Python 发送邮件 email、smtplib

版权声明:本文为博主原创文章,欢迎讨论共同进步。 https://blog.csdn.net/tz_zs/article/details/81672466

____tz_zs

SMTP

email 模块:负则构造邮件
smtplib 模块:负则发送邮件

发送纯文本邮件

from email.header import Header
from email.mime.text import MIMEText
import re
import smtplib

# 发送者、接收者
from_addr = '[email protected]'
password = 'zzz'
to_addrs = '[email protected]'
# 服务器、端口
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: [email protected]
To: [email protected]

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源码:

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)

参数:

_text=”” 为邮件内容
_subtype=”plain” 设置文本格式。默认为普通(plain)
_charset=”utf-8” 设置字符编码格式,默认为 us-ascii。从源码可看出,当 _test 中包含 ascii 之外的字符,则将使用 utf-8 编码

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 = '[email protected]'
password = 'xxxpassword'
# to_addrs = "[email protected]"
to_addrs = '[email protected]'

# 创建 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: [email protected]
To: [email protected]; [email protected]

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 = '[email protected]'
password = '12345678'
to_addrs = ['[email protected]', '[email protected]']

# 创建 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: [email protected]
To: [email protected]; [email protected]

--===============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 = '[email protected]'
    password = 'xyz'
    to_addrs = ["[email protected]", "[email protected]", "[email protected]", ]

    # 创建 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())
    msg.attach(payload=MIMEText(_text=message, _subtype="html", _charset="utf-8"))

    # 指定图片为当前目录
    fp = open(self.path_output_open + "zusd_value_portfolio.png", 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()

    # 定义图片 ID,在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    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

猜你喜欢

转载自blog.csdn.net/tz_zs/article/details/81672466