____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.comTXkgZW1haWwgY29udGVudCwgaGVsbG/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-Typeheader.  This defaults to "us-ascii".  Note that as a side-effect, theContent-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.comCjxodG1sPgogICAgPGhlYWQ+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: base64TXkgZW1haWwgY29udGVudCwgaGVsbG/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 ,并加入msgmsg.attach(payload=MIMEText(_text=message, _subtype="html", _charset="utf-8"))# 加载图片内容,创建 MIMEImagefp = 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>')# 加入msgmsg.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

Python 发送邮件 email 模块、smtplib 模块相关推荐

  1. Python发送邮件(Email SMTP)

    Python发送邮件(Email SMTP) Python发送邮件(Email SMTP) : 简单邮件传输协议(SMTP)是一种处理电子邮件发送电子邮件和邮件服务器之间的路由协议. Python提供 ...

  2. smtplib python教程_python使用smtplib模块发送邮件

    使用smtplib模块发送邮件,供大家参考,具体内容如下 1)使用smtplib模块发送简单邮件 步骤: 1.连接SMTP服务器,并使用用户名.密码登陆服务器 2.创建EmailMessage对象,该 ...

  3. smtplib python_python模块:smtplib模块

    1.使用本地的sendmail协议进行邮件发送 格式(1):smtpObj=smtplib.SMTP([host [,port [,local_hostname]]]) host:SMTP服务器主机的 ...

  4. python发送邮件(smtplib、email、zmail)

    1.邮箱账号准备 首先需要注册一个个人邮箱,本文以126邮箱为例. 打开设置(网页版)中的POP3/SMTP/IMAP设置,开启POP3/SMTP服务,如果开启了会给出一串授权密码.开启后POP3/S ...

  5. 手把手教你用python发送邮件

    用python发邮件 1.用python发邮件 2.模块: 3.目标拆解: 3.1 版本1.0:给自己发送一句简单的话. 3.2 版本2.0:在版本1.0的基础上,增添邮件头(收发人和邮件标题). 1 ...

  6. python安装email模块_Python使用SMTP模块、email模块发送邮件

    一.smtplib模块: 主要通过SMTP类与邮件系统进行交互.使用方法如下: 1.实例化一个SMTP对象: s = smtplib.SMTP(邮件服务地址,端口号) s = smtplib.SMTP ...

  7. 【Python学习笔记】(十)邮件处理:email模块;SMTP协议(smtplib模块);POP3协议(poplib模块);IMAP协议(imaplib模块)

    电子邮件,简称电邮,是指一种由寄件人将数字信息发送给一个人或者多个人的信息交换方式. 电邮包括三个部分:消息的"信封".邮件标头.邮件内容. 电邮的格式:用户名@主机名(域名).电 ...

  8. [新星计划] Python smtplib模块 | 轻松学会收发E-mail(电子邮件)

    文章目录 ● 理论知识 ■ smtplib模块作用 ■ 邮件协议 ● 实操步骤 ■ QQ邮箱获取授权码 ■ 代码部分 □ 示例1 □ 示例2 □ 示例3 ■ Foxmail登录 □ 使用POP3协议登 ...

  9. [转载]Python SMTP发送邮件-smtplib模块

    在进入正题之前,我们需要对一些基本内容有所了解:常用的电子邮件协议有SMTP.POP3.IMAP4,它们都隶属于TCP/IP协议簇,默认状态下,分别通过TCP端口25.110和143建立连接. Pyt ...

最新文章

  1. “32 位应用已死!”
  2. Centos7系统创建Docker本地仓库
  3. 原来,07年我把自己给和谐了
  4. DELPHI参数几个概念上的区别 收藏
  5. pandas 空字符串与na区别_python从安装到数据分析应用高手 Pandas处理文本数据(一)...
  6. error C2065: “cout”: 未声明的标识符
  7. mysql 给指定用户指定数据库
  8. TLS 1.2 握手过程
  9. C 主导、C++与 C# 为辅,揭秘 Windows 10 源代码!
  10. 前端的常见的面试试题
  11. Mathematica 计算矩阵的伴随矩阵
  12. sap字段及描述底表_SAP各模块字段与表的对应关系.
  13. Linux命令行删除文件恢复
  14. R语言-gsub替换字符工具
  15. python安装包的时候报错 ERROR: Exception: Traceback (most recent call last): File “C:\Users\
  16. 基于Android的高校家校互通平台
  17. yii2授权之ACF
  18. Qt、GDAL遥感影像显示
  19. nginx防御简单CC攻击的方法
  20. redis哨兵模式(docker)

热门文章

  1. 如何将迅雷设为默认下载器
  2. 转:国内网址导航的现状和未来
  3. 【模拟IC】gm/id设计方法(简便、ic61版)
  4. java切换卡片_CardView之可切换式卡片
  5. 获取手机Imei码,手机号,IMSI标识
  6. 程序猿,你也配吃10元的盒饭?
  7. Imagination和瑞昱半导体携手推出全球首款具有图像压缩功能的数字电视SoC
  8. 基于51单片机的adc0832程序编写的学习
  9. 中国的电子商务三强鼎立
  10. [CubeMX]stm32通过wifi模块手机控制麦轮小车