jetz
8/5/2014 - 8:21 AM

Send email using Python

Send email using Python

#!/usr/bin/env python
# encoding: utf-8

import os.path
import smtplib

from email.utils import formataddr
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


hostname = ''
username = ''
password = ''
sender = ''


def send_email(recipients, subject, content, attachment=None, content_type='html'):
    recipients = [recipients] if isinstance(recipients, basestring) else list(recipients)

    msg = MIMEMultipart('related')

    text_msg = MIMEText(content, _subtype=content_type, _charset='UTF-8')
    msg.attach(text_msg)
    
    # HTML <img src="cid:test_id"/>
    img_msg = MIMEImage(open('test.png', 'rb').read())
    img_msg.add_header('Content-ID', '<test_id>')
    msg.attach(img_msg)

    if attachment:
        file_msg = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf8')
        file_msg["Content-Type"] = 'application/octet-stream'
        file_msg.add_header("Content-Disposition",
                            "attachment",
                            filename=os.path.basename(attachment))
        msg.attach(file_msg)

    msg['To'] = formataddr(('Admin', ';'.join(recipients)))
    msg['From'] = formataddr(('notice', sender))
    msg['Subject'] = Header(subject, charset='UTF-8')

    server = smtplib.SMTP(hostname)
    try:
        # server.set_debuglevel(True)
        server.ehlo()
        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo()

        server.login(username, password)
        server.sendmail(sender, recipients, msg.as_string())
    except Exception as e:
        raise e
    finally:
        server.quit()