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 = ['XXXX@163.com']  # 收件人列表,以英文逗号分隔
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文件夹下面两个文件
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值