Python send text/image/attachment email

"""
Python发文本/图片/附件邮件
"""
import smtplib
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class Email(object):
    """
    邮件类,提供功能:发邮件
    """

    def __init__(self, mail_user, mail_pass):
        self.mail_host = "smtp.qq.com"  # 邮件服务器域名
        self.mail_port = 465  # 邮件服务器端口
        self.mail_user = mail_user  # 用户名
        self.mail_pass = mail_pass  # 口令
        self.sender = self.mail_user  # 发件人
        self.smtpObj = smtplib.SMTP_SSL(self.mail_host, self.mail_port)
        self.smtpObj.login(self.mail_user, self.mail_pass)

    def send_email(self, subject, content, receivers):
        """
        发送文本邮件
        :param subject:邮件主题(标题)
        :param content: 邮件内容
        :param receivers: 收件人列表
        :return:
        """
        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')
        message['From'] = Header(self.sender, 'utf-8')
        message['To'] = Header(';'.join(receivers), 'utf-8')
        try:
            self.smtpObj.sendmail(self.sender, receivers, message.as_string())
            print('邮件发送成功')
            self.smtpObj.quit()
        except smtplib.SMTPException as e:
            raise Exception('邮件发送失败,异常信息:%s' % e)

    def send_email_img(self, subject, content, receivers, img_path):
        """
        发送带图片/附件邮件
        :param subject: 邮件主题(标题)
        :param content: 邮件文本内容
        :param receivers: 收件人列表
        :param img_path: 图片路径
        :return:
        """
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = Header(self.sender, 'utf-8')
        msg['To'] = Header(';'.join(receivers), 'utf-8')

        # 以html格式构建邮件内容
        content_str = '<html><body>'
        content_str += f'<p>{content}</p><br>'
        content_str += '<img src="cid:image1" alt="image1" align="center" width=100%/>'
        content_str += '</body></html>'
        # 添加邮件内容
        content_str = MIMEText(content_str, _subtype='html', _charset='utf8')
        msg.attach(content_str)
        # 构建并添加图像对象
        image1 = MIMEImage(open(img_path, 'rb').read(), _subtype='octet-stream')
        image1.add_header('Content-ID', 'image1')
        msg.attach(image1)
        # 构建并添加附件对象
        img = MIMEImage(open(img_path, 'rb').read(), _subtype='octet-stream')
        img.add_header('Content-Disposition', 'attachment', filename=img_path)
        msg.attach(img)

        try:
            self.smtpObj.sendmail(self.sender, receivers, msg.as_string())
            print('邮件发送成功')
            self.smtpObj.quit()
        except smtplib.SMTPException as e:
            raise Exception('邮件发送失败,异常信息:%s' % e)


if __name__ == '__main__':
    email = Email("[email protected]", "")
    # 发送文本邮件
    # subject = '我是subject'
    # content = '我是content'
    # receivers = ['[email protected]', '[email protected]']
    # email.send_email(subject, content, receivers)

    # 发送带图片/附件邮件
    subject = '51job每周职位数量统计'
    receivers = ['[email protected]']
    email.send_email_img(subject, '我是文本内容', receivers, '51job.png')

 

Guess you like

Origin blog.csdn.net/zhu6201976/article/details/103941725