# 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
import yagmail
yag = yagmail.SMTP('your_email@gmail.com', 'your_app_specific_password')
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_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='重要通知!'
)
錯誤現象:
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted')
解決方案: - 確保已開啟”允許不夠安全的應用” - 使用應用專用密碼而非賬戶密碼 - 檢查是否啟用了兩步驗證
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')
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, ...)
# 顯式指定編碼
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設計
# 完整示例模板
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字) 需要擴展哪部分內容可以告訴我,我可以繼續補充完善。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。