How to send HTML email in body using Python

# Import smtplib to provide email functions
import smtplib

# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Define email addresses to use
addr_to = ‘’
addr_from = ‘’

# Define SMTP email server details
smtp_server = ‘’
smtp_user = ‘’
smtp_pass = ‘1234567889’

# Construct email
msg = MIMEMultipart(‘alternative’)
msg[‘To’] = addr_to
msg[‘From’] = addr_from
msg[‘Subject’] = ‘Test Email From RPi’

# Create the body of the message (a plain-text and an HTML version).
text = “This is a test message.\nText and html.”
html = “””\

This is a test message.

Text and HTML


# Record the MIME types of both parts – text/plain and text/html.
part1 = MIMEText(text, ‘plain’)
part2 = MIMEText(html, ‘html’)

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.

# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server)
s.sendmail(addr_from, addr_to, msg.as_string())

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: