利用Python发送邮件
程序员文章站
2022-04-07 15:48:42
...
Python爬虫学习1
利用Python发送邮件
这是我第一次写博客记录我学习Python的过程。
一、配置邮箱环境
1、开启163的smtp服务器(绑定自己的手机),以便后面使用授权码发送邮件
2、查看SMTP服务器地址和端口,后面需要用到
具体代码
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
import os
os.chdir(r'C:\Users\Desktop') ##设置路径
##设置163邮箱环境,获取邮箱授权码,具体操作如下:https://blog.csdn.net/qlzy_5418/article/details/86661883
sender = '*******@163.com' ##发件人邮箱账号
receiver = '*********@qq.com' ##收件人邮箱账号
mail_msg = """
<p>这是一条测试链接</p>
<p><a href = "https://movie.douban.com/top250">请点击链接</a></p>
<p>若链接无法连接,请扫描下方图片进入:</p>
<p><img src = "cid:image1"></p>
"""
msg = MIMEMultipart()
msg['From'] = formataddr(['*********@163.com' , sender]) ##发件人邮箱名称,可直接用账号
msg['To'] = formataddr(['*********@qq.com' , receiver]) ##收件人邮箱名称,可直接用账号
msg['Subject'] = '测试邮件'
att1 = MIMEText(mail_msg , 'html' , 'utf-8')
att2 = MIMEText(open('test.txt','rb').read() , 'base64' , 'utf-8')
att2['Content-Type'] = 'application/octet-stream'
att2['Content-Disposition'] = 'attachment;filename = "test.txt"'
att3 = MIMEText(open('xixi.jpg','rb').read() , 'base64' , 'utf-8')
att3['Content-Type'] = 'application/octet-stream' ## 只能提交二进制,而且只能提交一个二进制,如果提交文件的话,只能提交一个文件,后台接收参数只能有一个,而且只能是流(或者字节数组)
att3['Content-Disposition'] = 'attachment;filename = "xixi.jpg"' ## Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。
att3['Content-ID'] = '<image1>'
msg.attach(att1)
msg.attach(att2)
msg.attach(att3)
def mail():
ret = True
try:
sever = smtplib.SMTP('smtp.163.com' , 25) ##SMTP对应端口
sever.login(sender , '***********') ##授权码,邮箱临时密码
sever.sendmail(sender , [receiver,] , msg.as_string())
sever.quit()
except Exception as e:
ret = False
return ret
ret = mail()
if ret:
print("发送成功!")
else:
print("发送失败...")
结语
刚刚开始学python的小菜鸡一枚,希望继续努力!
上一篇: C语言五子棋