python 发邮件 带附件

皇甫福
2023-12-01

环境

  • python==3.7

代码

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


class Email:
    def __init__(self):
        self.sender = EMAIL["SENDER_ACCOUNT"]
        self.password = EMAIL["PASSWORD"]
        self.port = EMAIL["PORT"]
        self.host = EMAIL["HOST"]
        self.receivers = EMAIL["RECEIVER"]
        self.charset = "utf-8"
    
    @staticmethod
    def to_bytes_io(df: pd.DataFrame):
        bytes_io = BytesIO()
        df.to_excel(bytes_io, index=False)
        bytes_io.seek(0, 0)
        return bytes_io.read()
    
    def _create_msg(self, subject, content, attachments):
        # 创建一个带附件的实例
        message = MIMEMultipart()
        # sender_obj = email.utils.formataddr(("syh", self.sender))

        message['From'] = self.sender
        message['To'] = ",".join(self.receivers)
        message['Subject'] = Header(subject, self.charset)

        # 邮件正文内容
        message.attach(MIMEText(content, 'plain', self.charset))

        for idx, x in enumerate(attachments):
            att = MIMEApplication(x)
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = f'attachment; filename="{idx}.xlsx"'
            message.attach(att)
        return message

    def send(self, subject, content, attachment_excels):
        msg = self._create_msg(subject, content, attachment_excels)
        smtp = smtplib.SMTP(self.host, port=self.port)
        smtp.login(self.sender, self.password)
        print("登录成功")
        smtp.sendmail(self.sender, self.receivers, msg.as_string())
        print("11")
        smtp.quit()

备注

本次使用的是qq邮箱进行测试,使用前需打开邮箱的SMTP服务,密码使用授权码,非密码。发送的附件可以是文件,也可以是bytes_io,如代码中的to_bytes_io。

 类似资料: