美文网首页
Python实现邮件发送

Python实现邮件发送

作者: Virtualer | 来源:发表于2019-09-25 13:58 被阅读0次

    发送邮件其实很简单,主要用了smtplib和email库。
    要注意的是这个varifycode其实是邮箱的授权码,QQ邮箱的授权码是在邮箱设置-账号里开启IMAP后提供给你的一个固定字符串有点像uuid,163邮箱类似,不同的点在于163邮箱的授权码可以自己设定。
    这份实现是我将发送邮件功能封装了个类,通过传入发送邮件的账户、账户名、授权码、接收邮件的用户名、主机地址、端口、主题和发送的内容,实现发送。可以调用result()函数获取发送结果,判断是否发送成功,失败的话错误是什么。

    #/usr/bin/python
    # -*- coding:utf-8 -*-
    
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    class SendMail:
        errCode = ""
    
        def __init__(self, accout, name, varifycode, reciever, host, port, maintitle, sendmessage):
            self.accout = accout;
            self.varifycode = varifycode;
            self.reciever = reciever;
            self.host = host;
            self.port = port;
            self.maintitle = maintitle;
            self.build(sendmessage, name, maintitle)
    
        def build(self, message, name, maintitle):
            message = MIMEText(message, 'plain', 'utf-8')
            message['From'] = Header(name + "<" + self.accout + ">", 'utf-8')
            message['To'] = Header("<" + self.reciever + ">", 'utf-8')
            subject = maintitle
            message['Subject'] = Header(subject, 'utf-8')
            self.sendmessage = message;
    
        def send(self):
            try:
                smtpObj = smtplib.SMTP_SSL(self.host, self.port)
                smtpObj.login(self.accout, self.varifycode)
                smtpObj.sendmail(self.accout, self.reciever, self.sendmessage.as_string())
                self.errCode = "send succeed"
            except smtplib.SMTPException as e:
                self.errCode.format("send err : %s"%e)
    
        def result(self):
            return self.errCode
    
    if __name__ == "__main__":
        send1 = SendMail("sender@qq.com", "sendname", "varifycode", "reciever@qq.com", "smtp.qq.com", 465, "maintitle", "send words")
        send1.send()
        print(send1.result())
    
    

    相关文章

      网友评论

          本文标题:Python实现邮件发送

          本文链接:https://www.haomeiwen.com/subject/zwcaectx.html