Sending Emails in Python With SMTP

, , Comments Off on Sending Emails in Python With SMTP

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.

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.

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 while you’re logged in to your Google account, and “Allow less secure apps”. See screenshot below.

Create and Send a Simple Email

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 MIMEMultipart message object and attach the relevant headers to it, i.e. From, To, and Subject.
  • Attach the message to the message MIMEMultipart object.
  • Finally, send the message.

Read full tutorial at code.tutsplus