导入模块
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
创建邮箱对象
Email = smtplib.SMTP()
连接服务器
Email.connect('smtp.qq.com', 25)
登录邮箱
Email.login('weicreate@qq.com', input('邮箱授权码:'))
添加正文
content = MIMEText(input('请输入邮件内容:'), 'plain', 'utf-8')
添加附件
file = MIMEText(open('excel.xlsx').read(), 'base64', 'utf-8')
file.add_header('Content-Disposition', 'attachment', filename='excel.xlsx')
创建复合邮件对象
msg = MIMEMultipart()
msg.attach(content)
msg.attach(file)
添加表头
msg['From'] = Header('weicreate')
obj = ['阿浩', ]
msg['To'] = Header(",".join(obj))
msg['Subject'] = Header('来自python的程序测试')
发送邮件
objMail = ['1243007569@qq.com', ]
try:
Email.sendmail('weicreate@qq.com', objMail, msg.as_string())
print('发送成功!')
except Exception as e:
print('发送失败:', repr(e))
Email.quit()
参考文件
smtplib模块.py