Python語言實用性非常強,發送郵件也是Python功能之一。Python內置對SMTP的支持。使用SMTP可以發送電子郵件,SMTP則是Python處理電子郵件的標準協議。
一、連接SMTP服務器
要使用SMTP發送郵件,必須首先進行SMTP服務器的連接,Python的SMTP庫提供了SMTP類,可以方便地和SMTP服務器進行對話。連接SMTP服務器,需要在Python腳本中引入SMTP模塊,示例如下:
import smtplib
使用SMTP類,需要創建SMTP對象實例,需要傳入SMTP主機地址和端口號。不同郵件服務提供商的SMTP服務器地址不同。以下代碼以QQ郵箱為例示範SMTP連接:
# 導入SMTP模塊 import smtplib # 配置郵箱服務器地址和端口號 SMTP_SERVER = 'smtp.qq.com' SMTP_PORT = 465 # 登錄郵箱服務器 server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
在創建SMTP對象實例時,為了確保用戶的個人信息安全,可以選擇採用SSL協議進行SMTP連接。
在SMTP連接成功後,還需要進行登錄認證。使用SMTP對象的login方法可以輕鬆地進行郵件服務器認證:
# 登錄郵箱服務器 server.login(sender_email, password)
其中,sender_email為郵件發送方郵箱,password為登錄郵箱對應的密碼。
二、構建郵件
SMTP連接成功後,就可以進行郵件的構建了。Python的email庫提供了EmailMessage類,可以輕鬆地構建郵件。以下是Python構建郵件的示例代碼:
from email.message import EmailMessage # 創建EmailMessage對象 message = EmailMessage() # 設置郵件主題 message['Subject'] = 'Python SMTP發送郵件的簡易教程' # 添加接收方地址 recipients = ['receiver_1@example.com', 'receiver_2@example.com'] message['To'] = ', '.join(recipients) # 添加郵件正文 message.set_content('這是一封Python SMTP發送的簡易教程郵件。') # 添加郵件附件 attachment_path = r'/path/to/attachment/file' with open(attachment_path, 'rb') as file: attachment_data = file.read() attachment_name = 'attachment.txt' message.add_attachment(attachment_data, maintype='application', subtype='octet-stream', filename=attachment_name)
EmailMessage對象包含郵件的主題、收件人、郵件正文和附件等信息。要添加附件,可以使用EmailMessage對象的add_attachment方法添加附件。需要注意的是,添加附件需要將附件內容讀入內存,然後作為參數傳遞。
三、發送郵件
構建好郵件之後,就可以使用SMTP類的send_message方法將郵件發送出去了:
# 發送郵件 server.send_message(from_addr=sender_email, to_addrs=recipients, msg=message) # 關閉SMTP連接 server.quit()
send_message方法接收發件人、收件人和郵件內容作為參數,並將郵件發送出去。發送完成後,還需要使用SMTP類的quit方法關閉SMTP連接
四、完整示例
以下是Python SMTP發送郵件的完整示例:
import smtplib from email.message import EmailMessage # 配置郵箱服務器地址和端口號 SMTP_SERVER = 'smtp.qq.com' SMTP_PORT = 465 # 郵箱賬號和密碼 sender_email = 'your_email@example.com' password = 'your_password' # 接收方郵箱 recipients = ['recipient_1@example.com', 'recipient_2@example.com'] # 創建SMTP連接 server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) # 登錄郵箱 server.login(sender_email, password) # 創建EmailMessage對象 message = EmailMessage() # 設置郵件主題 message['Subject'] = 'Python SMTP發送郵件的簡易教程' # 添加接收方地址 message['To'] = ', '.join(recipients) # 添加郵件正文 message.set_content('這是一封Python SMTP發送的簡易教程郵件。') # 添加郵件附件 attachment_path = r'/path/to/attachment/file' with open(attachment_path, 'rb') as file: attachment_data = file.read() attachment_name = 'attachment.txt' message.add_attachment(attachment_data, maintype='application', subtype='octet-stream', filename=attachment_name) # 發送郵件 server.send_message(from_addr=sender_email, to_addrs=recipients, msg=message) # 關閉SMTP連接 server.quit()
以上就是Python SMTP發送郵件的簡易教程,可以輕鬆地使用Python發送電子郵件了。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/244367.html