python之发送邮件~

在之前的工作中,测试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 = 'xxx@126.com'
receives = 'xxx@qq.com'
cc_receiver = 'xxx@qq.com'
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(xxx,xxx')
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 = 'xxx@126.com'
    receives = 'xxx@qq.com'
    cc_receiver = 'xxx@qq.com'
    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('xxx',xxx')
    sendmail.sendmail(sender,receives,msg.as_string())
    sendmail.quit()

这里把主题、正文和附件文件作为参数代入,函数中的其他变量也可以作为参数输入,个人觉得没什么必要,但可以把其他的一些变量放到文件来读取,这样方便管理

关于本篇内容如有转载请注明出处;技术内容的探讨、纠错,请发邮件到70907583@qq.com
原文地址:https://www.cnblogs.com/watertaro/p/9278906.html