一、SMTP發送郵件介紹
SMTP(Simple Mail Transfer Protocol)即簡單郵件傳送協議,是一種用於發送電子郵件的常用協議。
使用Python可以通過SMTP協議來發送郵件,本文將介紹Python中SMTP郵件發送的方法,包括郵件的構造及其發送。
二、SMTP發送郵件的基本流程
Python中SMTP發送郵件的基本流程如下:
- 連接郵件伺服器
- 構造郵件
- 發送郵件
- 檢查SMTP服務地址和埠是否正確
- 檢查SMTP服務是否開啟
- 檢查網路是否正常
- 設置SSL加密連接
- 檢查郵件格式是否符合規範
- 檢查編碼格式是否正確
- 設置附件
import smtplib
smtp_server = 'smtp.qq.com'
smtp_port = 465 # qq郵箱SMTP埠
smtp_user = 'xxx@qq.com' # 郵箱賬戶
smtp_password = 'xxxxx' # 郵箱密碼
# SSL加密連接
smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
# 登錄郵箱賬戶
smtp.login(smtp_user, smtp_password)
from email.mime.text import MIMEText
sender = 'xxx@qq.com'
receivers = ['xxx@qq.com', 'xxx@163.com'] # 郵件收件人列表
# 構造郵件內容
text = '測試郵件'
msg = MIMEText(text, 'plain', 'utf-8')
msg['From'] = sender
msg['To'] = ','.join(receivers)
msg['Subject'] = 'Python SMTP測試'
# 添加附件
with open('sample.txt', 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename="sample.txt"'
msg.attach(attachment)
# 發送郵件
smtp.sendmail(sender, receivers, msg.as_string())
# 關閉連接
smtp.quit()
三、SMTP發送郵件常見問題解決方法
1. SMTP連接報錯
有時可能會遇到SMTP連接異常的情況,一般有以下解決方法:
smtp_server = 'smtp.qq.com'
smtp_port = 465 # qq郵箱SMTP埠
smtp_user = 'xxx@qq.com' # 郵箱賬戶
smtp_password = 'xxxxx' # 郵箱密碼
有些SMTP服務需要手動開啟,如QQ郵箱的SMTP服務需要在郵箱設置中手動開啟。
網路異常也可能導致SMTP連接異常,需要檢查網路是否正常。
一些SMTP服務需要通過SSL加密連接,需要在連接SMTP時設置SSL加密。
smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
2. 郵件內容報錯
當郵件內容不符合SMTP協議規範時,可能會發生郵件發送失敗的情況,一般有以下解決方法:
郵件格式需要符合SMTP協議規範,如郵件頭部需要包含From、To、Subject等欄位。
郵件內容主體需要使用正確的編碼格式,一般使用utf-8編碼。
如果需要發送附件,需要使用MIMEText添加附件並設置正確的Content-Type和Content-Disposition。
with open('sample.txt', 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename="sample.txt"'
msg.attach(attachment)
四、完整代碼示例
import smtplib
from email.mime.text import MIMEText
smtp_server = 'smtp.qq.com'
smtp_port = 465 # qq郵箱SMTP埠
smtp_user = 'xxx@qq.com' # 郵箱賬戶
smtp_password = 'xxxxx' # 郵箱密碼
# SSL加密連接
smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
# 登錄郵箱賬戶
smtp.login(smtp_user, smtp_password)
sender = 'xxx@qq.com'
receivers = ['xxx@qq.com', 'xxx@163.com'] # 郵件收件人列表
# 構造郵件內容
text = '測試郵件'
msg = MIMEText(text, 'plain', 'utf-8')
msg['From'] = sender
msg['To'] = ','.join(receivers)
msg['Subject'] = 'Python SMTP測試'
# 添加附件
with open('sample.txt', 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename="sample.txt"'
msg.attach(attachment)
# 發送郵件
smtp.sendmail(sender, receivers, msg.as_string())
# 關閉連接
smtp.quit()
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257597.html