function, you must provide the user ID and password that you use to connect to your email server
using your normal email client. Usually they’re just your standard email address and password. To
make the connection secure, you should also use the starttls() method. The process looks like
this:
Click here to view code image
smtpsrtver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('myuserid', 'mypassword')
You may have noticed that the code uses the ehlo() method twice. Some email servers require the
client to re-introduce itself after switching to encrypted mode. Therefore, it’s a good idea to always
use the extra ehlo() method, which doesn’t break anything on servers that don’t need it.
After you establish the connection and login, you’re ready to compose and send your message. The
message must be formatted using the RFC2822 email standard, which requires the message to start out
with a To: line to identify the recipients, a From: line to identify the sender, and a Subject: line.
Instead of creating one huge text string with all that info, it’s easier to create separate variables with
that info and then “glue” them all together to make the final message, like this:
Click here to view code image
to = '[email protected]'
from = '[email protected]'
subject = 'This is a test'
header = 'To:' + to + '\n'
header = header + 'From:' + from + '\n'
header = header + 'Subject:' + subject + '\n'
body = 'This is a test message from my Python script!'
message = header + body
Now the message variable contains the required RFC2822 headers, plus the contents of the
message to send. It’s easy to change any of the individual parts, if needed.
Now you need to send the message and close the connection, as shown here:
Click here to view code image
smtpserver.sendmail(from, to, message)
smtpserver.quit()
To send the message, the sendmail() method also needs to know the from and to information. The
to variable can either be a single email address or a list object that contains multiple recipient email
addresses.
In the following Try It Yourself, you’ll write your own Python script to send email messages.
Try It Yourself: Send Email Messages
In the following steps, you’ll create a window application using the tkinter library
(see Hour 18, “GUI Programming”) to send an email message to one or more
recipients. Just follow these steps:
- Create the file script2001.py in the folder for this hour.
- Enter the code shown here in the script2001.py file: