Python send simple HTML email with SMTP

Posted: April 1, 2016 in Python
Tags:

Hi, below are the basic setting for sending email with SMTP in Python:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart('alternative')
msg['From'] = 'flakesns@gmail.com'
msg['To'] = 'client@yahoo.com'
msg['Subject'] = 'Basic SMTP email with Python'
text = "Test body email"

html = """\
 <html>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <head>Test simple HTML email with Python!</head>
 <body>
 <p>Hi!<br></p>
 """

html += "<p>Test body email with Python</p>"

html += """
 </body>
 </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.
msg.attach(part1)
msg.attach(part2) mailserver = smtplib.SMTP('mail.gmail.com',587) 

# identify ourselves to smtp gmail client 
mailserver.ehlo() 
# re-identify ourselves as an encrypted connection 
mailserver.ehlo() 
mailserver.login('flakesns@gmail.com', 'your_email_password_here') 
mailserver.sendmail('flakesns@gmail.com','client@yahoo.com',msg.as_string()) 
mailserver.quit()

You can download my python project at https://github.com/flakesns/python-example

Credit to : http://stackoverflow.com/questions/64505/sending-mail-from-python-using-smtp

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s