Python基于SMTP协议实现发送邮件功能详解


Posted in Python onAugust 14, 2018

本文实例讲述了Python基于SMTP协议实现发送邮件功能。分享给大家供大家参考,具体如下:

SMTP(Simple Mail Transfer Protocol),即简单邮件传输协议,它是一组由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplibemail两个模块,email负责构造邮件,smtplib负责发送邮件。

Python创建SMTP语法如下:

import smtplib
smtpObj = mstplib.SMTP(host,port)

创建具有SSL协议的SMTP:

import smtplib
smtpObj = mstplib.SMTP_SSL(host,port)

使用SMTP对象发送邮件:

# from_addr:发送者邮箱
# to_addrs:接收者邮箱,list
# msg:消息体
smtpObj.sendmail(from_addr, to_addrs, msg, mail_options=[],
         rcpt_options=[])

接下来的示例都是以网易邮箱作为邮箱服务器来写的,网易163免费邮箱相关服务器信息如下:

Python基于SMTP协议实现发送邮件功能详解

使用网易邮箱作为发送者邮箱时应注意,邮箱密码并非为邮箱的登录密码,而是客户端授权密码。

发送纯文本邮件

首先,我们需要构造一个消息体:

from email.header import Header
from email.mime.text import MIMEText
# 第一个参数为邮件正文,第二个参数为MINE的subtype,传入‘plain',最终的MINE就是‘text/plain',最后参数为编码
msg = MIMEText('hello email','palin','utf-8')
def _format_addr(s):
  name,addr = parseaddr(s)
  return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr))
# 发送者昵称
msg['From'] = _format_addr('发送者昵称 <%s>'%from_addr) 
# 接收者昵称
msg['To'] = _format_addr('接收者昵称 <%s>'%to_addr)
# 标题
msg['Subject'] = Header('标题','utf-8').encode()

此时就构造了一个简单的消息体。切记,如果未指定标题以及昵称,并且将其格式化编码,有可能会被认为是辣鸡邮件而导致发送失败!!!

以下就是发送纯文本邮件示例的完整代码:

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr,parseaddr
host = 'smtp.163.com'
port = 25
from_addr = 'xxxx@163.com'
from_addr_pwd = 'xxxxxx'
to_addr = 'xxxx@qq.com'
def _format_addr(s):
  name,addr = parseaddr(s)
  return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr))
msg = MIMEText('hello email','palin','utf-8')
msg['From'] = _format_addr('发送者昵称 <%s>'%from_addr) 
msg['To'] = _format_addr('接收者昵称 <%s>'%to_addr)
msg['Subject'] = Header('标题','utf-8').encode()
smtpObj = smtplib.SMTP(host,25)
smtpObj.set_debuglevel(1)
smtpObj.login(sender,password)
smtpObj.sendmail(sender, [receivers], message.as_string())
smtoObj.quit()

值得注意的是,调用sendmail方法时,接收者邮箱为一个list类型,用于群发功能。

发送HTML邮件

如果有发送HTML邮件的需求,此时我们仍需先够着一个MIMEText对象,将html字符串传递进来,如下:

htmlStr = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>Hello SMTP</h1>
  <p>点击<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >链接</a></p>
</body>
</html>'''
msg = MIMEText(htmlStr,'html','utf-8')

完整代码如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr,parseaddr
def _format_addr(s):
  name,addr = parseaddr(s)
  return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr))
server = 'smtp.163.com'
from_addr = 'xxx@163.com'
from_addr_pwd = 'xxxxxx'
to_addr = 'xxx1@qq.com'
htmlStr = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>Hello SMTP</h1>
  <p>点击<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >链接</a></p>
</body>
</html>'''
msg = MIMEText(htmlStr,'html','utf-8')
msg['From'] = _format_addr("发送者 <%s>"%from_addr)
msg['To'] = _format_addr("接收者 <%s>"%to_addr)
msg['Subject'] = Header('一个简单的标题','utf-8').encode()
smtpObj = smtplib.SMTP(server,25)
smtpObj.set_debuglevel(1)
smtpObj.login(from_addr,from_addr_pwd)
smtpObj.sendmail(from_addr,[to_addr],msg.as_string())
smtpObj.quit()

发送附件邮件

如果我们有发送附件的需求时,我们该如何改造消息体呢?我们此时可以用MIMEMultipart构造邮件的本身,传递一个MIMEText对象来写入邮件的正文,再用MIMEBase对象存储附件的信息即可,代码如下:

