1. 程式人生 > >實現自動發郵件功能

實現自動發郵件功能

.text 函數 stp con tps desc htm -s lambda

在實際的項目中,當腳本執行完畢,生成測試報告,我們需要把報告通過郵件發送到對應的測試人員和開發人員,下面學習下在Python中如何實現郵件發送功能,在Python中提供了smtplib模塊來發送郵件,導入smtplib,通過help函數可以查看smtp提供的方法。

在學習發郵件的過程中,只需要掌握兩個模塊的用法即可,smtplib和email,smtplib模塊負責發送郵件(連接郵箱服務器,登錄郵箱,發送郵件),email負責構造郵件(發件人,收件人,主題,正文,附件等)。

smtplib模塊:

 1 connect(host,port):
 2 host:指定連接的郵箱服務器
3 port:指定連接服務器的端口號,默認為25 4 login(user,password): 5 usr:指定郵箱用戶名 6 password:指定郵箱登錄密碼 7 sendmail(from_addr, to_addrs, msg): 8 from_addr:指定郵件發送者地址 9 to_addrs:指定郵箱接受者地址 10 msg:發送消息:郵件內容,一般是msg.as_string()將msg(MIMEText對象或者MIMEMultipart對象)變為str。 11 quit():
用來結束SMTP回話。

email模塊:

email模塊下有mime包,該包下常用的三個模塊是:text,image,multipart。

構造一個MIMEText對象,就表示一個文本郵件對象,構造一個MIMEImage對象,就表示一個作為附件的圖片,如果要把多個對象組合到一起,則需要使用MIMEMultipart對象。

發送普通的文本:text_plain=MIMEText(text,"plain","utf-8")

發送HTML格式的文本:text_html=MIMEText(text,"html","utf-8")

在進行發送郵件時,我們需要把subject,from,to等添加到MIMEText或者MIMEMultipart對象中,因為只有這樣,郵件才會顯示主題,發件人,收件人等。

    msg = MIMEMultipart()
    msg[
"subject"] = "這是發送郵件的主題" msg["from"] = sender msg["to"] = recever

說明:如果只有一個html網頁或者plain普通文本的話,msg可以是MIMEText,但是如果是多個的話(附件,文本,圖片等),則msg類型要為MIMEMultipart。

1.發送HTML格式的郵件

# -*-coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText

# ------1、設置發送郵件相關的參數------
smtpserver ="smtp.126.com"  # 發送郵件服務器
sender ="xxxxxx"  # 發送郵件的賬號
pwd = "xxxxxx"  # 發送郵件賬號的密碼
receiver = "xxxxxx"  # 接收郵件的賬號
# ------2、編輯郵件的內容-----
subject = "發送郵件的主題"  # 發送郵件的主題
body = "這是發送的郵件的內容"  # 發送郵件的內容,郵件的正文為html格式
msg = MIMEText(body, "html", "utf-8")  # 發送純文本格式的郵件
msg["Subject"] = subject
msg[from] = "xxxxxx"
msg[to] = "xxxxxx"
# ------3、發送郵件------
smtp = smtplib.SMTP()
smtp.connect(smtpserver)  # 連接郵件服務器
smtp.login(sender, pwd)  # 登錄郵件服務器

smtp.sendmail(sender, receiver, msg.as_string())  # 發送郵件
smtp.quit()  # 關閉連接

2.發送帶附件的郵件

上面的MIMEText只能發送正文格式的郵件,無法發送附件,如果想要發送帶附件的郵件,需要另外一個類MIMEMultipart。

# -*-coding:utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# ------1、設置發送郵件相關的參數------
smtpserver ="smtp.126.com"  # 發送郵件服務器
sender ="xxxxxx"  # 發送郵件的賬號
pwd = "xxxxxx"  # 發送郵件賬號的密碼
receiver = "xxxxxx"  # 接收郵件的賬號
# ------2、編輯郵件的內容-----
# 讀文件
file_path = "./testpro/testresult/2019-03-10 09-35-54result.html"
with open(file_path, "rb") as fp:
    mail_body = fp.read()

msg = MIMEMultipart()
msg[from] = sender
msg[to] = receiver
msg["subject"] = "這是發送郵件的主題"

