本文为博主原创,未经许可严禁转载。
本文链接:https://blog.csdn.net/zyooooxie/article/details/113102263

之前分享过一期 smtplib发邮件踩过的坑;我感觉smtplib 用起来比较复杂,没那么好用,后来 我看到2个与发邮件相关的库 zmail、 yagmail,使用后有些心得,在此做个分享。

个人博客:https://blog.csdn.net/zyooooxie

需求

本篇主要是讲述 4个方法:

  1. 发送 内容为纯文本的邮件 send_text()
  2. 发送 内容为html格式的邮件 send_html()
  3. 发送 包含多个附件的邮件 send_file()
  4. 发送 混合的邮件 send_text_html_file()

代码

smtplib


def my_send_email(receiver: list, cc: list, msg):receiver.extend(cc)# 163邮箱# smtp = smtplib.SMTP()# smtp.connect(host=smtp_server, port=port)# qq邮箱smtp = smtplib.SMTP_SSL(host=smtp_server, port=port)smtp.login(user=sender, password=pwd)smtp.sendmail(from_addr=sender, to_addrs=receiver, msg=msg.as_string())smtp.quit()print('发送成功')# text/plain(纯文本)
def send_text():receiver = 'zyooooxie@csdn.com'cc = 'zyooooxie@csdn.com'now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['smtplib-text', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])text = '1.邮件是由zyooooxie推送;\n2.{}完成测试'.format(faker.Faker(locale='zh_CN').name())msg = MIMEText(_text=text, _subtype='plain', _charset='utf-8')msg['from'] = sendermsg['to'] = receivermsg['subject'] = subjectmsg['cc'] = ccmy_send_email([receiver], [cc], msg)# text/html(超文本)
def send_html():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['smtplib-html', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])body = """<p style="font-size:10px;color:red;line-height:90px">这由zyooooxie推送</p><p style="font-size:30px;color:orange">{}完成测试</p>""".format(faker.Faker(locale='zh_CN').name())msg = MIMEText(_text=body, _subtype='html', _charset='utf-8')msg['from'] = sendermsg['to'] = ','.join(receiver)msg['subject'] = subjectmsg['cc'] = ','.join(cc)my_send_email(receiver, cc, msg)# 发送附件+正文添加图片
def send_file():receiver = 'zyooooxie@csdn.com'cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['smtplib-file', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])msg = MIMEMultipart('alternative')msg['from'] = sendermsg['to'] = receivermsg['subject'] = subjectmsg['cc'] = ','.join(cc)file_path = r'D:\zy0'# 添加附件file_list = [i for i in os.listdir(file_path)]for fl in file_list:f = os.path.join(file_path, fl)with open(f, 'rb') as F:n = F.read()part = MIMEApplication(n)part.add_header('Content-Disposition', 'attachment', filename=Header(fl, "utf-8").encode())msg.attach(part)# 要把图片嵌入到邮件正文中pic_path = os.path.join(file_path, '物业3.PNG')with open(pic_path, 'rb') as f:pic = MIMEImage(f.read())pic.add_header('Content-ID', '<zy>')msg.attach(pic)body = """<p>send email with inside picture</p><img src="cid:zy">"""msg.attach(MIMEText(body, 'html', 'utf-8'))my_send_email([receiver], cc, msg)def send_text_html_file():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = 'zyooooxie@csdn.com'now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['smtplib-混合', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])msg = MIMEMultipart('mixed')msg['from'] = sendermsg['to'] = ','.join(receiver)msg['subject'] = subjectmsg['cc'] = cctext = '{} well done '.format(faker.Faker(locale='zh_CN').name())text_plain = MIMEText(_text=text, _subtype='plain', _charset='utf-8')msg.attach(text_plain)html = '<p style="font-size:30px;color:orange">{}完成测试</p>'.format(faker.Faker(locale='zh_CN').name())text_html = MIMEText(_text=html, _subtype='html', _charset='utf-8')msg.attach(text_html)file_path = r'D:\zy0'with open(os.path.join(file_path, 'report_20201221_140614.html'), 'rb') as f:html = f.read()text_html = MIMEText(_text=html, _subtype='html', _charset='utf-8')msg.attach(text_html)file_list = [i for i in os.listdir(file_path)]file_list.extend([r'D:\0128postman.csv', r'D:\物业2.PNG'])for fl in file_list:f = os.path.join(file_path, fl)# print(f)with open(f, 'rb') as file:n = file.read()# fl = os.path.basename(fl)# # print(fl)# # file_name最好不要相同,收件邮箱可能会对其重命名part = MIMEApplication(n)part.add_header('Content-Disposition', 'attachment', filename=Header(fl, "utf-8").encode())msg.attach(part)my_send_email(receiver, [cc], msg)

