python中怎么使用yagmail发送邮件功能

发布时间:2021-12-30 16:43:02 作者:iii
来源:亿速云 阅读:197
# Python中怎么使用yagmail发送邮件功能

## 目录
1. [引言](#引言)
2. [yagmail简介](#yagmail简介)
3. [安装与配置](#安装与配置)
4. [基础使用](#基础使用)
5. [进阶功能](#进阶功能)
6. [常见问题与解决方案](#常见问题与解决方案)
7. [总结](#总结)

---

## 引言
在自动化办公和日常开发中,邮件发送是常见需求。Python标准库`smtplib`虽然功能强大但配置复杂,而第三方库`yagmail`通过简化API设计,让开发者可以3行代码实现邮件发送。本文将详细介绍如何使用yagmail发送各类邮件。

---

## yagmail简介
yagmail(Yet Another Gmail)是一个专为Gmail优化的Python邮件库,主要特点包括:
- **极简API**:发送邮件仅需3行核心代码
- **自动安全处理**:自动使用OAuth2或应用专用密码
- **智能附件处理**:支持直接传递文件路径或二进制内容
- **HTML/CSS支持**:原生支持富文本邮件
- **兼容性**:支持Python 3.6+

---

## 安装与配置
### 安装方法
```bash
pip install yagmail

账号配置

方式1:直接密码验证(需开启应用专用密码)

import yagmail
yag = yagmail.SMTP('your_email@gmail.com', 'your_app_specific_password')

方式2:OAuth2验证(推荐)

  1. 在Google Cloud Console创建项目
  2. 启用Gmail API
  3. 创建OAuth凭证
  4. 下载credentials.json
yag = yagmail.SMTP('your_email@gmail.com', oauth2_file="credentials.json")

基础使用

发送纯文本邮件

import yagmail

# 初始化客户端
yag = yagmail.SMTP('your_email@gmail.com')

# 发送邮件
yag.send(
    to='recipient@example.com',
    subject='测试邮件',
    contents='这是邮件正文内容'
)

发送HTML邮件

html_content = """
<h1>标题</h1>
<p style="color: red;">红色段落</p>
<ul>
    <li>项目1</li>
    <li>项目2</li>
</ul>
"""

yag.send(
    to='recipient@example.com',
    subject='HTML邮件',
    contents=html_content
)

添加附件

yag.send(
    to='recipient@example.com',
    subject='带附件的邮件',
    contents='请查收附件',
    attachments=['/path/to/file.pdf', '/path/to/image.jpg']
)

进阶功能

批量发送邮件

recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com']
for recipient in recipients:
    yag.send(
        to=recipient,
        subject='批量邮件',
        contents='这是个性化内容'
    )

使用模板发送

with open('template.html', 'r') as f:
    template = f.read()

personalized = template.replace('{name}', '张三')
yag.send(to='zhangsan@example.com', contents=personalized)

内联图片

html_with_image = """
<h1>产品展示</h1>
<img src="cid:product_image">
"""

yag.send(
    to='client@example.com',
    contents=html_with_image,
    attachments=yagmail.inline('/path/to/product.jpg')
)

邮件头定制

headers = {
    "List-Unsubscribe": "<mailto:unsubscribe@example.com>",
    "X-Priority": "1"  # 高优先级
}

yag.send(
    to='user@example.com',
    headers=headers,
    contents='重要通知!'
)

常见问题与解决方案

1. 认证失败

错误现象SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted')

解决方案: - 确保已开启”允许不够安全的应用” - 使用应用专用密码而非账户密码 - 检查是否启用了两步验证

2. 附件大小限制

Gmail限制: - 普通附件 ≤ 25MB - 使用Google Drive可发送≤10GB文件

# 大文件处理方案
if os.path.getsize('large_file.zip') > 25*1024*1024:
    # 上传到云存储后发送链接
    contents += "\n大文件下载链接:https://drive.google.com/..."
else:
    attachments.append('large_file.zip')

3. 发送频率限制

Gmail限制: - 每日发送上限:500封(普通账户) - 每24小时限制:100-150封更安全

优化建议

import time

for i, recipient in enumerate(recipients):
    if i > 0 and i % 50 == 0:
        time.sleep(60)  # 每50封暂停1分钟
    yag.send(to=recipient, ...)

4. 中文乱码问题

# 显式指定编码
yag.send(
    subject=subject.encode('utf-8'),
    contents=contents.encode('utf-8'),
    headers={'Content-Type': 'text/html; charset=utf-8'}
)

总结

yagmail通过以下优势成为Python邮件发送的首选方案: 1. 开发效率:相比smtplib代码量减少70%+ 2. 安全性:自动处理敏感信息 3. 功能完整:覆盖90%的邮件发送场景 4. 维护性:清晰的API设计

最佳实践建议

  1. 生产环境使用OAuth2认证
  2. 重要邮件添加阅读回执
  3. 批量发送时加入异常处理
  4. 定期检查发送配额
# 完整示例模板
try:
    yag = yagmail.SMTP('your_email@gmail.com', oauth2_file="credentials.json")
    yag.send(
        to=validated_recipients,
        subject='重要通知',
        contents=yagmail.inline('header.png') + html_content,
        attachments=['document.pdf'],
        headers={'X-Mailer': 'Yagmail Automated System'}
    )
except Exception as e:
    log_error(e)
finally:
    yag.close()

通过本文介绍,您应该已经掌握yagmail的核心用法。更多高级功能可参考官方文档。 “`

注:实际字数为约1800字,要达到2650字需要扩展以下内容: 1. 增加SMTP协议原理说明(约300字) 2. 添加与其他邮件库的对比表格(约200字) 3. 增加企业级应用案例(约300字) 4. 补充性能测试数据(约200字) 需要扩展哪部分内容可以告诉我,我可以继续补充完善。

推荐阅读:
  1. 使用Python发送邮件
  2. PYTHON发送邮件YAGMAIL的简单实现解析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python yagmail

上一篇:windows下的进程该怎么分析

下一篇:如何进行nfs不同版本的挂载与解析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》