SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。
python的smtplib提供了一種很方便的途徑發送電子郵件。它對smtp協議進行了簡單的封裝。
Python創建 SMTP 對象語法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
參數說明:
- host: SMTP 服務器主機。 你可以指定主機的ip地址或者域名如:runoob.com,這個是可選參數。
- port: 如果你提供了 host 參數, 你需要指定 SMTP 服務使用的端口號,一般情況下SMTP端口號爲25。
- local_hostname: 如果SMTP在你的本機上,你只需要指定服務器地址爲 localhost 即可。
Python SMTP對象使用sendmail方法發送郵件,語法如下:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
參數說明:
- from_addr: 郵件發送者地址。
- to_addrs: 字符串列表,郵件發送地址。
- msg: 發送消息
msg是字符串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。
實例
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]'] # 接收郵件,可設置爲你的QQ郵箱或者其他郵箱
# 三個參數:第一個爲文本內容,第二個 plain 設置文本格式,第三個 utf-8 設置編碼
message = MIMEText('Python 郵件發送測試...', 'plain', 'utf-8')
message['From'] = Header("菜鳥教程", 'utf-8') # 發送者
message['To'] = Header("測試", 'utf-8') # 接收者
subject = 'Python SMTP 郵件測試'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.login(sender, "password",)
smtpObj.sendmail(sender, receivers, message.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")
使用三個引號來設置郵件信息,標準郵件需要三個頭部信息: From, To, 和 Subject ,每個信息直接使用空行分割。
通過實例化 smtplib 模塊的 SMTP 對象 smtpObj 來連接到 SMTP 訪問,並使用 sendmail 方法來發送信息。
如果我們本機沒有 sendmail 訪問,也可以使用其他服務商的 SMTP 訪問(QQ、網易、Google等)。
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服務
mail_host="smtp.XXX.com" #設置服務器
mail_user="XXXX" #用戶名
mail_pass="XXXXXX" #口令
sender = '[email protected]'
receivers = ['[email protected]'] # 接收郵件,可設置爲你的QQ郵箱或者其他郵箱
message = MIMEText('Python 郵件發送測試...', 'plain', 'utf-8')
message['From'] = Header("菜鳥教程", 'utf-8')
message['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 爲 SMTP 端口號
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")
使用Python發送HTML格式的郵件
Python發送HTML格式的郵件與發送純文本消息的郵件不同之處就是將MIMEText中_subtype設置爲html。具體代碼如下:
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]'] # 接收郵件,可設置爲你的QQ郵箱或者其他郵箱
mail_msg = """
<p>Python 郵件發送測試...</p>
<p><a href="http://www.runoob.com">這是一個鏈接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("菜鳥教程", 'utf-8')
message['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")
Python 發送帶附件的郵件
發送帶附件的郵件,首先要創建MIMEMultipart()實例,然後構造附件,如果有多個附件,可依次構造,最後利用smtplib.smtp發送。
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]'] # 接收郵件,可設置爲你的QQ郵箱或者其他郵箱
#創建一個帶附件的實例
message = MIMEMultipart()
message['From'] = Header("菜鳥教程", 'utf-8')
message['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
message['Subject'] = Header(subject, 'utf-8')
#郵件正文內容
message.attach(MIMEText('這是菜鳥教程Python 郵件發送測試……', 'plain', 'utf-8'))
# 構造附件1,傳送當前目錄下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)
# 構造附件2,傳送當前目錄下的 runoob.txt 文件
att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
message.attach(att2)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")
在 HTML 文本中添加圖片
郵件的 HTML 文本中一般郵件服務商添加外鏈是無效的,正確添加圖片的實例如下所示:
#!/usr/bin/python3
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]'] # 接收郵件,可設置爲你的QQ郵箱或者其他郵箱
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("菜鳥教程", 'utf-8')
msgRoot['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
mail_msg = """
<p>Python 郵件發送測試...</p>
<p><a href="http://www.runoob.com">菜鳥教程鏈接</a></p>
<p>圖片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
# 指定圖片爲當前目錄
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定義圖片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msgRoot.as_string())
print ("郵件發送成功")
except smtplib.SMTPException:
print ("Error: 無法發送郵件")
使用第三方 SMTP 服務發送
(這一步我沒有測試,因爲前面我是用騰訊企業郵箱往自己QQ郵箱發送的)
這裏使用了 QQ 郵箱(你也可以使用 163,Gmail等)的 SMTP 服務,需要做以下配置:
QQ 郵箱通過生成授權碼來設置密碼:
QQ 郵箱 SMTP 服務器地址:smtp.qq.com,ssl 端口:465。
以下實例你需要修改:發件人郵箱(你的QQ郵箱),密碼,收件人郵箱(可發給自己)。
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
my_sender='[email protected]' # 發件人郵箱賬號
my_pass = 'xxxxxxxxxx' # 發件人郵箱密碼
my_user='[email protected]' # 收件人郵箱賬號,我這邊發送給自己
def mail():
ret=True
try:
msg=MIMEText('填寫郵件內容','plain','utf-8')
msg['From']=formataddr(["FromRunoob",my_sender]) # 括號裏的對應發件人郵箱暱稱、發件人郵箱賬號
msg['To']=formataddr(["FK",my_user]) # 括號裏的對應收件人郵箱暱稱、收件人郵箱賬號
msg['Subject']="菜鳥教程發送郵件測試" # 郵件的主題,也可以說是標題
server=smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的SMTP服務器,端口是25
server.login(my_sender, my_pass) # 括號中對應的是發件人郵箱賬號、郵箱密碼
server.sendmail(my_sender,[my_user,],msg.as_string()) # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
server.quit() # 關閉連接
except Exception: # 如果 try 中的語句沒有執行,則會執行下面的 ret=False
ret=False
return ret
ret=mail()
if ret:
print("郵件發送成功")
else:
print("郵件發送失敗")
更多內容請參閱:https://docs.python.org/3/library/email-examples.html。
IDEA 下的測試代碼send Email.py
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = '[email protected]'
receivers = ['[email protected]']
# TEXT
# message = MIMEText('Python3 郵件發佈測試...', 'plain', 'utf-8')
# HTML
# mail_msg = """
# <p>Python 郵件發送測試...</p>
# <p><a href="http://www.runoob.com">這是一個鏈接</a></p>
# """
# message = MIMEText(mail_msg, 'html', 'utf-8')
# message['From'] = Header('菜鳥教程', 'utf-8')
# message['To'] = Header('測試', 'utf-8')
#
# subject = 'Python SMTP 郵件測試'
# message['Subject'] = Header(subject, 'utf-8')
# 發送帶附件的郵件
#創建一個帶附件的實例
# message = MIMEMultipart()
# message['From'] = Header("菜鳥教程", 'utf-8')
# message['To'] = Header("測試", 'utf-8')
# subject = 'Python SMTP 郵件測試'
# message['Subject'] = Header(subject, 'utf-8')
#
# #郵件正文內容
# message.attach(MIMEText('這是菜鳥教程Python 郵件發送測試……', 'plain', 'utf-8'))
#
# # 構造附件1,傳送當前目錄下的 test.txt 文件
# att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
# att1["Content-Type"] = 'application/octet-stream'
# # 這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
# att1["Content-Disposition"] = 'attachment; filename="test.txt"'
# message.attach(att1)
#
# # 構造附件2,傳送當前目錄下的 runoob.txt 文件
# att2 = MIMEText(open('../other/runoob.txt', 'rb').read(), 'base64', 'utf-8')
# att2["Content-Type"] = 'application/octet-stream'
# att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
# message.attach(att2)
# 在 HTML 文本中添加圖片
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("菜鳥教程", 'utf-8')
msgRoot['To'] = Header("測試", 'utf-8')
subject = 'Python SMTP 郵件測試'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
mail_msg = """
<p>Python 郵件發送測試...</p>
<p><a href="http://www.runoob.com">菜鳥教程鏈接</a></p>
<p>圖片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
# 指定圖片爲當前目錄
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定義圖片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
try:
smtpObj = smtplib.SMTP('smtp.exmail.qq.com',25)
smtpObj.login(sender, "12345678",)
# smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.sendmail(sender, receivers, msgRoot.as_string())
print("郵件發送成功")
except smtplib.SMTPException:
print("Error: 無法發送郵件")