zmail

# 使用zmail的好处就是不需要输入服务商地址、端口号等def send_text():receiver = 'zyooooxie@csdn.com'cc = 'zyooooxie@csdn.com'now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['zmail-text', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])text = '1.邮件是由zyooooxie推送;\n2.{}完成测试'.format(faker.Faker(locale='zh_CN').name())mail_content = {'subject': subject,'content_text': text}server = zmail.server(username=sender, password=pwd)server.send_mail(recipients=receiver, mail=mail_content, cc=cc)def send_html():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = 'zyooooxie@csdn.com'now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['zmail-html', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])body = """<p style="font-size:10px;color:red;line-height:90px">这由zyooooxie推送</p><p style="font-size:30px;color:orange">{}完成测试</p>""".format(faker.Faker(locale='zh_CN').name())mail_content = {'subject': subject,'content_html': body}server = zmail.server(username=sender, password=pwd)server.send_mail(recipients=receiver, mail=mail_content, cc=cc)def send_file():receiver = 'zyooooxie@csdn.com'cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['zmail-file', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])file_path = r'D:\zy0'file_list = [os.path.join(file_path, i) for i in os.listdir(file_path)]mail_content = {'subject': subject,'attachments': file_list}server = zmail.server(username=sender, password=pwd)server.send_mail(recipients=receiver, mail=mail_content, cc=cc)def send_text_html_file():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com', 'zyooooxie@csdn.com']now_time = time.strftime('%Y%m%d_%H%M%S')random_int = random.randint(10000, 99999)print(now_time, random_int)subject = ':'.join(['zmail-混合', '重要邮件通知', '{} '.format(now_time), '随机码:{}'.format(random_int)])file_path = r'D:\zy0'file_list = [os.path.join(file_path, i) for i in os.listdir(file_path)]file_list.extend([r'D:\0128postman.csv', r'D:\物业2.PNG'])text = '1.邮件是由zyooooxie推送;\n2.{}完成测试'.format(faker.Faker(locale='zh_CN').name())with open(os.path.join(file_path, 'report_20201221_140614.html'), 'rb') as f:html = f.read()body = """<p style="font-size:10px;color:red;line-height:90px">这由zyooooxie推送</p><p style="font-size:30px;color:orange">{}完成测试</p>""".format(faker.Faker(locale='zh_CN').name())# 图片添加到正文pic = os.path.join(file_path, 'Pycharm_wallpaper——壁纸.jpg')with open(pic, 'rb') as f:base64_data = base64.b64encode(f.read())new_html = """<img src="https://img-blog.csdnimg.cn/2022010619212247814.jpeg">""".format(base64_data.decode())mail_content = {'subject': subject,'attachments': file_list,'content_text': text,# Gmail始终不显示html的图片【下方2行都可用】'content_html': html.decode() + body + new_html# 'content_html': [html, body, new_html]}server = zmail.server(username=sender, password=pwd)server.send_mail(recipients=receiver, mail=mail_content, cc=cc)# 实际send_mail()代码中 with 已经关闭连接

yagmail


