发送邮件——stamplib

本文介绍了一种使用Python3.x进行自动化邮件发送的方法,通过读取配置文件email.ini获取发件人、密码及收件人信息,利用smtplib库实现邮件发送功能。文章详细展示了如何构造MIME类型的邮件内容,并以html附件形式发送测试报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文email.ini件信息:

[email]
sender=xxxxxxxxxxx
pwd=xxxxxxxxxxxx
reciver=xxxxxxxxxxxxx
python 3.x代码如下:

import os,configparser,time,requests,hashlib,json
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def filePath(path):
return os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))),path)

def getEmailData():
#获取配置文件email信息
cf=configparser.ConfigParser()
ConfigPath=filePath('config\\email.ini')
cf.read(ConfigPath)
form_addr=cf.get('email','sender')
pwd=cf.get('email','pwd')
to_addr=cf.get('email','reciver')
return form_addr,pwd,to_addr
def sendEmail(report_path,report_name):
    #发送邮件
  '''
  report_path:发送的文件路径
  report_name:发送的文件命名
'''
from_add,pwd,to_user=getEmailData()
fp=open(report_path,'rb')
mail_body=fp.read()
fp.close()
msg=MIMEMultipart()
smtp_server='smtp.exmail.qq.com'
msg['From']=Header(from_add)
msg['To']=Header(to_user)
msg['Subject']=Header(u'私家云接口测试报告','utf-8')
msg['date']=time.strftime('%Y%m%d%H%M')
#发送内容
textpart=MIMEText(mail_body,_subtype='html',_charset='utf-8')
msg.attach(textpart)
#以html附件形式发送
htmlpart=MIMEApplication(open(reportPath(),'rb').read())
htmlpart.add_header('Content-Disposition','attachment',filename=report_name)
msg.attach(htmlpart)
#发送邮件
try:
s=smtplib.SMTP(smtp_server,25)
s.login(from_add,pwd)
s.sendmail(from_add,to_user.split(','),msg.as_string())
s.quit()
log.info(u'邮件发送成功!')
except smtplib.SMTPRecipientsRefused as err:
log.error(u'邮件发送失败!原因为:'+err)
except smtplib.SMTPAuthenticationError as err:
log.error(u'邮件发送失败!原因为:'+err)
except smtplib.SMTPException as err:
log.error(u'邮件发送失败!原因为:'+err)




转载于:https://www.cnblogs.com/langhuagungun/p/9028566.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值