msg = MIMEMultipart()
msg.attach(MIMEText('发送一个附件...','plain','utf-8'))
path = os.path.join(os.getcwd(),'1.png')
with open(path,'rb') as f:
  # 设置附件的MIME
  mime = MIMEBase('image','png',filename='1.png')
  # 加上必要的头信息
  mime.add_header('Content-Disposition','attachment',filename='1.png')
  mime.add_header('Content-ID','<0>')
  mime.add_header('X-Attachment-Id','0')
  # 读取文件内容
  mime.set_payload(f.read())
  # 使用base64编码
  encode_base64(mime)
  msg.attach(mime)

完整代码如下:

import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart,MIMEBase
from email.header import Header
from email.encoders import encode_base64
from email.utils import formataddr,parseaddr
msg = MIMEMultipart()
msg.attach(MIMEText('发送一个附件...','plain','utf-8'))
def _format_addr(s):
  name,addr = parseaddr(s)
  return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr))
server = 'smtp.163.com'
from_addr = 'xxx@163.com'
from_addr_pwd = 'xxxxxx'
to_addr = 'xxx1@qq.com'
path = os.path.join(os.getcwd(),'1.png')
with open(path,'rb') as f:
  mime = MIMEBase('image','png',filename='1.png')
  mime.add_header('Content-Disposition','attachment',filename='1.png')
  mime.add_header('Content-ID','<0>')
  mime.add_header('X-Attachment-Id','0')
  mime.set_payload(f.read())
  encode_base64(mime)
  msg.attach(mime)
msg['From'] = _format_addr("发送者 <%s>"%from_addr)
msg['To'] = _format_addr("接收者 <%s>"%to_addr)
msg['Subject'] = Header('一个简单的附件邮件','utf-8').encode()
smtpObj = smtplib.SMTP(server,25)
smtpObj.set_debuglevel(1)
smtpObj.login(from_addr,from_addr_pwd)
smtpObj.sendmail(from_addr,[to_addr],msg.as_string())
smtpObj.quit()

发送图片邮件

如果我们需要在一段文本中插入图片作为邮件正文,那么我们该如何实现呢?有人会想用HTML,在里面嵌一个img标签就可以了,但是这样有一个问题,因为img标签是引用一个图片路径的,我们总不能将图片文件也发送过去吧。那么久没有办法了吗,当然有,我们可以结合HTML与附件邮件发送方式来发送图片邮件,首先我们将图片以附件的形式添加进来,再以HTML中img标签引用src='cid:0',就可以将图片引用进来了,如下:

msg = MIMEMultipart()
path = os.path.join(os.getcwd(),'1.png')
with open(path,'rb') as f:
  mime = MIMEBase('image','png',filename='1.png')
  mime.add_header('Content-Disposition','attachment',filename='1.png')
  mime.add_header('Content-ID','<0>')
  mime.add_header('X-Attachment-Id','0')
  mime.set_payload(f.read())
  encode_base64(mime)
  msg.attach(mime)
htmlStr = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>图片标题</h1>
  <p>插入一个图片<img src="cid:0"/></p>
</body>
</html>'''
msg.attach(MIMEText(htmlStr,'html','utf-8'))

完整代码如下:

import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart,MIMEBase
from email.header import Header
from email.encoders import encode_base64
from email.utils import parseaddr,formataddr
server = 'smtp.163.com'
from_addr = 'xxx@163.com'
from_addr_pwd = 'xxxxxx'
to_addr = 'xxx1@qq.com'
def _format_addr(s):
  name,addr = parseaddr(s)
  return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr))
msg = MIMEMultipart()
path = os.path.join(os.getcwd(),'1.png')
with open(path,'rb') as f:
  # 设置附件的MIME
  mime = MIMEBase('image','png',filename='1.png')
  # 加上必要的头信息
  mime.add_header('Content-Disposition','attachment',filename='1.png')
  mime.add_header('Content-ID','<0>')
  mime.add_header('X-Attachment-Id','0')
  # 读取文件内容
  mime.set_payload(f.read())
  # 使用base64编码
  encode_base64(mime)
  msg.attach(mime)
htmlStr = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>图片标题</h1>
  <p>插入一个图片<img src="cid:0"/></p>
</body>
</html>'''
msg.attach(MIMEText(htmlStr,'html','utf-8'))
msg['From'] = _format_addr('发送者 <%s>'%from_addr)
msg['To'] = _format_addr('接收者 <%s>'%to_addr)
msg['Subject'] = Header('发送图片邮件','utf-8').encode()
smtpObj = smtplib.SMTP(server,25)
smtpObj.set_debuglevel(1)
smtpObj.login(from_addr,from_addr_pwd)
smtpObj.sendmail(from_addr,[to_addr],msg.as_string())
smtpObj.quit()

