Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

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.

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.

import smtplib

server = smtplib.SMTP(host='host_address',port=your_port)

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.

Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

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.

This process is as simple as shown below.

# import necessary packages

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

# create message object instance
msg = MIMEMultipart()


message = "Thank you"

# setup the parameters of the message
password = "your_password"
msg['From'] = "your_address"
msg['To'] = "to_address"
msg['Subject'] = "Subscription"

# add in the message body
msg.attach(MIMEText(message, 'plain'))

#create server
server = smtplib.SMTP('smtp.gmail.com: 587')

server.starttls()

# Login Credentials for sending the mail
server.login(msg['From'], password)


# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())

server.quit()

print "successfully sent email to %s:" % (msg['To'])

Note that the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.

Create and Send an Email With an Attachment

In this example, we are going to send an email with an image attachment. The process is similar to sending a plain text email.

  • 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.
  • Read and attach the image to the message MIMEMultipart object.
  • Finally, send the message.
# send_attachment.py
# import necessary packages
from email.mime.multipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.mime.text import MIMEText
import smtplib

# create message object instance
msg = MIMEMultipart()


# setup the parameters of the message
password = "your_password"
msg['From'] = "your_address"
msg['To'] = "to_address"
msg['Subject'] = "Photos"

# attach image to message body
msg.attach(MIMEImage(file("google.jpg").read()))


# create server
server = smtplib.SMTP('smtp.gmail.com: 587')

server.starttls()

# Login Credentials for sending the mail
server.login(msg['From'], password)


# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())

server.quit()

print "successfully sent email to %s:" % (msg['To'])

The MIMEImage class is a subclass of MIMENonMultipart which is used to create MIME message objects of image types. Other available classes include
MIMEMessage and MIMEAudio.

Create and Send HTML Emails

The first thing we are going to do is create an HTML email template.

Create an HTML Template

Here is the HTML code for the template, and it contains two table columns each with an image and preview content. If you prefer a ready-made, professional solution, grab our best email templates. We have a number of responsive options with easy-to-customize features to get started with.



   
   Tutsplus Email Newsletter
   


View in Browser

How to Get Up and Running With Vue

In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we’ll learn how to get Vue up..

Introducing Haiku: Design and Create Motion

With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..

Design better experiences for web & mobile

Unsubscribe | Tweet | View in Browser

The template will finally look like this when complete:

The HTML Template

Below is the script for sending an email with HTML content. The content of the template will be our email message.

import smtplib
import email.message
server = smtplib.SMTP('smtp.gmail.com:587')

email_content = """




   
   Tutsplus Email Newsletter
   





View in Browser

How to Get Up and Running With Vue

In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we will learn how to get Vue up..

Introducing Haiku: Design and Create Motion

With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..

Design better experiences for web & mobile

Unsubscribe | Tweet | View in Browser

""" msg = email.message.Message() msg['Subject'] = 'Tutsplus Newsletter' msg['From'] = 'youraddress' msg['To'] = 'to_address' password = "yourpassword" msg.add_header('Content-Type', 'text/html') msg.set_payload(email_content) s = smtplib.SMTP('smtp.gmail.com: 587') s.starttls() # Login Credentials for sending the mail s.login(msg['From'], password) s.sendmail(msg['From'], [msg['To']], msg.as_string())

Execute your code, and if no error occurs, then the email was successful. Now go to your inbox and you should see your email as HTML content nicely formatted.

See more from Net Tuts
Instructor Lead On-Demand Learning Courses - August Big $10 Sitewide Extravaganza All Pro Web Designs and Udemy are happy to offer this special to you, good only on dates: 08/21-08/31 Act Now!

Leave a Reply