Showing posts with label python attachment email. Show all posts
Showing posts with label python attachment email. Show all posts

Wednesday, August 13, 2014

Python send plain/html email with attachment using smtp


import os
import tempfile
import mimetypes

from email.Utils import COMMASPACE, formatdate
from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEAudio import MIMEAudio
from email import Encoders


SMTPserver = 'smtp.mail.yahoo.com';
sender =     'some.name@yahoo.com';
destination = ['some.name@domain.com'];

USERNAME = "some.name@yahoo.com";
PASSWORD = "some.password";

contentHtml = """\
<b>Html message</b>
<div><span style='color: red'>Span with color red</span></div>
<div><span style='color: blue'>Span with color blue</span></div>
""";

contentPlain = 'Plain message';

contentAsPlainTextFile = 'Content as plain text file.';

subject = "Sent from Python";

conn = None;
try:
    msg = MIMEMultipart()
    msg['Subject'] = subject;
    msg['From'] = sender;
    msg['To'] = COMMASPACE.join(destination);
    msg['Date'] = formatdate(localtime=True);

    #Typical values for text_subtype are plain, html, xml
    msg.attach( MIMEText(contentHtml, 'html') );
    msg.attach( MIMEText(contentPlain, 'plain') );

    directory = os.path.dirname(os.path.realpath(__file__))
    files = [];
    files.append(os.path.join(directory, 'mail.simple.py'));
    files.append(os.path.join(directory, 'royal.jpg'));
    files.append(os.path.join(directory, 'audio.rm'));
    files.append(os.path.join(directory, 'xml7.xml'));

    tempdirectory = tempfile.mkdtemp()
    tempfilelocal = os.path.join(tempdirectory, 'Custom Text As Attachment.txt');
    tempfilelocal = open(tempfilelocal, 'w+b');
    tempfilelocal.write(contentAsPlainTextFile);
    tempfilelocal.seek(0);
    tempfilelocal.close();
    files.append(tempfilelocal.name);

    for fullpath in files:
        if not os.path.isfile(fullpath):
            continue;
        ctype, encoding = mimetypes.guess_type(fullpath);
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream';
        maintype, subtype = ctype.split('/', 1);
        if maintype == 'text':
            fp = open(fullpath);
            msgpart = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(fullpath, 'rb')
            msgpart = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(fullpath, 'rb')
            msgpart = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(fullpath, 'rb')
            msgpart = MIMEBase(maintype, subtype)
            msgpart.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msgpart)
        # Set the filename parameter
        msgpart.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fullpath))
        msg.attach(msgpart);

    conn = SMTP(SMTPserver);
    conn.set_debuglevel(False);
    conn.login(USERNAME, PASSWORD);
    conn.sendmail(sender, destination, msg.as_string());
    print("Mail sent.");
except Exception, exc:
    print( "Mail send failed: %s" % str(exc) );
finally:
    if conn is not None:
        conn.close()
        print("Connection closed.");

If server name and credentials are correct, you will receive email as below. In my case, it is my gmail inbox.