学习总结 python (5)
—用Python发送邮件
1.准备邮箱账号和授权码
username=‘xxxxxxx@qq.com’
mandate_code=‘qq邮箱授权码’
2.连接邮箱服务器
con=smtplib.SMTP_SSL(‘smtp.qq.com’)
3.登录邮箱
con.login(username,mandate_code)
4.构建邮箱
1.)创建邮件对象(创建空邮箱)
msg=MIMEMultipart()
2.)添加邮件主题
header=Header(‘邮件主题’,’utf-8’).encode()
msg[‘Subject’]=header
3.)设置发件人显示信息
sender=f’{username}<{username}>’
msg[‘From’] = sender
4.)设置收件人信息
receiver=‘xxxx@qq.com’
msg[‘To’]=receiver
5.)构建邮件正文
content=MIMEText(’邮件正文内容‘,’plain’,‘utf-8’)
msg.attach(content)
6.发送邮件
con.sendmail(username,‘y_t209@163.com’,msg,as_string())
7.关闭连接
con.quit()
如果文件添加附件—构建邮件和发送邮件中添加
例如:
file1 = open('files/pyecharts的使用.pdf', 'rb').read()
# base64 - 文件
att1 = MIMEText(file1, 'base64', 'utf-8')
att1['Content-Disposition'] = 'attachment; filename="pyecharts.pdf"'
msg.attach(att1)
file2 = open('files/07-Excel图表用途.xlsx', 'rb').read()
att2 = MIMEText(file2, 'base64', 'utf-8')
att2['Content-Disposition'] = 'attachment; filename="excel.xlsx"'
msg.attach(att2)
如果发送富文本
邮件正文例如:
# html - 富文本(超文本)
# MIMEText(html代码, 'html', 'utf-8')
html = open('files/demo.html', 'r', encoding='utf-8').read()
content = MIMEText(html, 'html', 'utf-8')
msg.attach(content)
image_data1 = open('files/hua.png', 'rb').read()
image1 = MIMEImage(image_data1)
image1.add_header('Content-ID', '<i1>')
msg.attach(image1)
image_data2 = open('luffy1.png', 'rb').read()
image2 = MIMEImage(image_data2)
image2.add_header('Content-ID'