Commit efc039ea authored by Hamaker, Alec's avatar Hamaker, Alec
Browse files

Added support for sending attachments with mail.py

parent 31bca741
Loading
Loading
Loading
Loading
+16 −1
Original line number Diff line number Diff line
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from common.env import check_environment as ce
from common.logz import create_logger


def send_email(subject, text):
def send_email(subject, text, files=None):
    """ Send email to the EMAIL_RECIPIENTS env variable with the given subject
        and message body from the EMAIL_SENDER address. Email debug level is
        controlled with the EMAIL_DEBUG_LEVEL environmental variable and
@@ -36,6 +38,19 @@ def send_email(subject, text):
    msg['To'] = to_address
    msg['Subject'] = subject
    msg.attach(MIMEText(text, 'plain'))
    # if attachment files have been passed..
    if isinstance(files, list) and len(files) > 0:
        for f in files:
            if os.path.isfile(f):
                with open(f, 'rb') as att_file:
                    part = MIMEApplication(att_file.read())
                part['Content-Disposition'] = ('attachment; filename='
                                               f'"{os.path.basename(f)}"')
                msg.attach(part)
            else:
                logger.error(f'Failed to attach file {f}. {f} is not a file.')
    else:
        logger.error(f'Failed to attach files {files}')
    logger.info(f'Sending email to {to_address} from {from_address}')
    try:
        with smtplib.SMTP(smtp_address, smtp_port) as server: