Friday, February 6, 2009

Sending E-Mail using Python

Well, it's really easy, all you need to do is build up a MIME message using the Python "email" library.

I am using the "alternative" multipart content type, which allows be to enter both text content and HTML content, and display the supported content type (which will of course almost always be HTML, but there are a lot of guys who still use text clients to read emails apparently).

I also used a small line in the example that convert from simple text to HTML.

Here is a sample code:


#!/usr/bin/python
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# We are using the local SMTP server
MAIL_SERVER = "localhost"

class Mailer:
def __init__(self):
self.mail_server = MAIL_SERVER

def send_raw_email(self, mail_from, mail_to, data):
smtp = smtplib.SMTP(self.mail_server)
smtp.sendmail(mail_from, mail_to, data)
smtp.quit()

def send_email(self, mail_from, mail_to, subject, text_message, html_message='', images=[]):
# Initialize MIME message
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = mail_from
if type(mail_to) is str:
msg["To"] = mail_to
else:
msg["To"] = ", ".join(mail_to)

text = MIMEText(text_message)
msg.attach(text)

if html_message:
html = MIMEText(html_message, "html")
msg.attach(html)

for image in images:
image = MIMEImage(open(image, "rb"))
msg.attach(image)

self.send_raw_email(mail_from, mail_to, msg.as_string())

if __name__ == '__main__':
mailer = Mailer()

subject = "This is the subject"
message = "This is the message"

html = "<html dir="'ltr'"><body>%s</body></html>" % message.replace("\n", "<br/>")
mailer.send_email("admin@myserver.com", "recipient@example.com", subject, message, html)

No comments: