如何用python发送邮件?

Image

如何用python发送邮件?

最近在查看关于Python的一些书籍,看到了邮件发送相关的内容,特此整理一下。

运行环境

  • windows10 64位系统
  • python3.7版本
  • Pycharm2020.1版本

准备工作

进入163邮箱,点击设置中的pop3/smtp/imap


Image

开启smtp服务,如果没有开启,点击开启,手机号验证后即可开启,开启后图如下:

Image
Image
Image

主要用到的就是smtp服务器:smtp.163.com

然后设置客户端授权密码:

Image

记住密码,如果不记得密码在这重新授权。手机号验证即可重新授权。这个密码一会写代码的时候要用

设置成功后,开始写代码

一、python对SMTP的支持

SMTP(Simple Mail Transfer Protocol)是简单传输协议,它是一组用于用于由源地址到目的地址的邮件传输规则。

1.python中对SMTP进行了简单的封装,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

python对SMTP的支持

①email模块:负责构建邮件

②smtplib模块:负责发送邮件

2、smtplib.SMTP()对象方法的使用说明

①connect(host,port)方法参数说明

host:指定连接的邮箱服务器

port:指定连接的服务器端口

②login(user,password)方法参数说明

user:登录邮箱用户名

password:登录邮箱密码

③sendmail(from-addr,to_addrs,msg...)方法参数说明

from_addr:邮件发送者地址

to_addrs:字符串列表,邮件发送地址

msg:发送消息

④quit():结束当前会话

二、发送不同格式的邮件

1、纯文本格式的邮件

下面上代码


# @File    : simple1.py
# @Software: PyCharm

import smtplib

HOST = "smtp.163.com"
SUBJECT = "Test email from Python"
TO = "[email protected]"
FROM = "[email protected]"
text = "Python rules them all!"
BODY = "\r\n".join((
    "From: %s" % FROM,
    "To: %s" % TO,
    "Subject: %s" % SUBJECT,
    "",
    text
))


def main():
    server = smtplib.SMTP()
    server.connect(HOST, 25)
    server.login(FROM, "123456")
    server.set_debuglevel(1)
    server.sendmail(FROM, [TO], BODY)
    server.quit()


if __name__ == '__main__':
    main()

注意: 发件人的密码是邮箱授权码,不是邮箱登录密码

我们将收到这样一封邮件,如下图

Image

2、HTML格式的邮件

下面上代码


# @File    : simple2.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

HOST = "smtp.163.com"
SUBJECT = "官网流量数据报表"
TO = "[email protected]"
FROM = "[email protected]"

msg = MIMEText("""
    
*官网数据 更多>>
1)日访问量:152433 访问次数:23651 页面浏览量:45123 点击数:545122 数据流量:504Mb
2)状态码信息
  500:105 404:3264 503:214
3)访客浏览器信息
  IE:50% firefox:10% chrome:30% other:10%
4)页面信息
  /index.php 42153
  /view.php 21451
  /login.php 5112
""", "html", "utf-8") msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO msg['Date'] = formatdate() def main(): try: server = smtplib.SMTP() server.connect(HOST, 25) server.login(FROM, "123456") server.sendmail(FROM, TO, msg.as_string()) server.quit() print("邮件发送成功!") except Exception as e: print("失败:" + str(e)) if __name__ == '__main__': main()

我们将收到这样一封邮件,如下图

Image

3、 发送图文格式的邮件:

下面上代码


# @File    : simple3.py
# @Software: PyCharm

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate

HOST = "smtp.163.com"
SUBJECT = "业务性能数据报表"
TO = "[email protected]"
FROM = "[email protected]"


