簡單郵件傳輸協議 (SMTP) 是一種協議,用于處理在郵件服務器之間發送電子郵件和路由電子郵件。
Python 提供了smtplib模塊,該模塊定義了一個 SMTP 客戶端會話對象,該對象可用于將郵件發送到具有 SMTP 或 ESMTP 偵聽器守護程序的任何 Internet 機器。
這是創建一個 SMTP 對象的簡單語法,稍后可用于發送電子郵件 -
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
這是參數的詳細信息 -
host - 這是運行 SMTP 服務器的主機。您可以指定主機的 IP 地址或域名,如 tutorialspoint.com。這是可選參數。
port - 如果您提供主機參數,那么您需要指定一個端口,SMTP 服務器正在偵聽該端口。通常這個端口是 25。
local_hostname - 如果您的 SMTP 服務器在本地計算機上運行,那么您可以在此選項中僅指定localhost。
SMTP 對象有一個名為sendmail的實例方法,通常用于完成郵寄消息的工作。它需要三個參數 -
發件人- 帶有發件人地址的字符串。
接收者- 字符串列表,每個接收者一個。
消息- 作為字符串的消息,格式為各種 RFC 中指定的格式。
例子
這是使用 Python 腳本發送一封電子郵件的簡單方法。嘗試一次 -
#!/usr/bin/python
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"
在這里,您在消息中放置了一個基本的電子郵件,使用三引號,注意正確格式化標題。電子郵件需要From、To和Subject標頭,并用空行與電子郵件正文分開。
要發送郵件,您可以使用smtpObj連接到本地計算機上的 SMTP 服務器,然后使用sendmail方法以及消息、發件人地址和目標地址作為參數(即使發件人地址和發件人地址在 e -mail 本身,這些并不總是用于路由郵件)。
如果您沒有在本地計算機上運行 SMTP 服務器,則可以使用smtplib客戶端與遠程 SMTP 服務器進行通信。除非您使用網絡郵件服務(例如 Hotmail 或 Yahoo! Mail),否則您的電子郵件提供商必須向您提供您可以提供的外發郵件服務器詳細信息,如下所示 -
smtplib.SMTP('mail.your-domain.com', 25)
使用 Python 發送 HTML 電子郵件
當您使用 Python 發送文本消息時,所有內容都被視為簡單文本。即使您在文本消息中包含 HTML 標記,它也會顯示為簡單文本,并且 HTML 標記不會根據 HTML 語法進行格式化。但是 Python 提供了將 HTML 消息作為實際 HTML 消息發送的選項。
發送電子郵件時,您可以指定 Mime 版本、內容類型和字符集以發送 HTML 電子郵件。
例子
以下是將 HTML 內容作為電子郵件發送的示例。嘗試一次 -
#!/usr/bin/python
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"
以電子郵件形式發送附件
要發送包含混合內容的電子郵件,需要將Content-type標頭設置為multipart/mixed。然后,可以在邊界內指定文本和附件部分。
邊界以兩個連字符開頭,后跟一個唯一編號,該編號不能出現在電子郵件的消息部分中。表示電子郵件最后部分的最后邊界也必須以兩個連字符結尾。
附加文件應使用pack("m")函數進行編碼,以便在傳輸前進行 base64 編碼。
例子
以下是示例,它將文件/tmp/test.txt作為附件發送。嘗試一次 -
#!/usr/bin/python
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"