
- Python - 網路程式設計
- Python - 網路基礎
- Python - 網路環境
- Python - 網際網路協議
- Python - IP 地址
- Python - DNS 查詢
- Python - 路由
- Python - HTTP 請求
- Python - HTTP 響應
- Python - HTTP 頭部
- Python - 自定義 HTTP 請求
- Python - 請求狀態碼
- Python - HTTP 認證
- Python - HTTP 資料下載
- Python - 連線複用
- Python - 網路介面
- Python - 套接字程式設計
- Python - HTTP 客戶端
- Python - HTTP 伺服器
- Python - 構建 URL
- Python - Web 表單提交
- Python - 資料庫和 SQL
- Python - Telnet
- Python - 郵件訊息
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web 伺服器
- Python - 上傳資料
- Python - 代理伺服器
- Python - 目錄列表
- Python - 遠端過程呼叫
- Python - RPC JSON 伺服器
- Python - 谷歌地圖
- Python - RSS Feed
Python - SMTP
簡單郵件傳輸協議 (SMTP) 是一種協議,用於處理傳送電子郵件並在郵件伺服器之間路由電子郵件。
Python 提供了 **smtplib** 模組,該模組定義了一個 SMTP 客戶端會話物件,可用於將郵件傳送到任何具有 SMTP 或 ESMTP 監聽守護程式的網際網路機器。
SMTP 物件有一個名為 **sendmail** 的例項方法,通常用於執行傳送郵件的工作。它接受三個引數:
發件人 - 包含發件人地址的字串。
收件人 - 字串列表,每個收件人一個。
郵件內容 - 格式化為 RFC 中指定的格式的郵件字串。
示例
以下是如何使用 Python 指令碼傳送一封簡單電子郵件的方法。請嘗試一下:
#!/usr/bin/python3 import smtplib sender = 'from@fromdomain.com' receivers = ['to@todomain.com'] message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email"
在這裡,您使用三引號將基本電子郵件放在 message 中,並確保正確格式化標題。電子郵件需要 **From**、**To** 和 **Subject** 標題,並用空行與電子郵件正文隔開。
要傳送郵件,您使用 smtpObj 連線到本地機器上的 SMTP 伺服器。然後使用 sendmail 方法以及郵件內容、發件人和目標地址作為引數(即使發件人和收件人地址在電子郵件本身中,這些地址並不總是用於路由郵件)。
如果您在本地機器上沒有執行 SMTP 伺服器,則可以使用 smtplib 客戶端與遠端 SMTP 伺服器通訊。除非您使用 Web 郵件服務(如 Gmail 或 Yahoo! Mail),否則您的電子郵件提供商必須為您提供傳出郵件伺服器詳細資訊,您可以按如下方式提供:
mail = smtplib.SMTP('smtp.gmail.com', 587)
使用 Python 傳送 HTML 電子郵件
當您使用 Python 傳送文字訊息時,所有內容都將被視為純文字。即使您在文字訊息中包含 HTML 標籤,它也會顯示為純文字,並且 HTML 標籤不會根據 HTML 語法進行格式化。但是,Python 提供了一個選項可以將 HTML 訊息作為實際的 HTML 訊息傳送。
在傳送電子郵件訊息時,您可以指定 Mime 版本、內容型別和字元集以傳送 HTML 電子郵件。
示例
以下是如何將 HTML 內容作為電子郵件傳送的示例。請嘗試一下:
#!/usr/bin/python3 import smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email" except SMTPException: print "Error: unable to send email"