def addimg(src, imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage


msg = MIMEMultipart('related')
msgtext = MIMEText("""
*官网性能数据 更多>>
""", "html", "utf-8") msg.attach(msgtext) msg.attach(addimg("img/bytes_io.png", "io")) msg.attach(addimg("img/myisam_key_hit.png", "key_hit")) msg.attach(addimg("img/os_mem.png", "men")) msg.attach(addimg("img/os_swap.png", "swap")) msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO msg['Date'] = formatdate() def main(): try: server = smtplib.SMTP() server.connect(HOST, 25) server.login(FROM, "123456") server.sendmail(FROM, TO, msg.as_string()) server.quit() print("邮件发送成功!") except Exception as e: print("失败:" + str(e)) if __name__ == '__main__': main()

我们将收到这样一封邮件,如下图

Image

4、 发送不同格式的附件:

一般来说,不会用到MIMEBase,而是直接使用它的继承类。MIMEMultipart有attach方法,而MIMENonMultipart没有,只能被attach。
MIME有很多种类型,这个略麻烦,如果附件是图片格式,我要用MIMEImage,如果是音频,要用MIMEAudio,如果是word、excel,我都不知道该用哪种MIME类型了,得上google去查。
最懒的方法就是,不管什么类型的附件,都用MIMEApplication,MIMEApplication默认子类型是application/octet-stream。
application/octet-stream表明“这是个二进制的文件,希望你们那边知道怎么处理”,然后客户端,比如qq邮箱,收到这个声明后,会根据文件扩展名来猜测。

下面上代码


# @File    : simple4.py
# @Software: PyCharm

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from email.mime.application import MIMEApplication

HOST = "smtp.163.com"
SUBJECT = "官网业务服务质量周报"
TO = "[email protected]"
FROM = "[email protected]"


def addimg(src, imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage


msg = MIMEMultipart('related')
msgtext = MIMEText("官网业务周平均延时图表:

详细内容见附件。
", "html", "utf-8") msg.attach(msgtext) msg.attach(addimg("img/weekly.png", "weekly")) attach = MIMEApplication(open("doc/week_report.xlsx", "rb").read()) attach.add_header('Content-Disposition', 'attachment', filename="week_report.xlsx") msg.attach(attach) msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO msg['Date'] = formatdate() def main(): try: server = smtplib.SMTP() server.connect(HOST, 25) server.login(FROM, "123456") server.sendmail(FROM, [TO], msg.as_string()) server.quit() print("邮件发送成功!") except Exception as e: print("失败:" + str(e)) if __name__ == '__main__': main()

我们将收到这样一封邮件,如下图

Image

5、批量发送带附件邮件

下面上代码


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/5/22 15:01
# @Author  : 一叶知秋
# @File    : simple5.py
# @Software: PyCharm
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication


def add_attachment(email_attachment_address, msgRoot):
    # 添加附件
    for path in email_attachment_address:
        if path.endswith(('.jpg', '.png')):
            # jpg
            picture_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=picture_name)
            msgRoot.attach(part)

        if path.endswith('.pdf'):
            # pdf
            pdf_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=pdf_name)
            msgRoot.attach(part)

        if path.endswith(('.docx', '.pptx', '.xlsx')):
            # doc,xlsx,ppt
            office_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=office_name)
            msgRoot.attach(part)

        if path.endswith('.txt'):
            # txt
            txt_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=txt_name)
            msgRoot.attach(part)

        if path.endswith('.mp3'):
            # mp3
            mp3_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=mp3_name)
            msgRoot.attach(part)

        if path.endswith(('.zip','.tar','.gz')):
            # tar zip tar.gz
            compress_name = path.split('\\')[-1]
            part = MIMEApplication(open(path, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=compress_name)
            msgRoot.attach(part)


def send_email(email_subject, email_content, email_attachment_address, email_receiver):
    sender = '[email protected]'
    passwd = '123456'
    receivers = email_receiver  # 邮件接收人
    msgRoot = MIMEMultipart()
    msgRoot['Subject'] = email_subject
    msgRoot['From'] = sender
    if len(receivers) > 1:
        msgRoot['To'] = ';'.join(receivers)  # 群发邮件
    else:
        msgRoot['To'] = receivers[0]

    part = MIMEText(email_content)
    msgRoot.attach(part)

    # 添加附件
    add_attachment(email_attachment_address, msgRoot)
    server = None
    try:
        server = smtplib.SMTP()
        server.connect('smtp.163.com')
        server.login(sender, passwd)
        server.sendmail(sender, receivers, msgRoot.as_string())
        print('邮件发送成功')
    except smtplib.SMTPException as e:
        print('邮件发送失败')
    finally:
        server.quit()


def main():
    # 发送测试邮件
    email_subject = 'python 邮件测试'
    email_content = 'hello world'
    file_dir = r'C:\Users\liming\Desktop\file_dir'
    email_attachment_address = [os.path.join(file_dir, file) for file in os.listdir(file_dir)]
    email_receiver = ['[email protected]', '[email protected]']
    send_email(email_subject, email_content, email_attachment_address, email_receiver)


if __name__ == '__main__':
    main()

我们将收到这样一封邮件,如下图

Image

最后

项目地址:https://github.com/jumploop/pymail

希望对大家有帮助!随手点个赞!

参考链接,书籍

  • https://www.cnblogs.com/insane-Mr-Li/p/9121619.html
  • 《Python自动化运维:技术与最佳实践》

你可能感兴趣的:(如何用python发送邮件?)