This tutorial will give an introduction to SMTP, a Python module used for sending mail. It will also demonstrate how to send different email types like simple text emails, emails with attachments, and emails with HTML content.
Introduction to SMTP
The Simple Mail Transfer Protocol (SMTP) handles sending and routing email between mail servers.
In Python, the
smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is how to create an SMTP object.
Create and Send a Simple Email
The following script will allow you to send an email via the Gmail SMTP server. However, Google will not allow logging in via
smtplib because it has flagged this type of login as “less secure”. To solve this, go to https://www.google.com/settings/security/lesssecureapps while you’re logged in to your Google account, and “Allow less secure apps”. See screenshot below.
We will follow the following steps to accomplish this process:
- Create an SMTP object for connection to the server.
- Log in to your account.
- Define your message headers and login credentials.
- Create a
MIMEMultipartmessage object and attach the relevant headers to it, i.e. From, To, and Subject.
- Attach the message to the message
- Finally, send the message.
Read full tutorial at code.tutsplus