欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-04 21:22:32
本文实例讲述了python基于smtp协议实现发送邮件功能。分享给大家供大家参考,具体如下: smtp(simple mail transfer protocol),即简...

本文实例讲述了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程序设计有所帮助。