python发送邮件带多个附件代码

# ! /usr/bin/env python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
import os

mailto_list = ['[email protected]']  # 收件人列表,以英文逗号分隔
mail_host = "smtp.163.com"  # 使用的邮箱的smtp服务器地址,这里是163的smtp地址
mail_user = "*****@163.com"  # 用户名
mail_pass = "******"  # 授权码,不是密码,授权码要在邮箱设置中获取


# 参数:收件人,主题,正文,文件名集合(可发送多个文件),文件路径(文件在同一个路径)
def send_mail(sub, content, files, path):
    me = sub + "<" + mail_user + ">"
    msg = MIMEMultipart()
    msg.attach(MIMEText(content, _subtype='html', _charset='utf-8'))
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ",".join(mailto_list)  # 将收件人列表以‘,’分隔
    for file in files:
        if os.path.isfile(path + '/' + file):
            # 构造附件
            att = MIMEText(open(path + '/' + file, 'rb').read(), 'base64', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att.add_header("Content-Disposition", "attachment", filename=("gbk", "", file))
            msg.attach(att)
    try:
        server = smtplib.SMTP()
        if mail_host == 'smtp.gmail.com':
            server.connect(mail_host, port=587)  # 连接服务器
            server.starttls()
        else:
            server.connect(mail_host)
        server.login(mail_user, mail_pass)  # 登录操作
        server.sendmail(me, mailto_list, msg.as_string())
        server.close()
        print('Mail sent successfully')
        return True
    except Exception as e:
        print('Mail sent failed')
        print(sys.exc_info()[0], sys.exc_info()[1])
        return False

if __name__ == '__main__':
    files = ['1.xlsx', '2.txt']
    send_mail('国内top200应用', '国内top200应用', files, '/home/data')  # 发送/home/data文件夹下面两个文件

你可能感兴趣的:(python)