This Tutorial is based on (semi) automating the task of sending emails using the SMTP server in Python.
See Also: How to extract emails from Email Account in Python
What is the Python SMTP Module?
The rules of the internet are defined by the many protocols used on it. For instance, we have HTTP which is used in the transfer of web pages. Likewise, we have a protocol called SMTP or Simple Mail Transfer Protocol for sending emails across the internet.
The Python SMTP Library defines how email messages should be formatted, encrypted, and relayed between mail servers, and any other small details that your computer has to deal with.
The protocol for receiving emails is different. You can either use POP3 or IMAP. Since IMAP is more advanced and flexible, we use it to demonstrate how to receive emails. Check it out if you’re interested.
Note: If you are not connected to the Internet, Python will raise a socket.gaierror: [Errno 11004] getaddrinfo failed or similar exception.
Installation
Run the following command in the command prompt to install the smtplib
library. If you’re having some trouble refer to our Installation guide for Python.
pip install smtplib
Once this is done, import smtplib into your python module using the import smtplib
statement.
Account Settings
There is a very strong likelihood, that if you try using a gmail account with smtplib, then it will not allow you to sign in. This is because of security features in place, designed to prevent sign-in from unknown sources and apps.
The same goes for any other email service provider who may have similar checks in place. What you need to do, is either modify your security settings, or authorize your python script to have access to your email account.
The first method is a teensy-bit unsafe, because you are lowering the security level on your account, but it’s easier to do. The second method is the more official way. As a third option, you can just create a new account, and then lower the security settings on that instead. (So even in the worst case scenario, your main account is perfectly safe)
If you have a gmail account, follow this link to change your settings. Alternatively, if you want to take more official route, you can follow this tutorial on how to setup Authorization with the Gmail API.
Setting up a Connection with SMTP
The first step is to create a SMTP object that you can use to execute various methods and perform specific functions.
smtpobject = smtplib.SMTP('smtp.gmail.com', 587)
The first parameter here, defines the server name we wish to connect to. If we want to use a gmail account, then we use ‘smtp.gmail.com
‘. Similarly, different providers have different server names. Refer to the end of the tutorial for a complete list.
The port 587 is the port used by TLS, the encryption standard. May be different in some rare occasions.
Once the SMTP()
connection has been made, you can start the TLS session using the starttls()
function.
smtpobject.starttls()
If the TLS call fails, you can always use SSL, another encryption protocol. It operates on the 465 port. You can call it using the SMTP_SSL()
function.
smtpobject = smtplib.SMTP_SSL('smtp.gmail.com', 465)
Now that we’ve established a connection and created end-to-end encryption we can begin safely with the login process. Use the login() function which takes your email and password as it’s parameters.
smtpobject.login('[email protected]', 'password')
Sending an Email with SMTP
Finally, it’s time to use the sendmail()
function. It takes three parameters, your email, the recipent’s email and the message to be sent.
You can use the newline character “\n
” to to separate the lines in your message. Keep in mind that your email message must begin with "Subject: subject\n"
.
smtpobject.sendmail('[email protected]', '[email protected]',
'''Subject: Appreciation\n
Dear Contributor, Your contributed article is greatly appreciated''')
The return value from this function is a dictionary. If this dictionary is empty, it means your message was successfully sent to the recipient(s). Otherwise, there will be one key:value pair in the dictionary for each recipient the message failed to be sent.
Trying to stuff the whole message into a single function which also takes other parameters can be a bit messy. So we can store it in a separate variable first. Just remember to use multi-lines strings, where each new line represents a new line in the message. If you store it all in one consecutive line, it might put the whole text in the subject.
The complete code:
import smtplib
smtpobject = smtplib.SMTP('smtp.gmail.com', 587)
smtpobject.starttls()
smtpobject.login('[email protected]', 'password')
message = '''\
Subject: Appreciation\n
Dear Contributor, Your contributed article is greatly appreciated.
Looking forward to future contributions!'''
smtpobject.sendmail('[email protected]', '[email protected]', message)
smtpobject.quit()
Once you’re done with everything we use the smtpobject.quit()
to end the connection.
SMTP Server Names for Email Providers
The table below shows the server names of each Email provider for the smtplib module. You’ll need these while connecting to your email account.
Email Provider | SMTP server name |
---|---|
Gmail | smtp.gmail.com |
Outlook.com/Hotmail.com | smtp-mail.outlook.com |
Yahoo Mail | smtp.mail.yahoo.com |
AT&T | smpt.mail.att.net (port 465) |
Comcast | smtp.comcast.net |
Verizon | smtp.verizon.net (port 465) |
This marks the end of our, “Sending Emails with Python SMTP” Article. Let us know if you have suggestions or contributions to make. Anything to help improve Coders Legacy is more than welcome.