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
# https://stackoverflow.com/questions/882712/sending-html-email-using-python <- multipart example
me = 'email@example.com'
to = 'firstname.lastname@example.org'
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
# more info on parameters (auth, forced tls,..) see twisted api docs
d = sendmail('localhost', me, to, message, port=25)
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 ;)Share on Twitter Share on Facebook