import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
"""
*****************************第三方服务地址*************************
协议 服务器地址 服务器端口号(常规) 服务器端口号(加密)
POP3 pop.exmail.qq.com 110 995
IMAP imap.exmail.qq.com 143 993
SMTP smtp.exmail.qq.com 25 465
"""
mail_host = "smtp.exmail.qq.com"
mail_user = "xxxx@xxx.com"
mail_pass = "xxxxx"
# 发送/接受地址
sender = "xxxx@xxx.com"
receivers = ['xxxx@xxx.com']
# ①发送html文件
message_msg = """
<p>Python SMTP 邮件发送TEST...</p>
<p><a href="http://www.baidu.com">这是一个链接</a></p>
"""
# ②发送附件类
message = MIMEMultipart()
message['From'] = Header("发送者", 'utf-8')
message['To'] = Header("接收者", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText(message_msg, 'html', 'utf-8'))
# ③构造附件1
att1 = MIMEText(open('SMTP_Test1.zip', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="SMTP_Test1.zip"'
message.attach(att1)
# ④构造附件2
att2 = MIMEText(open('SMTP_Test2.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="SMTP_Test2.txt"'
message.attach(att2)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
****************************************执行结果**************************************