学习总结 python (5)

学习总结 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'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值