Sending Multipart MIME Emails (html + text alternative) using python and twisted


I needed a way to send html + plain text alternative emails (based on templates ultimately) - preferrably using python. and since I always liked twisted i turned to that again.

Here's what I came up with after reading some other tutorials and manuals:

from twisted.mail.smtp import sendmail
from twisted.internet.task import react

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# <- multipart example

def main(reactor):
me = ''
to = ''

message = MIMEMultipart('alternative')
message['Subject'] = 'test email sent from twisted'
message['From'] = me
message['To'] = to
html = '<html><head /><body><p style="color: red;">This is an awesome email sent with twisted!</p></body></html>'
text = 'This is an awesome email sent with twisted! (plain text version)'

# according to RFC2046 the last part is preferred
message.attach(MIMEText(text, 'plain'))
message.attach(MIMEText(html, 'html'))

# more info on parameters (auth, forced tls,..) see twisted api docs
d = sendmail('localhost', me, to, message, port=25)
return d

react (main)

Pretty self explainatory I think. first we create a multipart mime object, add some headers, define our html text and palin text and then attach the 2 texts in the correct order tehn use twisted's sendmail method - and add print as callback for the deferred so the results just get printed out.

then start the reactor ;)

Current rating: 5


There are currently no comments

New Comment


required (not published)