# 正文
body = MIMEText(mail_body, "html", "utf-8")
msg.attach(body)
# 附件
attach = MIMEText(mail_body, "base64", "utf-8")
attach["Content-Type"] = "application/octet-stream"
attach["Content-Disposition"] = attachment; filename="testReport.html"
msg.attach(attach)
# ------3、發送郵件------
smtp = smtplib.SMTP()
smtp.connect(smtpserver)  # 連接郵件服務器
smtp.login(sender, pwd)  # 登錄郵件服務器

smtp.sendmail(sender, receiver, msg.as_string())  # 發送郵件
smtp.quit()  # 關閉連接

3.郵件發送最新的測試報告

# -*-coding:utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
from email.header import Header

# ------1、設置發送郵件相關的參數------
smtpserver ="smtp.126.com"  # 發送郵件服務器
sender ="xxxxxx"  # 發送郵件的賬號
pwd = "xxxxxx"  # 發送郵件賬號的密碼
receiver = "xxxxxx"  # 接收郵件的賬號
# ------2、編輯郵件的內容-----
result_dir = "./testpro/testresult/"
file_list = os.listdir(result_dir)
file_list.sort(key=lambda fn: os.path.getmtime(result_dir + "/" + fn))
file = os.path.join(result_dir+file_list[-1])
# 讀文件
with open(file, "rb") as fp:
    mail_body = fp.read()

msg = MIMEMultipart()
msg["subject"] = "這是發送郵件的主題"
msg["from"] = sender
msg["to"] =  receiver

# 正文
body = MIMEText(mail_body, "html", "utf-8")
msg.attach(body)
# 附件
attach = MIMEText(mail_body, "base64", "utf-8")
attach["Content-Type"] = "application/octet-stream"
attach["Content-Disposition"] = attachment; filename="testReport.html"
msg.attach(attach)
# ------3、發送郵件------
smtp = smtplib.SMTP()
smtp.connect(smtpserver)  # 連接郵件服務器
smtp.login(sender, pwd)  # 登錄郵件服務器

smtp.sendmail(sender, receiver, msg.as_string())  # 發送郵件
smtp.quit()  # 關閉連接

4.整合自動發送郵件功能

下面根據上節的測試百度搜索和搜狗搜索的案例整合自動發送郵件功能。

# coding:utf-8
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

def send_mail(report):
    # 設置發送郵件需要的參數
    smtp_server = "smtp.126.com"
    sender = "xxxxxx"
    pwd = "xxxxxx"
    recever = "xxxxxx"
    # 設置發送郵件的內容
    # 讀文件
    with open(report, "rb") as fp:
        mail_body = fp.read()

    msg = MIMEMultipart()
    msg["subject"] = "這是發送郵件的主題"
    msg["from"] = sender
    msg["to"] = recever
    # 內容
    body = MIMEText(mail_body,"html","utf-8")
    msg.attach(body)
    # 附件
    attach = MIMEText(mail_body, "base64", "utf-8")
    attach["Content-Type"] = "application/octet-stream"
    attach["Content-Disposition"] = attachment; filename="testReport.html"
    msg.attach(attach)
    # 發送郵件
    smtp = SMTP()
    smtp.connect(smtp_server)
    smtp.login(sender, pwd)
    smtp.sendmail(sender, recever, msg.as_string())
    smtp.quit()


def find_report(file_path):
    list_file = os.listdir(file_path)  # 列出該目錄下的所有文件
    list_file.sort(key=lambda fn: os.path.getmtime(file_path + "/" + fn))
    report = os.path.join(file_path + list_file[-1])
    return report


if __name__ == __main__:
    discover = unittest.defaultTestLoader.discover("./testpro/testcase/", "test*.py")
    now_time = time.strftime("%Y-%m-%d %H-%M-%S")
    file_name = "./testpro/testresult/"+now_time+"result.html"
    file = open(file_name, "wb")
    runner = HTMLTestRunner(stream=file, title="測試報告", description="測試用例執行情況")
    runner.run(discover)
    file.close()
    new_report = find_report("./testpro/testresult/")
    send_mail(new_report)
    print("The end!")

實現自動發郵件功能