邮件内容支持附件、图片、文字

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2020/5/13 6:05 下午
# @Author   : 陈日志
# @Email    : [email protected]
# @File     : Mail.py
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header


class Mail(object):
    def __init__(self, smtp_server, smtp_port=25, ssl=False):
        self._message = MIMEMultipart()
        if ssl:
            self.smtp = smtplib.SMTP_SSL(smtp_server, 465 if smtp_port == 25 else smtp_port)
        else:
            self.smtp = smtplib.SMTP(smtp_server, smtp_port)
        self._receivers = None
        self._sender = None
        self._content = ''
        self._imageid = 0

    def login(self, user, password):
        try:
            self.smtp.login(user, password)
        except Exception as e:
            print(e)
            raise smtplib.SMTPAuthenticationError(1, "login failed")
        self._message["From"] = user
        self._sender = user

    @property
    def receives(self):
        return self._receivers

    @property
    def receives(self):
        return self._receivers

    @receives.setter
    def receives(self, receivers):
        type_ = type(receivers)
        if type_ is str:
            receivers = receivers.split(',')
            self._message["To"] = receivers
            self._receivers = receivers
        elif type_ is list or type_ is tuple:
            self._message["To"] = ','.join(receivers)
            self._receivers = receivers

    @property
    def title(self):
        return self._message.get("Subject")

    @title.setter
    def title(self, title):
        self._message["Subject"] = Header(title, 'utf-8')

    @property
    def content(self):
        return self._message

    @content.setter
    def content(self, content):
        self._content = content

    @property
    def imageid(self):
        self._imageid += 1
        return self._imageid

    def append_content(self, content):
        self._content += content

    def add_attachment(self, file):
        att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        # att["Content-Disposition"] = 'attachment; filename=%s' % os.path.basename(file).encode('utf-8')
        att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', os.path.basename(file)))
        self._message.attach(att)

    def add_image(self, img):
        imageid = 'image%s' % self.imageid
        msg = MIMEImage(open(img, 'rb').read())
        msg.add_header('Content-ID', imageid)
        self._content += '<br/><img src="cid:%s">' % imageid
        self._message.attach(msg)

    def send(self):
        self._message.attach(MIMEText(self._content, 'html', 'utf-8'))
        try:
            self.smtp.sendmail(self._sender, self._receivers, self._message.as_string())
        except Exception as e:
            print(e)
            raise smtplib.SMTPConnectError(1, "Send mail error")

    def logout(self):
        self.smtp.quit()

使用实例

实例一:纯文本邮件

from Mail import Mail

mail = Mail('邮箱SMTP地址')
mail.login('发件人邮箱', '邮箱密码')
mail.title = "邮件标题"
mail.content = "邮件正文"
mail.receives = '收件人'
mail.send()
mail.logout()

实例二:给多人发邮件

from Mail import Mail

mail = Mail('邮箱SMTP地址')
mail.login('发件人邮箱', '邮箱密码')
mail.title = "邮件标题"
mail.content = "邮件正文"
mail.receives = ['收件人1', '收件人2']
mail.send()
mail.logout()

实例三:发带附件的邮件

from Mail import Mail

mail = Mail('邮箱SMTP地址')
mail.login('发件人邮箱', '邮箱密码')
mail.title = "邮件标题"
mail.content = "邮件正文"
mail.receives = ['收件人1', '收件人2']
mail.add_attachment('附件1路径')
mail.add_attachment('附件2路径')
mail.send()
mail.logout()

实例四:发图文邮件

from Mail import Mail

mail = Mail('邮箱SMTP地址')
mail.login('发件人邮箱', '邮箱密码')
mail.title = "邮件标题"
mail.content = "邮件正文"
mail.receives = ['收件人1', '收件人2']
mail.add_image('图片1路径')
# 后面还可以插入文本
mail.append_content('追加的文本内容')
# 还能插入图片
mail.add_image('图片2路径')
# 继续还能插入文本
mail.append_content('追加的文本内容2')
# 还可以带附件
mail.add_attachment('附件路径')
mail.send()
mail.logout()

邮件正文支持html的,如果需要格式,邮件内容写html代码即可。

标签: none

添加新评论