User Tools

Site Tools


coding:python:sendmail

Send Email with Python

A small function for sending mails with attachments
Works with Python3

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
 
 
def send_mail(send_from, send_to, subject, text, server, files=[], port=None, username=None, password=None, tls=None):
    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:
        with open(f, 'rb') as data:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(data.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
        msg.attach(part)
 
    smtp = smtplib.SMTP(server, port)
    smtp.set_debuglevel(1)
    if tls:
        smtp.starttls()
    if username:
        smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()
coding/python/sendmail.txt · Last modified: 2019/01/30 12:57 by karloff