Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.
Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.
I heard that getpass.getpass()
can be used to hide the input.
Here is my code:
import smtplib
import getpass
import sys
print('Starting...')
SERVER = "localhost"
FROM = "[email protected]"
while True:
password = getpass.getpass()
try:
smtpObj = smtplib.SMTP(SERVER)
smtpObj.login(FROM, password)
break
except smtplib.SMTPAuthenticationError:
print("Wrong Username/Password.")
except ConnectionRefusedError:
print("Connection refused.")
sys.exit()
TO = ["[email protected]"]
SUBJECT = "Hello!"
TEXT = "msg text"
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")
But when I run my code, here is the output:
Starting...
/Nothing else appears/
I know the default prompt for getpass()
is 'Password:'
but I get the same result even when I pass it a prompt string.
Any suggestions?
EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.
The getpass() function prints a prompt then reads input from the user until they press return. The input is passed back as a string to the caller. The default prompt, if none is specified by the caller, is “Password:”. The prompt can be changed to any value your program needs.
getpass.getpass(prompt='Password: ', stream=None) The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.
There are two functions defined in getpass module of Python's standard library. They are useful whenever a terminal based application needs to be executed only after validating user credentials.
For PyCharm 2018.3 Go to 'Edit Configurations' and then select 'Emulate terminal in output console'.
Answer provided by Abhyudaya Sharma
The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by getpass
)
Running the code via a command prompt should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With