____tz_zs
SMTP
email 模块:负则构造邮件
smtplib 模块:负则发送邮件
一、发送纯文本邮件
from email.header import Header
from email.mime.text import MIMEText
import re
import smtplib
# 发送者、接收者
from_addr = 'xxxname@yyy.cn'
password = 'zzz'
to_addrs = 'xxxxto@foxmail.com'
# 服务器、端口
smtp_host = 'smtp.exmail.qq.com' # SMTP 服务器主机
smtp_port = 465 # SMTP 服务器端口号
# 创建 SMTP 对象
smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)
#创建 MIMEText 对象
msg = MIMEText(_text="My email content, hello!", _subtype="plain", _charset="utf-8") # _text="邮件内容"
msg["Subject"] = Header(s="The title", charset="utf-8") # 标题
msg["From"] = Header(s=from_addr) # 发送者
msg["To"] = Header(s=to_addrs) # 接收者
print(msg.as_string())
"""
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Subject: =?utf-8?q?The_title?=
From: xxxname@yyy.cn
To: xxxx@foxmail.com
TXkgZW1haWwgY29udGVudCwgaGVsbG/vvIE=
"""
# 使用 SMTP 对象登录、发送邮件
smtp_obj.login(user=from_addr, password=password)
smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())
smtp_obj.quit()
MIMEText 对象
MIMEText 类是 MIMENonMultipart 类的子类,用于生成文本类型的邮件。邮件由标题,发信人,收件人,邮件内容,附件等构成。
MIMEText(_text=“My email content, hello!”, _subtype=“plain”, _charset=“utf-8”)
参数:
_text="" 为邮件内容
_subtype=“plain” 设置文本格式。默认为普通(plain)
_charset=“utf-8” 设置字符编码格式,默认为 us-ascii。从源码可看出,当 _test 中包含 ascii 之外的字符,则将使用 utf-8 编码
MIMENonMultipart源码:
由源码可知,此类及其子类不能调用 attach 函数添加额外的 part。
MIMENonMultipart 的子类有:
- MIMEImage: generating image/* type MIME documents.
- MIMEAudio: generating audio/* MIME documents.
- MIMEApplication: generating application/* MIME documents.
- MIMEMessage: representing message/* MIME documents.
- MIMEText: generating text/* type MIME documents.
class MIMEText(MIMENonMultipart):
"""Class for generating text/* type MIME documents."""
def __init__(self, _text, _subtype='plain', _charset=None):
"""Create a text/* type MIME document.
_text is the string for this message object.
_subtype is the MIME sub content type, defaulting to "plain".
_charset is the character set parameter added to the Content-Type
header. This defaults to "us-ascii". Note that as a side-effect, the
Content-Transfer-Encoding header will also be set.
"""
# If no _charset was specified, check to see if there are non-ascii
# characters present. If not, use 'us-ascii', otherwise use utf-8.
# XXX: This can be removed once #7304 is fixed.
if _charset is None:
try:
_text.encode('us-ascii')
_charset = 'us-ascii'
except UnicodeEncodeError:
_charset = 'utf-8'
if isinstance(_charset, Charset):
_charset = str(_charset)
MIMENonMultipart.__init__(self, 'text', _subtype,
**{'charset': _charset})
self.set_payload(_text, _charset)
class MIMENonMultipart(MIMEBase):
"""Base class for MIME non-multipart type messages."""
def attach(self, payload):
# The public API prohibits attaching multiple subparts to MIMEBase
# derived subtypes since none of them are, by definition, of content
# type multipart/*
raise errors.MultipartConversionError(
'Cannot attach additional subparts to non-multipart/*')
sendmail()函数
sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
参数:
from_addr: 发出邮件的地址
to_addrs: 一个list,包括要发送邮件的邮箱地址。也可以是一个字符串,这时会被当成长度为1的list。
msg: 消息
二、发送HTML邮件
只需在创建 MIMEText 时,将 _subtype 设置为 “html”,则可发送 html 格式的邮件,其他步骤和发送纯文本邮件一致。
如果要同时发送邮件给多个目标邮箱,只需使用 list 包裹多个邮箱地址即可。需要注意的是,邮件的 “To” 字段部分需要的是字符串。
# 发送者、接收者
from_addr = 'xxxuser@yyy.cn'
password = 'xxxpassword'
# to_addrs = "zzz@gmail.com"
to_addrs = 'zzz@foxmail.com'
# 创建 SMTP 对象
smtp_host = 'smtp.exmail.qq.com' # SMTP 服务器主机
smtp_port = 465 # SMTP 服务器端口号
smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)
str = """
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 align="center">html 标题</h1>
<p>正文</p>
<br>
<a href="https://www.baidu.com/" target="_blank" title="点击跳转到百度">一个超链接</a>
<br>
</body>
</html>
"""
msg = MIMEText(_text=str, _subtype="html", _charset="utf-8") # _text="邮件内容"
msg["Subject"] = Header(s="发送 html 邮件", charset="utf-8") # 标题
msg["From"] = Header(s=from_addr) # 发送者
msg["To"] = Header(s='; '.join(to_addrs)) # 接收者
print(msg.as_string())
"""
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Subject: =?utf-8?b?5Y+R6YCBIGh0bWwg6YKu5Lu2?=
From: xxxuser@yyy.cn
To: yyy@foxmail.com; yyy@gmail.com
CjxodG1sPgogICAgPGhlYWQ+CiAgICAgICAgPG1ldGEgY2hhcnNldD0iVVRGLTgiPgogICAgPC9o
ZWFkPgogICAgPGJvZHk+CiAgICA8aDEgYWxpZ249ImNlbnRlciI+aHRtbCDmoIfpopg8L2gxPgog
ICAgPHA+5q2j5paHPC9wPgogICAgPGJyPgogICAgPGEgaHJlZj0iaHR0cHM6Ly93d3cuYmFpZHUu
Y29tLyIgdGFyZ2V0PSJfYmxhbmsiIHRpdGxlPSLngrnlh7vot7PovazliLDnmb7luqYiPuS4gOS4
qui2hemTvuaOpTwvYT4KICAgIDxicj4KICAgIDwvYm9keT4KPC9odG1sPgo=
"""
# 使用 SMTP 对象发送邮件
smtp_obj.login(user=from_addr, password=password)
smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())
smtp_obj.quit()
三、发送带附件的邮件
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
"""
@author: tz_zs
"""
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
# 发送者、接收者
from_addr = 'xxxsend@yyy.cn'
password = '12345678'
to_addrs = ['zzz@foxmail.com', 'zzz@gmail.com']
# 创建 SMTP 对象
smtp_host = 'smtp.exmail.qq.com' # SMTP 服务器主机
smtp_port = 465 # SMTP 服务器端口号
smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)
str = """
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 align="center">html 标题</h1>
<p>正文</p>
<br>
<a href="https://www.baidu.com/" target="_blank" title="点击跳转到百度">一个超链接</a>
<br>
</body>
</html>
"""
msg = MIMEMultipart()
msg["Subject"] = Header(s="发送带附件的邮件", charset="utf-8") # 标题
msg["From"] = Header(s=from_addr) # 发送者
msg["To"] = Header(s='; '.join(to_addrs)) # 接收者
# 邮件正文
msg.attach(payload=MIMEText(_text="My email content, hello!", _subtype="plain", _charset="utf-8"))
# 附件1
file_path = 'test.xls'
att1 = MIMEText(_text=open(file_path, "rb").read(), _subtype="base64", _charset="utf-8")
att1["Content-Type"] = "application/octet-stream"
att1["Content-Disposition"] = "attachment; filename=%s" % file_path # filename 可以任意写,写什么名字,邮件中显示什么名字。但是不要写中文
msg.attach(payload=att1)
# 附件2
file_path2 = 'a.png'
att2 = MIMEText(_text=open(file_path2, "rb").read(), _subtype="base64", _charset="utf-8")
att2["Content-Type"] = "application/octet-stream"
att2["Content-Disposition"] = "attachment; filename=%s" % file_path2 # filename 可以任意写,写什么名字,邮件中显示什么名字。但是不要写中文
msg.attach(payload=att2)
print(msg.as_string())
"""
Content-Type: multipart/mixed; boundary="===============0753960931152521813=="
MIME-Version: 1.0
Subject: =?utf-8?b?5Y+R6YCB5bim6ZmE5Lu255qE6YKu5Lu2?=
From: xxxsend@yyy.cn
To: zzz@foxmail.com; zzz@gmail.com
--===============0753960931152521813==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
TXkgZW1haWwgY29udGVudCwgaGVsbG/vvIE=
--===============0753960931152521813==
Content-Type: text/base64; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=test.xls
......
......
......
"""
# 使用 SMTP 对象发送邮件
smtp_obj.login(user=from_addr, password=password)
smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())
smtp_obj.quit()
四、发送带图片展示的邮件
def send_img_mail(self):
"""用于发送带图片的邮件"""
# 发送者、接收者
from_addr = 'xxx@yyy.cn'
password = 'xyz'
to_addrs = ["bbb@yyy.cn", "jjj@yyy.cn", "ccc@yyy.cn", ]
# 创建 SMTP 对象
smtp_host = 'smtp.exmail.qq.com' # SMTP 服务器主机
smtp_port = 465 # SMTP 服务器端口号
smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)
msg = MIMEMultipart()
msg["Subject"] = Header(s="发送带图片显示的邮件", charset="utf-8") # 标题
msg["From"] = Header(s=from_addr) # 发送者
msg["To"] = Header(s='; '.join(to_addrs)) # 接收者
# 邮件正文
message = """
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 align="center">状态监控</h1>
<b>本邮件发送时间: %s</b>
<br>
<b>状态报告: %s</b>
<h3>走势:</h3>
<p><img src="cid:image1"></p>
</body>
</html>
""" % (ToolDate.get_ymdhms_string(), self.df.to_html())
# 创建 MIMEText ,并加入msg
msg.attach(payload=MIMEText(_text=message, _subtype="html", _charset="utf-8"))
# 加载图片内容,创建 MIMEImage
fp = open(self.path_output_open + "zusd_value_portfolio.png", 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,与 HTML 文本中的引用id一致
msgImage.add_header('Content-ID', '<image1>')
# 加入msg
msg.attach(msgImage)
# 使用 SMTP 对象发送邮件
smtp_obj.login(user=from_addr, password=password)
smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())
smtp_obj.quit()
五、参考:
http://www.runoob.com/python/python-email.html