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

本文实例讲述了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 = '[email protected]'
from_addr_pwd = 'xxxxxx'
to_addr = '[email protected]'
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 = '[email protected]'
from_addr_pwd = 'xxxxxx'
to_addr = '[email protected]'
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 = '[email protected]'
from_addr_pwd = 'xxxxxx'
to_addr = '[email protected]'
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 = '[email protected]'
from_addr_pwd = 'xxxxxx'
to_addr = '[email protected]'
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程序设计有所帮助。

相关推荐