python之发送邮件~
Posted 水里的芋头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = ‘[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之发送邮件~的主要内容,如果未能解决你的问题,请参考以下文章