Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


msg['Subject'] = input('Enter your email subject: ')
message = input('Enter your email message. Press Enter when
finished. ')
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
# create smtp session
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.set_debuglevel(1)
session.ehlo()
session.starttls()
session.ehlo
password = getpass.getpass(prompt="Enter you email password:
")
# login to server
session.login(sender, password)
# send mail
session.sendmail(sender, recipient, msg.as_string())
print("You email is sent to {0}.".format(recipient))
session.quit()

if __name__ == '__main__':
sender = input("Enter sender email address: ")
recipient = input("Enter recipeint email address: ")
send_email(sender, recipient)

The preceding code is similar to our first example, except for the authentication to
the server. In this case, the SMTP user is authenticated against the server. If we run
the script after turning on the SMTP debugging, then we would be seeing an output
similar to the following:


$ python3 smtp_mail_sender_tls.py


Enter sender email address: [email protected]


Enter recipeint email address: [email protected]


Enter your email subject: Test email


Enter your email message. Press Enter when finished. This is a test
email that can be ignored.


After the user input, communication with the server will begin. It will start by the
ehlo() method. In response to this command, the SMTP server will send a few
response lines with the return code 250. This response will include the features
supported by the server.

Free download pdf