Python includes several modules in the standard library for working with emails and email servers.
Sending mail is done with Python'ssmtplib
using an SMTP (Simple Mail Transfer Protocol) server. Actual usage varies depending on complexity of the email and settings of the email server, the instructions here are based on sending email through Google's Gmail.
The first step is to create an SMTP object, each object is used for connection with one server.
importsmtplibserver=smtplib.SMTP('smtp.gmail.com',587)
The first argument is the server's hostname, the second is the port. The port used varies depending on the server.
Next, we need to do a few steps to set up the proper connection for sending mail.
server.ehlo()server.starttls()server.ehlo()
These steps may not be necessary depending on the server you connect to. ehlo() is used forESMTP servers, for non-ESMTP servers, use helo() instead. See Wikipedia's article about theSMTP protocol for more information about this. The starttls() function startsTransport Layer Security mode, which is required by Gmail. Other mail systems may not use this, or it may not be available.
Next, log in to the server:
server.login("youremailusername","password")
Then, send the mail:
msg="\nHello!"# The \n separates the message from the headers (which we ignore for this example)server.sendmail("you@gmail.com","target@example.com",msg)
Note that this is a rather crude example, it doesn't include a subject, or any other headers. For that, one should use theemail
package.
email
packagePython's email package contains many classes and functions for composing and parsing email messages, this section only covers a small subset useful for sending emails.
We start by importing only the classes we need, this also saves us from having to use the full module name later.
fromemail.mime.textimportMIMETextfromemail.mime.multipartimportMIMEMultipart
Then we compose some of the basic message headers:
fromaddr="you@gmail.com"toaddr="target@example.com"msg=MIMEMultipart()msg['From']=fromaddrmsg['To']=toaddrmsg['Subject']="Python email"
Next, we attach the body of the email to the MIME message:
body="Python test mail"msg.attach(MIMEText(body,'plain'))
For sending the mail, we have to convert the object to a string, and then use the same procedure as above to send using the SMTP server..
importsmtplibserver=smtplib.SMTP('smtp.gmail.com',587)server.ehlo()server.starttls()server.ehlo()server.login("youremailusername","password")text=msg.as_string()server.sendmail(fromaddr,toaddr,text)
If we look at the text, we can see it has added all the necessary headers and structure necessary for a MIME formatted email. SeeMIME for more details on the standard:
|