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
def main(reactor):
me = 'foo@bar.com'
to = 'foobar@baz.com'
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'))
print(message)
# more info on parameters (auth, forced tls,..) see twisted api docs
d = sendmail('localhost', me, to, message, port=25)
d.addBoth(print)
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 ;)
Share on Twitter Share on Facebook
Comments
There are currently no comments
New Comment