def send_text():receiver = 'zyooooxie@csdn.com'cc = 'zyooooxie@csdn.com'# qq邮箱、163邮箱 下面2行 通用;encoding='gbk'是PC的编码,读取file;email = yagmail.SMTP(user=gl_acc, password=gl_pwd, host=gl_server, encoding='gbk')# email = yagmail.SMTP(user=gl_acc, password=gl_pwd, host=gl_server, encoding='gbk', smtp_ssl=True)n = random.randint(10000, 99999)subject = '重要通知 yagmail-text:测试完成,随机码:{}'.format(n)contents = ['Tester:{} 已经完成测试'.format(f.name()), '第一段text', '第二段text']email.send(to=receiver, subject=subject, contents=contents, cc=cc)print('邮件发送成功 {}'.format(n))email.close()def send_html():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = 'zyooooxie@csdn.com'email = yagmail.SMTP(user=gl_acc, password=gl_pwd, host=gl_server, encoding='gbk')n = random.randint(10000, 99999)subject = '重要通知 yagmail-html:测试完成,随机码:{}'.format(n)# # 读取html 加载失败# with open(r'D:\zy0\百度一下,你就知道.html', 'r', encoding='utf-8') as ff:#     n = ff.read()html = r'D:\zy0\Pycharm_wallpaper——壁纸.jpg'contents = ['html第一段', 'html第二段',yagmail.inline(html),'<a href="https://www.baidu.com">某度</a>', '<p style="font-size:30px;color:orange">{}完成测试</p>'.format(f.name())]email.send(to=receiver, subject=subject, contents=contents, cc=cc)print('邮件发送成功 {}'.format(n))email.close()def send_file():receiver = 'zyooooxie@csdn.com'cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']email = yagmail.SMTP(user=gl_acc, password=gl_pwd, host=gl_server, encoding='gbk')n = random.randint(10000, 99999)subject = '重要通知 yagmail-file:测试完成,随机码:{}'.format(n)# contents列表中本地路径作为附件# 但Gmail 会将html作为 正文contents = ['Tester:{} 已经完成测试'.format(f.name()), '第一段file', '第二段file',r'D:\zy0\report_20201221_140614.html', r'D:\work\企业微信截图_16043843834371.png']# 最好不要使用相对路径的.file = [r'D:\0128postman.csv', r'D:\物业2.PNG']file_path = r'D:\zy0'file_list = [os.path.join(file_path, i) for i in os.listdir(file_path)]file.extend(file_list)email.send(to=receiver, subject=subject, contents=contents, attachments=file, cc=cc)print('邮件发送成功 {}'.format(n))email.close()def send_text_html_file():receiver = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']cc = ['zyooooxie@csdn.com', 'zyooooxie@csdn.com']email = yagmail.SMTP(user=gl_acc, password=gl_pwd, host=gl_server, encoding='gbk')n = random.randint(10000, 99999)subject = '重要通知 yagmail-混合:测试完成,随机码:{}'.format(n)file_path = r'D:\zy0'# 给邮件正文嵌入图片html = os.path.join(file_path, 'Pycharm_wallpaper——壁纸.jpg')file_list = [os.path.join(file_path, i) for i in os.listdir(file_path)]contents = ['Tester:{} 已经完成测试'.format(f.name()), '第一段-混合','<p style="font-size:30px;color:orange">{}完成测试</p>'.format(f.name()), '第二段--混合','<p>send email with inside picture</p>',# Only needed when wanting to inline an image rather than attach ityagmail.inline(html)]# Gmail 会将附件的HTML 作为 正文# 是因为yagmail库message.py prepare_message()中的代码:# # merge contents and attachments for now.# if attachments is not None:#     for a in attachments:#         if not os.path.isfile(a):#             raise TypeError("'{0}' is not a valid filepath".format(a))#     contents = attachments if contents is None else contents + attachmentsemail.send(to=receiver, subject=subject, contents=contents, attachments=file_list, cc=cc)print('邮件发送成功 {}'.format(n))email.close()

实际结果

实际不同邮箱 收到相同邮件时 正文内容、附件内容【文件名、文件是否存在】、邮件数量 有不同;

这一部分 不打算分享;我现在无法确定 相同邮件不同结果 到底是什么原因。

关于发邮件的分享到此为止;

交流技术 欢迎+QQ 153132336 zy
个人博客 https://blog.csdn.net/zyooooxie

