第一篇博客!参考链接⬅
在书上看了用SMTP模块发邮件,试过之后发现并没有什么用。163邮箱开启了SMTP服务后,登陆了发送的时候却被拒收了。
找了前人的资料,发现被过期的教程害死了。
以下代码有效:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
#全部为python内置,不需要安装第三方模块
receivers = ["receivers@163.com"]
sender = "sender@163.com"
mail_pass = "password"
mail_subject = "python发送邮件测试" # 邮件的标题
mail_context = "这是邮件内容"
msg = MIMEMultipart()
msg["From"] = sender # 发件人
msg["To"] = ";".join(receivers) # 收件人
msg["Subject"] = mail_subject # 邮件标题
# 邮件正文
msg.attach(MIMEText(mail_context, 'plain', 'utf-8'))
#图片附件
#不同的目录下要写全文件路径
with open('test.jpg','rb') as picAtt:
msgImg = MIMEImage(picAtt.read())
msgImg.add_header('Content-Disposition', 'attachment', filename='你.jpg')
#msgImg.add_header('Content-ID', '<0>')
#msgImg.add_header('X-Attachment-Id', '0')
msg.attach(msgImg)
# 构造附件
att = MIMEText(open('test.txt', "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
# 附件名称为中文时的写法
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "测试结果.txt"))
# 附件名称非中文时的写法
# att["Content-Disposition"] = 'attachment; filename="test.html")'
msg.attach(att)
try:
# 启动网易SMTP服务,端口465
smtpObj = smtplib.SMTP_SSL('smtp.163.com', 465)
# 登陆账号
smtpObj.login('sender@163.com', 'your_password')
# 发送
smtpObj.sendmail(sender, receivers, msg.as_string())
print('Success!')
# 退出登录
smtpObj.quit()
except smtplib.SMTPException as e:
print(e)
如果不需要附件,删除附件的代码块就行。
注:密码最好不保存在代码中,而是使用时输入