Send email by Python Example

See also:

send-email.py

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate


def send_mail(send_from, send_to, subject, text="", files=None,
              server="smtp.office365.com"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)


    smtp = smtplib.SMTP(server,587)
    smtp.starttls()
    smtp.login('user@i88.ca','password')
    #smtp.set_debuglevel(True) # show communication with the server
    try:
     smtp.sendmail(send_from, send_to, msg.as_string())
    finally:
     smtp.close()

Popular posts from this blog

How to get Active Transactions and Locks from MySQL

Example of a PAC file

How to delete / clear queue of PowerMTA