二、发送HTML格式的邮件
Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。
1
2
|
content = '<h1>Hello</h1>' + '<p>send by <a href="http://www.python.org">Python</a>...</p>' message = MIMEText(content, "html" , "utf-8" ) |
三、发送文本中带图片的邮件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart subject = "图片邮件测试" content = """<p>Python 邮件发送测试...</p><p><img src="cid:image1"></p>""" sender = "156829568@qq.com" # 发送人,换成自己的! password = "qnrwndesjxmmijce" # 授权码,换成自己的! receiver = "32356088@qq.com" # 收件人 message = MIMEMultipart( "related" ) # 构造一个MIMEMultipart对象代表邮件本身。related 表示使用内嵌资源的形式 将邮件发送给对方 message[ "From" ] = sender message[ "To" ] = receiver message[ "Subject" ] = subject # msgAlternative = MIMEMultipart('alternative') # 接收者的别名 # msgAlternative.attach(MIMEText(content, 'html', 'utf-8')) # 添加文本 # message.attach(msgAlternative) message.attach(MIMEText(content, 'html' , 'utf-8' )) # 一步到位,不用上面三行代码 # ---------------发送图片的第一种方式----------------------- with open (r 'C:\Users\bt.cn\Desktop\004.jpg' , 'rb' ) as fp: # 二进制模式读取图片 msgImage = MIMEImage(fp.read()) msgImage.add_header( "Content-ID" , "<image1>" ) # 定义图片ID,在HTML文本中引用 message.attach(msgImage) # 添加图片到邮箱信息中去 # ---------------发送图片的第二种方式----------------------- # msgImage = MIMEText(open(r'C:\Users\bt.cn\Desktop\004.jpg', 'rb').read(), 'base64', 'utf-8') # msgImage['Content-disposition'] = 'attachment;filename="happy.png"' # message.attach(msgImage) smtp = smtplib.SMTP_SSL( "smtp.qq.com" , 465 ) smtp.set_debuglevel( 1 ) smtp.login(sender, password) try : smtp.sendmail(sender, receiver, message.as_string()) smtp.quit() smtp.close() except Exception as e: print ( "邮件发送失败,错误原因[{0}]" . format ( str (e))) print ( "邮件发送成功" ) |
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式