来了哈:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 使用smtp服务发带附件的邮件
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os
if __name__ == '__main__':
host = "smtp.*****.com"
port = 25
mail_user = "******@*****.com"
mail_pass = "******"
toaddrs = ["614027762@qq.com"]
# 附件
textApart = MIMEText('这是有附件的')
imageFile = os.path.abspath('../res/1.png')
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename="1.png")
pdfFile = os.path.abspath('../res/分析方法.pdf')
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment', filename="方法.pdf")
zipFile = os.path.abspath('../res/do.zip')
zipApart = MIMEApplication(open(zipFile, 'rb').read())
zipApart.add_header('Content-Disposition', 'attachment', filename="do.zip")
message = MIMEMultipart()
message.attach(textApart)
message.attach(imageApart)
message.attach(pdfApart)
message.attach(zipApart)
message['From'] = Header("明", 'utf-8')
message['To'] = Header("明; 波", 'utf-8')
subject = '【报告测试进行中】'
message['Subject'] = Header(subject, 'utf-8')
try:
server = smtplib.SMTP()
server.connect(host, port) # 链接服务器;25 为 SMTP 端口号
server.login(mail_user, mail_pass)
server.sendmail(mail_user, toaddrs, message.as_string())
print("success")
server.quit()
except smtplib.SMTPException as e:
print("error:", e)
完了哈。*号部分改成你自己的。附件文件自己创造。