Over a million developers have joined DZone.

Python : Send A Mail (text), With Attachments

DZone's Guide to

Python : Send A Mail (text), With Attachments

· ·
Free Resource

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

def sendMail(to, subject, text, files=[],server="localhost"):
    assert type(to)==list
    assert type(files)==list
    fro = "Expediteur 

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

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))

    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, to, msg.as_string() )



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}