python封装发送邮件类
阅读原文时间:2023年07月08日阅读:3

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

class SendEMail(object):
"""封装发送邮件类"""

def \_\_init\_\_(self, host: str, port: int, user: str, pwd: str):  
    self.host = host  
    self.port = port  
    self.user = user  
    self.pwd = pwd

def \_\_send(self, msg):  
    try:  
        smtpObj = smtplib.SMTP()  
        smtpObj.connect(self.host, self.port)  
        smtpObj.login(self.user, self.pwd)  
        smtpObj.sendmail(self.user, msg\["To"\], msg.as\_string())  
        print("邮件发送成功")  
    except Exception as e:  
        print("邮件发送失败")

def send\_text(self, to\_user: str, content: str, subject: str):  
    """  
    发送文本邮件  
    :param to\_user: 对方邮箱  
    :param content: 邮件正文,文本格式  
    :param subject: 邮件主题  
    :return:  
    """

    # 使用email构造邮件  
    msg = MIMEText(content, \_subtype='plain', \_charset="utf8")  
    msg\["From"\] = self.user  
    msg\["To"\] = to\_user  
    msg\["subject"\] = subject

    self.\_\_send(msg)

def send\_html(self, to\_user: str, content: str, subject: str):  
    """  
    发送html格式邮件  
    :param to\_user: 对方邮箱  
    :param content: 邮件正文,html格式  
    :param subject: 邮件主题  
    :return:  
    """  
    # 使用email构造邮件  
    msg = MIMEText(content, \_subtype='html', \_charset="utf8")  
    msg\["From"\] = self.user  
    msg\["To"\] = to\_user  
    msg\["subject"\] = subject

    self.\_\_send(msg)

def send\_attachment(self, to\_user: str, content: str, subject: str, files: list):  
    """  
    发送附件邮件  
    :param to\_user: 对方邮箱  
    :param content: 邮件正文,文本格式  
    :param subject: 邮件主题  
    :return:  
    """  
    # 创建一个带附件的实例  
    msg = MIMEMultipart()  
    msg\['From'\] = self.user  
    msg\['To'\] = to\_user  
    msg\['subject'\] = subject  
    # 邮件正文内容  
    msg.attach(MIMEText(content, 'plain', 'utf-8'))  
    # 构造附件  
    for file in files:  
        att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')  
        att\["Content-Type"\] = 'application/octet-stream'  
        # 这里的filename可以任意写,写什么名字,邮件中显示什么名字  
        \_, file\_name = os.path.split(file)  
        att\["Content-Disposition"\] = 'attachment; filename="{}"'.format(file\_name)  
        msg.attach(att)  
    self.\_\_send(msg)

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器