使用 Python 連接到 SMTP 服務器

簡單郵件傳輸協議 (SMTP) 是最常用的電子郵件協議,用於處理從客戶端應用程序向電子郵件服務器發送電子郵件消息。在各種情況下,電子郵件客戶端在 Python 應用程序中實現,以通過 SMTP 發送電子郵件。對於此類場景,本文介紹瞭如何使用 Python 連接到 SMTP 服務器。此外,它還演示瞭如何通過 SMTP 發送電子郵件。

用於連接 SMTP 服務器的 Python 庫

Aspose.Email for Python via .NET 是一個用於創建、發送和操作電子郵件的 Python 庫。它允許您在 Python 中無縫地實現您自己的電子郵件客戶端。我們將使用這個庫連接到 SMTP 服務器。您可以使用以下命令從 PyPI 安裝庫。

pip install Aspose.Email-for-Python-via-NET

或者,您可以按照以下步驟進行手動安裝。

  • 下載 部分下載可安裝的 .whl 文件。
  • 在命令行中,使用命令:pip install «FileName> >.whl 安裝 API。
  • GitHub 下載完整的源代碼示例包。

在 Python 中連接到 SMTP 服務器

在連接到 SMTP 服務器之前,您需要了解以下內容。

  • 用戶名
  • 密碼
  • 港口

擁有它們後,您可以使用以下步驟配置 SMTP 客戶端。

  • 首先,創建一個 SmtpClient 類的對象。
  • 然後,分別使用 SmtpClient.host、SmtpClient.username、SmtpClient.password 和 SmtpClient.port 屬性設置主機、用戶名、密碼和端口號。
  • 使用 SmtpClient.securityoptions 屬性設置安全選項。
  • 最後,繼續使用 SmtpClient 對象訪問郵箱。

以下代碼示例顯示瞭如何使用 Python 與 SMTP 服務器建立連接。

import aspose.email as ae
from aspose.email import SecurityOptions, SmtpClient

# 創建 SMTP 客戶端 
client = SmtpClient()

# 設置主機、端口、用戶名和密碼
client.host = "smtp.gmail.com"
client.port = 587
client.username = "username"
client.password = "password"

# 為支持 SSL 的服務器設置安全選項
client.security_options = SecurityOptions.SSLEXPLICIT
    

在 Python 中通過 SMTP 發送電子郵件

與 SMTP 服務器建立連接後,就可以發送郵件了。以下代碼示例顯示瞭如何在 Python 中通過 SMTP 發送電子郵件。

import aspose.email as ae
from aspose.email import SecurityOptions, SmtpClient
    
# 創建新消息
eml = ae.MailMessage()

# 設置主題、正文、往返地址
eml.subject = "Message with Html Body"
eml.is_body_html = True
eml.html_body = "<html><body>This is the <b>HTML</b>body</body></html>"
eml.from_address = "from@gmail.com"
eml.to.append(ae.MailAddress("to@gmail.com", "Recipient 1"))

# 使用 Smtp 客戶端發送電子郵件
client = SmtpClient("smtp.gmail.com", 995, "username", "password")
client.security_options = SecurityOptions.AUTO
client.send(eml)
    

獲取免費的 API 許可證

您可以通過 .NET 免費使用 Aspose.Email for Python 獲得臨時許可證

結論

在本文中,您學習瞭如何使用 Python 連接到 SMTP 服務器。此外,您還了解瞭如何在 Python 中通過 SMTP 發送電子郵件。您可以訪問 文檔 以通過 .NET 探索更多關於 Aspose.Email for Python 的信息。如果您有任何問題或疑問,請隨時通過我們的 論壇 告訴我們。

也可以看看