python编辑邮件格式_python 3.6 发邮件(html格式,带附件)

关于用 python 发邮件,搜出来的大部分代码都是 legacy code,而系统带的是 python 3.6,所以想试试 email 标准库的最新用法。

一番折腾,发现官方文档不够详尽,而且还引了一堆 rfc,涉及 email 的格式标准,头大,还是耐着性子整完了。

把最好的献给这世界,也许永远都不够。

———— 一位出家师父

#!/usr/bin/env python3

#~ 参考:

#~ https://docs.python.org/3.6/library/email.examples.html

#~ https://docs.python.org/3.6/library/email.message.html

#~ http://www.runoob.com/python3/python3-smtp.html

import smtplib

from email.message import EmailMessage

from email.headerregistry import Address, Group

import email.policy

import mimetypes

# 发送邮件服务器

smtp_server = "smtp.126.com"

user = "jack@126.com"

# 自己的客户端授权码

passwd = "客户端授权码"

# 发件人和收件人

# 直接用字符串也行,这里为了方便使用 display name

sender = Address("无明", "jack", "126.com") # 相当于 "无明 "

recipient = Group(addresses=(Address("解脱", "kate", "qq.com"), ))

# Use utf-8 encoding for headers. SMTP servers must support the SMTPUTF8 extension

# https://docs.python.org/3.6/library/email.policy.html

msg = EmailMessage(email.policy.SMTPUTF8)

# 邮件头和内容

msg['From'] = sender

msg['To'] = recipient

msg['Subject'] = 'smtp 测试'

msg.set_content("""

雪山偈

诸行无常,是生灭法。

生灭灭已,寂灭为乐。

""", subtype="html")

# 添加附件

filename = "test.zip"

ctype, encoding = mimetypes.guess_type(filename)

if ctype is None or encoding is not None:

# No guess could be made, or the file is encoded (compressed), so

# use a generic bag-of-bits type.

ctype = 'application/octet-stream'

maintype, subtype = ctype.split('/', 1)

with open(filename, 'rb') as fp:

msg.add_attachment(fp.read(), maintype, subtype, filename=filename)

# SSL

with smtplib.SMTP_SSL(smtp_server) as smtp:

# HELO向服务器标志用户身份

smtp.ehlo_or_helo_if_needed()

# 登录邮箱服务器

smtp.login(user, passwd)

print(f"Email: {str(sender)} ==> {str(recipient)}")

smtp.send_message(msg)

print("Sent!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值