跳轉到內容

Python 程式設計/電子郵件

來自華夏公益教科書,開放的書籍,開放的世界


Python 在標準庫中包含幾個模組,用於處理電子郵件和電子郵件伺服器。

傳送郵件

[編輯 | 編輯原始碼]

使用 Python 的 smtplib 和 SMTP(簡單郵件傳輸協議)伺服器來發送郵件。實際使用情況根據電子郵件的複雜性和電子郵件伺服器的設定而有所不同,此處的說明基於透過 Google 的 Gmail 傳送電子郵件。

第一步是建立一個 SMTP 物件,每個物件用於與一個伺服器連線。

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)

第一個引數是伺服器的主機名,第二個是埠。使用的埠根據伺服器的不同而不同。

接下來,我們需要執行一些步驟來設定傳送郵件的正確連線。

server.ehlo()
server.starttls()
server.ehlo()

這些步驟可能並非總是必要,具體取決於您連線的伺服器。ehlo() 用於 ESMTP 伺服器,對於非 ESMTP 伺服器,請改用 helo()。有關此內容的更多資訊,請參閱維基百科關於 SMTP 協議的文章。starttls() 函式啟動 傳輸層安全 模式,這是 Gmail 所要求的。其他郵件系統可能不使用此模式,或者此模式可能不可用。

接下來,登入到伺服器

server.login("youremailusername", "password")

然後,傳送郵件

msg = "\nHello!" # The \n separates the message from the headers (which we ignore for this example)
server.sendmail("you@gmail.com", "target@example.com", msg)

請注意,這是一個相當粗糙的示例,它不包括主題或任何其他標題。為此,應使用 email 包。

email

[編輯 | 編輯原始碼]

Python 的 email 包包含許多用於撰寫和解析電子郵件的類和函式,本節僅介紹一小部分用於傳送電子郵件的類和函式。

我們首先只匯入所需的類,這也可以讓我們在以後避免使用完整的模組名。

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

然後,我們撰寫一些基本的訊息標題

fromaddr = "you@gmail.com"
toaddr = "target@example.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Python email"

接下來,我們將電子郵件正文附加到 MIME 訊息

body = "Python test mail"
msg.attach(MIMEText(body, 'plain'))

為了傳送郵件,我們必須將物件轉換為字串,然後使用與上面相同的步驟透過 SMTP 伺服器傳送。

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("youremailusername", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

如果檢視文字,我們會發現它添加了所有必要的標題和結構,這些標題和結構對於 MIME 格式的電子郵件是必要的。有關此標準的更多詳細資訊,請參閱 MIME

我們示例訊息的完整文字
>>> print text
Content-Type: multipart/mixed; boundary="===============1893313573=="
MIME-Version: 1.0
From: you@gmail.com
To: target@example.com
Subject: Python email

--===============1893313573==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Python test mail
--===============1893313573==--


華夏公益教科書