Python实现邮件发送

2019-09-25  本文已影响0人  Virtualer

发送邮件其实很简单,主要用了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())

上一篇下一篇

猜你喜欢

热点阅读