有没有好用的Python发送邮件库推荐?
RT,有没有好用的发送邮件的 python 库推荐
最好能以某个写好的 html 作为邮件正文
有没有好用的Python发送邮件库推荐?
4 回复
python 标准库里的就很好用呀
推荐使用Python内置的smtplib和email库,它们功能完整且无需额外安装。对于需要更便捷功能的场景,yagmail和zmail是不错的选择。
1. 标准方案:smtplib + email 这是Python标准库的方案,适合需要精细控制邮件内容的情况:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email_smtplib():
# 配置
sender = "your_email@gmail.com"
receiver = "receiver@example.com"
password = "your_app_password" # 使用应用专用密码
# 创建邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = "测试邮件"
# 正文
body = "这是一封测试邮件"
msg.attach(MIMEText(body, 'plain'))
# 发送
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(sender, password)
server.send_message(msg)
print("邮件发送成功")
except Exception as e:
print(f"发送失败: {e}")
# 使用示例
send_email_smtplib()
2. 便捷方案:yagmail
如果追求简洁,yagmail让发送邮件变得非常简单:
import yagmail
def send_email_yagmail():
yag = yagmail.SMTP('your_email@gmail.com', 'your_app_password')
contents = ['正文内容', '可添加附件: /path/to/file.txt']
yag.send('receiver@example.com', '邮件主题', contents)
# 先安装:pip install yagmail
3. 现代方案:zmail
zmail的API设计更符合Python风格:
import zmail
def send_email_zmail():
server = zmail.server('your_email@gmail.com', 'your_app_password')
mail = {
'subject': '邮件主题',
'content_text': '正文内容',
'attachments': ['/path/to/file.txt']
}
server.send_mail('receiver@example.com', mail)
# 先安装:pip install zmail
选择建议:
- 需要标准库方案或精细控制:用
smtplib+email - 追求简单快速:用
yagmail - 喜欢现代API设计:用
zmail
一句话总结:根据需求选择,标准库最稳妥,第三方库更便捷。
https://gist.github.com/kba977/c7bd48acfeeac95819d0#file-simple_smtp-py
html 的话 可以先写好一个模板 留好变量 然后用 jinja 渲染一下就好了
envelopes

