python发送带附件的邮件

Posted by zluckyH on October 11, 2019

一直想用python发邮件,终于把代码跑通了,以下代码可以发送带附件的邮件

# coding:utf-8

import smtplib
import os.path as op
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
import datetime
import sys


def send_mail(send_from, send_to, subject, message, files=[],
              server="localhost", port=587, username='', password='',
              use_tls=True):
    """Compose and send email with provided info and attachments.

    Args:
        send_from (str): from name
        send_to (list(str)): to name
        subject (str): message title
        message (str): message body
        files (list[str]): list of file paths to be attached to email
        server (str): mail server host name
        port (int): port number
        username (str): server auth username
        password (str): server auth password
        use_tls (bool): use TLS mode
    """
    assert isinstance(send_to, list)
    try:
        # python2 解决编码问题
        reload(sys)
        sys.setdefaultencoding('utf-8')
    except Exception as e:
        pass
        # python3 unicode,编码无忧
        # from imp import  reload
        # reload(sys)
        # sys.setdefaultencoding('utf-8')
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg['Accept-Language'] = 'zh-CN'
    msg['Accept-Charset'] = 'ISO-8859-1,utf-8'
    msg.attach(MIMEText(message,_charset='utf-8'))

    for path in files:
        part = MIMEBase('application', "octet-stream")
        with open(path, 'rb') as file:
            part.set_payload(file.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="{}"'.format(op.basename(path)))
        msg.attach(part)

    # smtp = smtplib.SMTP(server, port)
    smtp = smtplib.SMTP_SSL(server, port)

    if use_tls:
        smtp.starttls()
    smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

if __name__ =='__main__':
    send_from = '***@163.com'
    send_to = ['1****@qq.com']
    subject = 'hello world'
    message = 'Dear all,...'
    files = ['test.csv']
    server = 'smtp.163.com'
    port = 465
    username = '***@**.com'
    password = '******'
    use_tls = False
send_mail(send_from=send_from,send_to=send_to,subject=subject,message=message,files=files,server=server,port=port,username=username,password=password,use_tls=use_tls)


Gitalking ...