[Python] 纯文本查看 复制代码
import smtplib # smtplib 用于邮件的发信动作
from email.mime.text import MIMEText # email 用于构建邮件内容
from email.header import Header # Header 用来构建邮件头
from email.mime.multipart import MIMEMultipart # 用于实例化附件(处理多种形态的邮件主体我们需要 MIMEMultipart 类)
# 邮件构建
sender = "*******@itcast.cn" # 发送方
password = "*****" # smtp服务密码
subject = "滴滴答答" # 邮件标题
content = "新年快乐!" # 文本内容
recver = "*******@itcast.cn" # 接收方
# content 发送内容 "plain"文本格式 utf-8 编码格式
message = MIMEText(content, "plain", "utf-8")
message['Subject'] = subject # 邮件标题
message['To'] = recver # 收件人
message['From'] = sender # 发件人
# 构造文件附件1
attr1 = MIMEText(open(files, 'rb').read(), 'base64', 'utf-8')
attr1["content_Type"] = 'application/octet-stream'
# attr1["Content-Disposition"] = "attachment; filename=Header({}, 'utf-8').encode()".format('你好') # 表示这是附件,名字是啥
# 解决附件中文名称乱码问题
attr1.add_header('Content-Disposition', 'attachment', filename=Header(file_name, 'utf-8').encode())
message.attach(attr1)
# 构造图片附件2
att2 = MIMEText(open('./1.png', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="12.jpg"'
message.attach(att2)
# 构造html附件3
att3 = MIMEText(open('./2.html', 'rb').read(), 'base64', 'utf-8')
att3["Content-Type"] = 'application/octet-stream'
att3["Content-Disposition"] = 'attachment; filename="boke.html"'
message.attach(att3)
smtp = smtplib.SMTP_SSL("smtp.263.com", 465) # 实例化smtp服务器
smtp.login(sender, password) # 发件人登录
smtp.sendmail(sender, [recver], message.as_string()) # as_string 对 message 的消息进行了封装
smtp.close()