Skip to content

Instantly share code, notes, and snippets.

@dpnova
Created April 7, 2011 10:15
Show Gist options
  • Save dpnova/907491 to your computer and use it in GitHub Desktop.
Save dpnova/907491 to your computer and use it in GitHub Desktop.
Email Mixin for Tornado - I can't remember who originally wrote this :(
#!/usr/bin/env python
import asyncore
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email.utils import formatdate
import logging
import smtplib
import smtpd
import time
from tornado.options import define
from tornado.options import options
from tornado.options import parse_command_line
import project.settings as settings
"""Simple outgoing email.
This module defines a Mixin class, MailMixin, to be used in
conjunction with web.RequestHandler. It adds a single method, send_mail
().
Additionally, running this module as a script will start a debugging
mail
server. Start your app as follows on your development machine:
./mail.py --smtp_port=2525 &
./application.py --smtp_port=2525 &
Mail messages sent using MailMixin.send_mail will be printed to stdout
along
with the usual Tornado request logging.
"""
class MailMixin(object):
def send_mail(self, sender, to, subject, body, html=None, attachments=[]):
"""Send an email.
If an HTML string is given, a mulitpart message will be generated with
plain text and HTML parts. Attachments can be added by providing as a
list of (filename, data) tuples.
"""
if html:
# Multipart HTML and plain text
message = MIMEMultipart("alternative")
message.attach(MIMEText(body, "plain"))
message.attach(MIMEText(html, "html"))
else:
# Plain text
message = MIMEText(body)
if attachments:
part = message
message = MIMEMultipart("mixed")
message.attach(part)
for filename, data in attachments:
part = MIMEBase("application", "octet-stream")
part.set_payload(data)
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment",
filename=filename)
message.attach(part)
message["Date"] = formatdate(time.time())
message["From"] = sender
message["To"] = COMMASPACE.join(to)
message["Subject"] = subject
server = smtplib.SMTP(settings.smtp_host, settings.smtp_port)
server.sendmail(sender, to, message.as_string())
server.quit()
#define("smtp_host", default="127.0.0.1", help="mail server host
#(default: 127.0.0.1)")
#define("smtp_port", default=25, help="mail server port (default: 25)",
#type=int)
#
#def main():
# """Starts a debugging mail server on the given host and port."""
# parse_command_line()
# server = smtpd.DebuggingServer(
# (options.smtp_host, options.smtp_port), None)
# asyncore.loop()
#
#if __name__ == "__main__":
# main()
@soiitaire
Copy link

Thanks. This helps me a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment