【python】126邮箱自动发送邮件(带附件)

前置步骤:
1、登录126邮箱,开启POP3/SMTP服务


image.png

2、新增授权码(供登录使用)


image.png

3、smtpObj.login登录邮箱(邮箱在本地无须次步骤)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 第三方 SMTP 服务
mail_host = 'smtp.126.com'  # 设置服务器
mail_username = 'b***[email protected]'  # 用户名
mail_auth_password = "x"  # 授权密码
sender = 'b***[email protected]'
# receivers = '[email protected]'         # 一个收件人
receivers = '[email protected],[email protected]'  # 多个收件人

mail_msg = """

Python 邮件发送测试...

这是一个链接

""" message = MIMEMultipart() message['From'] = sender message['To'] = receivers message['Subject'] = "这里是邮件主题" message.attach(MIMEText(mail_msg, 'html', 'utf-8')) att1 = MIMEText(open('1.txt', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="1.txt"' message.attach(att1) try: smtpObj = smtplib.SMTP(mail_host, 25) # 生成smtpObj对象,使用非SSL协议端口号25 smtpObj.login(mail_username, mail_auth_password) # 登录邮箱 # smtpObj.sendmail(sender, receivers, message.as_string()) # 发送给一人 smtpObj.sendmail(sender, receivers.split(','), message.as_string()) # 发送给多人 print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")

最终效果如下:


image.png

你可能感兴趣的:(【python】126邮箱自动发送邮件(带附件))