邮箱发送通用功能

给各位小伙伴们分享一下发送邮件的功能 :

1.需要用到这些包,么有的话用pip安装一下~

附上pip安装链接https://jingyan.baidu.com/article/7e4409533f32092fc0e2ef24.html

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart

2.定义一个发送邮件的类,自己可以命名,这里叫sendEmail

class SendEmail:

3.下面可以来写一些具体的方法啦

格式为:def+命名:

     #初始化
 def __init__(self,host_dir,email_port,username,passwd):
        self.host_dir=host_dir
        self.email_port=email_port
        self.username=username
        self.passwd=passwd

发送邮件需要几个参数,本机地址,email端口号 ,登录邮箱账号还有密码,所以我们初始化这几个参数,可以在后面的方法中都用到,比较方便。

    #连接邮件服务器
    def __connect(self):
        try:
            self.e = smtplib.SMTP()
            self.e.connect(self.host_dir, port=self.email_port)
            print("邮件服务器连接成功")
        except:
            print ("邮件服务器连接失败")

    #登录邮箱
    def __login(self):
        try:
            self.e.login(self.username, self.passwd)
            print("邮箱登录成功")
        except:
            print ("邮箱登录失败")
    #添加附件
    def __addannex(self,logs):
        for log in logs.keys():
            try:
                textpart = MIMEApplication(open(logs[log], 'rb').read())
                textpart.add_header('Content-Disposition', 'attachment', filename=log+".text")
                self.message.attach(textpart)
            except:
                print (log+" not exist")
    #添加内容
    def add_message(self,html,logs):
        #添加html
        with open(html,'rb') as fp:
            msg_text=fp.read()
            fp.close()
        msg = MIMEText(msg_text, 'html', 'utf-8')
        self.message = MIMEMultipart()
        self.message.attach(msg)

        #添加附件日志
        self.__addannex(logs)


    #添加头部信息
    def add_header(self,headerfrom,headerto,subject):
        self.message['from'] = Header(headerfrom, 'utf-8')
        self.message['to'] = Header(headerto, 'utf-8')
        self.message['Subject'] = Header(subject, 'utf-8')

    #发送邮件
    def send(self,sender,receivers):
        try:
            self.e.sendmail(sender, receivers, self.message.as_string())
            print("邮件发送完成")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")
        finally:
            self.e.quit()

到这里就结束了,大家实际操作看看吧~~

你可能感兴趣的:(自动化测试经验,python)