Sending HTML-Embedded Emails With Python

Whether you need this for a practical reason or are just beginning to code, this is a great place to start.

Recently I was tasked with automating complex emails, and was lost for the longest time until I found that there are two modules built right in to python built for that very thing.

This can be done in 6 easy steps that I will walk through, but if you want just the code it can be found at the end.


1: Making your html message

Your message can be as complex or as simple as you want it to be, but for the purposes of this messages, we will just be sending an embedded link.

<html>
<body>
<p>
Hi!<br>
Here is the <a href="google.com">link</a> you wanted.
</p>
</body>
</html>

Be sure to save both your python script and your html file in the same folder.

2: Importing modules

This program uses SMTP(Simple Mail Transfer Protocol) and parts of the email module, both of which are built-in to python.

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

3: Create your mail object

The email module allows us to specify parts of the email, such as the subject line.

message = MIMEMultipart('Alternative')
message['From'] = 'from@gmail.com'
message['Subject'] = ''

Note: The ‘From’ portion of the email does not have to be your own email, it will show up as the contact name at the top of the email (ie. a company name).

4: Attach the html file to the mail object

html = open('Message.html').read()
message.attach(MIMEText(html, 'html'))

5: Open a connection to the email server

I am using gmail for this example, but you can replace gmail with the name of your email provider (ie. smtp.outlook.com).

server = stmplib.SMTP('smtp.gmail.com', 587)
server.startls()

6: Login and send the email

Now that everything’s set up, all thats left to do is login and send the email!

server.login('Username', 'Password')
server.sendmail('from@gmail.com', 'to@gmail.com', message.as_string())

Just The Code:

Python:

import smtp
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('Alternative')
message['To'] = 'to@gmail.com'
message['From'] = 'from@gmail.com'
message['Subject'] = ''
html = open('Message.html').read()
message.attach(MIMEText(html, 'html'))
server = stmplib.SMTP('smtp.gmail.com', 587)
server.startls()
server.login('Username', 'Password')
server.sendmail('from@gmail.com', 'to@gmail.com', message.as_string())

HTML:

<!-- The contents of the email are stored in this file -->
<html>
<body>
<p>
Hi!<br>
Here is the <a href="google.com">link</a> you wanted.
</p>
</body>
</html>

Thank you for reading! It really is that simple to get started with python and it’s modules. It’s just about playing around with code until it looks like you want it to and does what it should. Happy programming!