Python使用smtplib、zmail、yagmail发送邮件相关推荐

  1. python发送邮件廖雪峰_利用Python的smtplib和email发送邮件

    原理 网上已经有了很多的教程讲解相关的发送邮件的原理,在这里还是推荐一下廖雪峰老师的Python教程,讲解通俗易懂.简要来说,SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本 ...

  2. Python通过smtplib发送邮件(2020最新最全版)

    smtplib 邮件自动发送 SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. pyt ...

  3. python封装sql脚本 github_Github 大牛封装 Python 代码,实现自动发送邮件只需三行代码...

    原标题:Github 大牛封装 Python 代码,实现自动发送邮件只需三行代码 在运维开发中,使用 Python 发送邮件是一个非常常见的应用场景.今天一起来探讨一下,GitHub 的大牛门是如何使 ...

  4. [Python] [邮件发送] 用Python的smtplib和email库进行邮件发送

    目录 1.Intro 2.Details 3.Theory 4.Environment 5.Source 6.Conclusion 1.Intro 眼看就到了12月中旬,除了帮朋友码竞赛题,前半个月可 ...

  5. Python使用网易的SMTP发送邮件554问题的解决

    Python使用网易的SMTP发送邮件554问题的解决 \quad 最近做个Python项目,需要用到发送邮件的功能,于是使用了网易的163邮箱作为SMTP服务器主机.但在使用过程中,有时候会出现代号 ...

  6. Python 使用第三方 SMTP 服务发送邮件(qq邮箱)

    原文链接:http://www.runoob.com/python/python-email.html Python SMTP发送邮件 SMTP(Simple Mail Transfer Protoc ...

  7. 用python实现自动化办公------定时发送邮件

    用python实现自动化办公------定时发送邮件 摘要 一.注册"和风天气" 二.用python获取和风天气响应的json数据 三.发送邮件 四.写入日志 程序源码 摘要 本文 ...

  8. email邮件中 内嵌iframe_邮件发送,使用Python中 smtplib与email 模块实现自动发送QQ邮件...

    在 Python 的实际应用中,特别是在执行周期性定时任务的场景中,我们希望能够一种简单.方便的方式获取任务的运行结果和状态.一般我们通过支持邮件发送功能的方式,实现任务结果的反馈.本文主要介绍,如何 ...

  9. python:smtplib --- SMTP 协议客户端

    python:smtplib --- SMTP 协议客户端 简介 SMTP 对象 SMTP 示例 简介 smtplib 模块定义了一个 SMTP 客户端会话对象,该对象可将邮件发送到互联网上任何带有 ...

  10. 使用Python的smtplib模块发送带附件的邮件

      上一篇文章<使用Python的smtplib模块发送简单邮件>介绍了调用smtplib模块发送包含简单内容的邮件,本文继续学习参考文献1中的发送带附件的邮件的示例代码,同时由于参考文献 ...

最新文章

  1. NYOJ-49 开心的小明
  2. java -jar 启动优化_Android 8.1 启动时间优化--耗时分析
  3. Java ByteArrayInputStream markSupported()方法与示例
  4. 关于js执行机制的理解
  5. java 人物头像识别
  6. 2022-2027年中国办公设备租赁市场竞争态势及行业投资潜力预测报告
  7. 硬件级光线追踪:移动游戏图形的变革时刻
  8. 玩转微信|两种微信批量删除好友教程
  9. HHUOJ 1887 班级聚会上的游戏
  10. 哈尔滨工业大学考研试题泄密了?官方通报:不存在
  11. 七牛云 vue 图片上传简单解说,js 上传文件图片
  12. java课程设计qq_Java课程设计(qq聊天程序)
  13. 宝泉岭计算机学校,2020年黑龙江计算机二级考点有哪些
  14. x-admin前端模板左侧菜单栏消除记忆功能(清除缓存)
  15. 寒假实习学习笔记总结
  16. Rust 在这个领域要大放异彩:一本新书推荐(附下载)
  17. Java乘船_船 - Minecraft Wiki,最详细的官方我的世界百科
  18. STM32F207串口通信配置
  19. MAC 彻底卸载PARAGON NTFS
  20. 基于java的档案管理系统

热门文章

  1. 安卓java:启动Bluedict深蓝词典 悬浮窗查词 intent, launch activity with params
  2. Axis2 中的 JAXB 和 JAX-WS
  3. DOTA2 插眼位置进行聚类分析,你也可以成为眼位大师
  4. IBM V7000错误代码及解决
  5. 安装配置Phoenix
  6. Google 音乐播放器
  7. HaaS506 - M320快速开始
  8. st-link v2怎么连接_【粉猪测评】入门级游戏鼠标怎么选(200内)
  9. linux会话空闲无法关机,解决linux的”turn off swap”无法关机问题
  10. 不变中谋变 华为云的坚持和赌注