Skip to content

Instantly share code, notes, and snippets.

@coderfi
Created November 3, 2014 22:03
Show Gist options
  • Save coderfi/800d6344ee9ac0fc21e3 to your computer and use it in GitHub Desktop.
Save coderfi/800d6344ee9ac0fc21e3 to your computer and use it in GitHub Desktop.
python xlsx email attachment (with luigi helpers)
from luigi import notifications, configuration
import smtplib
import email
import datetime
def send_email(subject, message, xlsx_fn, sender, recipients):
if not isinstance(recipients, (list, tuple, set)):
recipients = [ recipients ]
config = configuration.get_config()
smtp_ssl = config.getboolean('core', 'smtp_ssl', False)
smtp_host = config.get('core', 'smtp_host', 'localhost')
smtp_port = config.getint('core', 'smtp_port', 0)
smtp_local_hostname = config.get('core', 'smtp_local_hostname', None)
smtp_timeout = config.getfloat('core', 'smtp_timeout', None)
kwargs = dict(host=smtp_host, port=smtp_port, local_hostname=smtp_local_hostname)
if smtp_timeout:
kwargs['timeout'] = smtp_timeout
smtp_login = config.get('core', 'smtp_login', None)
smtp_password = config.get('core', 'smtp_password', None)
smtp = smtplib.SMTP(**kwargs) if not smtp_ssl else smtplib.SMTP_SSL(**kwargs)
if smtp_login and smtp_password:
smtp.login(smtp_login, smtp_password)
msg_root = notifications.generate_email(sender, subject, message, recipients, image_png=None)
msg_attach = email.mime.base.MIMEBase('application', 'vnd.ms-excel')
with open(xlsx_fn, 'rb') as f:
msg_attach.set_payload(f.read())
email.encoders.encode_base64(msg_attach)
msg_attach.add_header('Content-Disposition','attachment;filename=%s_%s'
% (datetime.datetime.now().strftime("%Y%m%dT%H%M%S"),
xlsx_fn))
msg_root.attach(msg_attach)
smtp.sendmail(sender, recipients, msg_root.as_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment