python之發送郵件~

來源:互聯網
上載者:User

標籤:管理   span   odi   name   style   plain   報告   測試   模組   

 

在之前的工作中,測試web介面產生的報告是自動使用python中發送郵件模組實現,在全部自動化測試完成之後,把報告自動發送給相關人員

 

其實在python中很好實現,一個是smtplib和mail倆個模組來實現,主要如下:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import os

sender = ‘[email protected]‘
receives = ‘[email protected]‘
cc_receiver = ‘[email protected]‘
subject = ‘Python auto test‘

msg = MIMEMultipart()
msg[‘From‘] = sender
msg[‘To‘] = receives
msg[‘Cc‘] = cc_receiver
msg[‘Subject‘] = subject
msg.attach(MIMEText(‘Dont reply‘,‘plain‘,‘utf-8‘))

os.chdir(‘H:\\‘)
with open(‘auto_report03.html‘,‘r‘,encoding = ‘utf-8‘) as fp:
att = MIMEBase(‘html‘,‘html‘)
att.add_header(‘Content-Disposion‘,‘attachment‘,filename = ‘auto_report03.html‘)
att.set_payload(fp.read())
msg.attach(att)

sendmail = smtplib.SMTP()
sendmail.connect(‘smtp.126.com‘,25)
sendmail.login(‘lounq10000‘,‘[email protected]‘)
sendmail.sendmail(sender,receives,msg.as_string())
sendmail.quit()

 

在這裡我們可以把發送mail的代碼進行封裝成一個函數供外部調用,如下:


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import os

def sendMail(subject,textContent,sendFileName):
sender = ‘[email protected]‘
receives = ‘[email protected]‘
cc_receiver = ‘[email protected]‘
subject = subject

msg = MIMEMultipart()
msg[‘From‘] = sender
msg[‘To‘] = receives
msg[‘Cc‘] = cc_receiver
msg[‘Subject‘] = subject
msg.attach(MIMEText(textContent,‘plain‘,‘utf-8‘))

os.chdir(‘H:\\‘)
with open(sendFileName,‘r‘,encoding = ‘utf-8‘) as fp:
att = MIMEBase(‘html‘,‘html‘)
att.add_header(‘Content-Disposion‘,‘attachment‘,filename = sendFileName)
att.set_payload(fp.read())
msg.attach(att)

sendmail = smtplib.SMTP()
sendmail.connect(‘smtp.126.com‘,25)
sendmail.login(‘lounq10000‘,‘[email protected]‘)
sendmail.sendmail(sender,receives,msg.as_string())
sendmail.quit()

 

這裡把主題、本文和附件檔案作為參數代入,函數中的其他變數也可以作為參數輸入,個人覺得沒什麼必要,但可以把其他的一些變數放到檔案來讀取,這樣方便管理

 

python之發送郵件~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.