美文网首页
发送邮件工具类封装

发送邮件工具类封装

作者: Chaweys | 来源:发表于2021-01-26 08:25 被阅读0次

#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header

class SendMail:
    def __init__(self,mail_server):
        self.mail_server=mail_server             #发送邮件服务器(域名)

    def send(self,content,sender,auth_code,receivers,title):
        message=MIMEText(content,"html","utf-8")              #定义发送内容为html格式编码为utf-8
        message["From"]="{}".format(sender)                   #定义发送者
        message["To"]=",".join(receivers)                     #接受者有可能多个,所以定义成一个列表参数,这里就用逗号拼接起来
        message["Subject"]=title                              #定义发送title
        try:
            smtp_obj=smtplib.SMTP_SSL(self.mail_server,465)   #开启SSL协议,端口固定465
            smtp_obj.helo(self.mail_server)
            smtp_obj.ehlo(self.mail_server)
            smtp_obj.login(sender,auth_code)                  #登录邮箱服务器
            smtp_obj.sendmail(sender,receivers,message.as_string())  #开始发送邮件
            print("发送邮件成功")

        except Exception as e:
            print("发送邮件失败:{0}".format(e))

if __name__ == '__main__':
    sendmail=SendMail("smtp.163.com")

    content="""
    小滴课堂xdclass.net
    <a href="xdclass.net">课堂首页</a>
    """
    sender="hu_dechao@163.com"
    auth_code="hdc328216"
    reveivers=["471260459@qq.com"]
    title="小滴课堂"

    sendmail.send(content,sender,auth_code,reveivers,title)

【注】:
发送邮件报错如下,表示在smtp.login()之前需要向服务器标识用户身份,
File "G:\Python38\lib\smtplib.py", line 607, in ehlo_or_helo_if_needed
    raise SMTPHeloError(code, resp)
smtplib.SMTPHeloError: (500, b'Error: bad syntax')
解决方法,在smtp.login()之前加上如下:
smtp.helo(mail_server)
smtp.ehlo(mail_server)

测试报告.png

相关文章

网友评论

      本文标题:发送邮件工具类封装

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