SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。Python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
使用Python发送带附件的邮件:
import time
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 第三方 SMTP 服务
mail_host = "smtp.exmail.qq.com" # 设置服务器
mail_user = "test@qq.com" # 用户名
mail_pass = "test" # 口令
sender = 'test@qq.com'
# 接收邮件,可设置为你的QQ邮箱或者其他邮箱
receivers1 = ['test@qq.com']
receivers2 = ['test2@qq.com']
# 创建一个带附件的实例
message = MIMEMultipart()
# 邮件正文内容
message.attach(MIMEText('测试', 'plain', 'utf-8'))
# # # ********************************** 邮件中第一个excel ***************************************************
att1 = MIMEText(open('name.txt', 'rb').read(), 'plain', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# # # 这里的filename可以任意写,写什么名字,邮件中显示什么名
att1["Content-Disposition"] = 'attachment; filename="test1"'
message.attach(att1)
# # # ********************************** 邮件中第二个excel ***************************************************
att2 = MIMEText(open('name.txt', 'rb').read(), 'plain', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
# # # 这里的filename可以任意写,写什么名字,邮件中显示什么名
att2["Content-Disposition"] = 'attachment; filename="test2"'
message.attach(att2)
# # # ********************************** -- end -- ***************************************************
message['From'] = Header("test@qq.com", 'utf-8')
message['To'] = Header("", 'utf-8')
subject = '测试'
message['Subject'] = Header(subject, 'utf-8')
# """imap.exmail.qq.com(使用SSL,端口号993) smtp.exmail.qq.com(使用SSL,端口号465)"""
try:
smtpObj = smtplib.SMTP_SSL(mail_host)
smtpObj.connect(mail_host, 465) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers1, message.as_string())
smtpObj.sendmail(sender, receivers2, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
网友评论