Monday, March 12, 2012

How to Use JangoSMTP from a Python Script

Like many other programming languages, Python provides a built-in library for sending SMTP emails. After you import smtplib, all you have to do is instantiate a MIMEMultipart object to hold email information, then send the message via smtplib.SMTP.

This example demonstrates how to set up and send an email from a Python script using JangoSMTP. Download the source code for this example, insert your own JangoSMTP username/password/etc and start sending tracked emails today!

# create the message object
msg = MIMEMultipart('alternative')
msg['Subject'] = "JangoSMTP from Python Test"
msg['From'] = FromAddress
msg['To'] = ToAddress
# Create a plain-text and an HTML version of the message
text = "This is a plain text email sent from a python program!"
html = """\
      This is an html email sent from a <b>python</b> program!
# JangoSMTP credentials
username = "Your JangoSMTP Username"
password = "Your JangoSMTP Password"

# store both parts of the email
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# Open a connection to the JangoSMTP server
s = smtplib.SMTP('', 25)
# Authenticate
s.login(username, password)
# send the email
s.sendmail(FromAddress, ToAddress, msg.as_string())