python之發送郵件~
阿新 • • 發佈:2018-07-08
color font 函數 pos 個人 dont sendmail log 其他
在之前的工作中,測試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‘,‘yangych@824029‘)
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‘,‘yangych@824029‘)
sendmail.sendmail(sender,receives,msg.as_string())
sendmail.quit()
這裏把主題、正文和附件文件作為參數代入,函數中的其他變量也可以作為參數輸入,個人覺得沒什麽必要,但可以把其他的一些變量放到文件來讀取,這樣方便管理
python之發送郵件~