如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python重新引入被覆盖的自带function
Jul 16 Python
python3 读取Excel表格中的数据
Oct 16 Python
python实现合并多个list及合并多个django QuerySet的方法示例
Jun 11 Python
使用python实现ftp的文件读写方法
Jul 02 Python
python3.7 的新特性详解
Jul 25 Python
Python高级特性——详解多维数组切片(Slice)
Nov 26 Python
pandas实现excel中的数据透视表和Vlookup函数功能代码
Feb 14 Python
浅谈pymysql查询语句中带有in时传递参数的问题
Jun 05 Python
django filter过滤器实现显示某个类型指定字段不同值方式
Jul 16 Python
python计算auc的方法
Sep 09 Python
浅析python 字典嵌套
Sep 29 Python
python获取天气接口给指定微信好友发天气预报
Dec 28 Python
selenium+python实现1688网站验证码图片的截取功能
Aug 14 #Python
django+xadmin+djcelery实现后台管理定时任务
Aug 14 #Python
Python延时操作实现方法示例
Aug 14 #Python
详解PyCharm配置Anaconda的艰难心路历程
Aug 13 #Python
python 实现A*算法的示例代码
Aug 13 #Python
Python绘制KS曲线的实现方法
Aug 13 #Python
Python标准库shutil用法实例详解
Aug 13 #Python
You might like
实时抓取YAHOO股票报价的代码
2006/10/09 PHP
PHP 递归效率分析
2009/11/24 PHP
PHP 网络开发详解之远程文件包含漏洞
2010/04/25 PHP
基于jQuery的仿flash的广告轮播
2010/11/05 Javascript
stream.js 一个很小、完全独立的Javascript类库
2011/10/28 Javascript
理解JS事件循环
2016/01/07 Javascript
javascript实现数字倒计时特效
2016/03/30 Javascript
gulp-uglify 与gulp.watch()配合使用时报错(重复压缩问题)
2016/08/24 Javascript
详解Node.Js如何处理post数据
2016/09/19 Javascript
浅谈js对象的创建和对6种继承模式的理解和遐想
2016/10/16 Javascript
微信小程序 实例开发总结
2017/04/26 Javascript
webpack教程之webpack.config.js配置文件
2017/07/05 Javascript
js实现带搜索功能的下拉框
2020/01/11 Javascript
python正则表达式判断字符串是否是全部小写示例
2013/12/25 Python
Python删除指定目录下过期文件的2个脚本分享
2014/04/10 Python
Python3基础之list列表实例解析
2014/08/13 Python
Python使用chardet判断字符编码
2015/05/09 Python
简述Python2与Python3的不同点
2018/01/21 Python
tensorflow 使用flags定义命令行参数的方法
2018/04/23 Python
python 匹配url中是否存在IP地址的方法
2018/06/04 Python
django使用haystack调用Elasticsearch实现索引搜索
2019/07/24 Python
详细介绍pandas的DataFrame的append方法使用
2019/07/31 Python
pandas DataFrame行或列的删除方法的实现示例
2019/08/02 Python
Python基于数列实现购物车程序过程详解
2020/06/09 Python
加拿大鞋子连锁店:Town Shoes
2016/09/26 全球购物
EJB的基本架构
2016/09/22 面试题
工商管理专业实习大学生自我鉴定
2013/09/19 职场文书
十佳教师事迹材料
2014/01/11 职场文书
应届电子商务毕业自荐书范文
2014/02/11 职场文书
计算机专业自荐信
2014/05/24 职场文书
低碳生活的宣传标语
2014/06/23 职场文书
办公室岗位职责范本
2015/04/11 职场文书
三好学生主要事迹怎么写
2015/11/03 职场文书
SQL Server使用PIVOT与unPIVOT实现行列转换
2022/05/25 SQL Server
Java 多线程并发FutureTask
2022/06/28 Java/Android
CSS 实现角标效果的完整代码
2022/06/28 HTML / CSS