代码内容如下:

# -*- coding: utf-8 -*-
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import os
import smtplib


class myEmail():
    def __init__(self, config: dict):
        self.from_addr = config['from_addr']
        self.to_addr = config['to_addr']
        self.cc_addr = config['cc_addr']
        self.mailhost = config['mailhost']
        self.password = config['password']
        self.msg_subject = config['msg_subject']
        self.msg_text = config['msg_text']
        self.file_path = config['file_path']
        self.is_smtp_ssl = config['is_smtp_ssl']
        self.smtp_port = config['smtp_port']
        self.msg_text_type = 'html'

        if len(self.to_addr) <= 0:
            return

    def send_email(self):
        msg = MIMEMultipart()
        msg['From'] = self._format_addr(self.from_addr)
        msg['To'] = self._format_addr(self.to_addr)
        if self.cc_addr is not None:
            msg['Cc'] = self._format_addr(self.cc_addr)

        msg['Subject'] = Header(self.msg_subject, 'utf-8').encode()
        msg.attach(MIMEText(self.msg_text, self.msg_text_type, 'utf-8'))

        if self.file_path is not None and len(self.file_path) > 0:
            msg = self.files(msg, self.file_path)

        smtp_server = self.mailhost
        if self.is_smtp_ssl:
            # 使用 smtp 协议以及 ssl 加密方式【推荐使用此方法】
            port = int(self.smtp_port)
            server = smtplib.SMTP_SSL(smtp_server, int(port), timeout=10.0)
        else:
            port = int(self.smtp_port)
            server = smtplib.SMTP(smtp_server, port, timeout=10.0)

        server.set_debuglevel(0)  # 设置 debug 级别 1:打印 0: 不打印
        server.connect(smtp_server)  # 连接服务器
        server.login(self.get_val(self.from_addr)[0], self.password)  # 登录发件人账号
        if self.cc_addr is not None:
            server.sendmail(
                self.get_val(self.from_addr)[0],
                self.get_val(self.to_addr) + self.get_val(self.cc_addr),
                msg.as_string()
            )
        else:
            server.sendmail(
                self.get_val(self.from_addr)[0],
                self.get_val(self.to_addr),
                msg.as_string()
            )
        server.quit()

    def get_val(self, dic):
        val = list(dic.values())
        return val

    def _format_addr(self, dic):
        addr_list = []
        for name, addr in dic.items():
            addr_list.append(formataddr((Header(name, 'utf-8').encode(), addr)))
        return ','.join(addr_list)

    def files(self, msg, file_path):
        for source_file, file_name in file_path.items():
            if not os.path.exists(source_file):
                print(source_file, '不存在!')
                continue

            with open(source_file, 'rb') as f:
                mime = MIMEBase('application', 'octet-stream')
                # file_name 转 gbk, 否则附件带有中文名会有乱码
                mime.add_header(
                    'Content-Disposition',
                    'attachment',
                    filename=('utf-8', '', file_name)
                )
                mime.add_header('Content-ID', '<0>')
                mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(f.read())  # 把附件的内容读进 mime
                encoders.encode_base64(mime)  # 用Base64编码
                msg.attach(mime)  # 添加到 MIMEMultipart 中

        return msg


if __name__ == "__main__":

    config = {
        'from_addr': {
            'Zabbix监控': 'xxx@xxx.com'
        },
        'to_addr': {
            'xxx': 'xxx@xxx.com',
        },
        'cc_addr': {
            'xxx': 'xxx@xxx.com',
        },
        'mailhost': 'xxx.com',
        'password': 'xxx@xxx.com',
        'msg_subject': '邮件标题',
        'msg_text': '邮件正文内容',
        'file_path': {
            # '文件路径': '文件名'
        },
        'is_smtp_ssl': False,
        'smtp_port': 25,
    }

    my_email = myEmail(config=config)
    my_email.send_email()

本博客所有内容采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可

转载文章请注明:python发送邮件(txt,html,附件) - https://yangxx.net/?p=4222

分类: python

young

记住该记住的,忘记该忘记的,改变能改变的,接受不能改变的!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

我不是机器人*