python发送邮件带多个附件代码
Sonder
2023-05-04
1921字
5分钟
浏览 (1.2k)
成功展示:
附件目录:
# ! /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 = ['qq814029073@163.com'] # 收件人列表,以英文逗号分隔
mail_host = "smtp.qq.com" # 使用的邮箱的smtp服务器地址,这里是163的smtp地址
mail_user = "814029073@qq.com" # 用户名
mail_pass = "xxx" # 授权码,不是密码,授权码要在邮箱设置中获取
# 参数:收件人,主题,正文,文件名集合(可发送多个文件),文件路径(文件在同一个路径)
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:
pathStr = file if len(path) == 0 else path + '/' + file # 三元表达式 如果path为空就取当前路径的文件
if os.path.isfile(pathStr):
# 构造附件
att = MIMEText(open(pathStr, '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('top200111111', '这里是内容', files, '') # 发送/home/data文件夹下面两个文件