溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中怎么使用yagmail發送郵件功能

發布時間:2021-12-30 16:43:02 來源:億速云 閱讀:205 作者:iii 欄目:開發技術
# 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字) 需要擴展哪部分內容可以告訴我,我可以繼續補充完善。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女