美文网首页
用python发邮件

用python发邮件

作者: 极寒本寒 | 来源:发表于2018-02-08 09:36 被阅读0次
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os


class SendMail:

    def __init__(self, path, sender, receiver):
        self.sender_act = sender['sender']
        self.password = sender['password']
        self.receiver = receiver
        self.path = path
        try:
            self.file_list = os.listdir(self.path)
        except Exception as e:
            self.file_list =[self.path]
        self.smtp_server = smtplib.SMTP_SSL('smtp.qq.com')

    def create_email(self):
        self.msg = MIMEMultipart('alternative')
        self.msg['Subject'] = "每日报表"
        self.msg['From'] = self.sender_act
        self.msg['To'] = ','.join(self.receiver)
        for file in self.file_list:
            self.msg.attach(self.add_attachment(file))
        self.msg.attach(self.add_content())
        return self.msg

    def add_attachment(self, file):
        att_file = MIMEText(
            open(self.path + '/' + file, 'rb').read(),
            'base64', 'gbk')
        att_file["Content-Type"] = 'application/octet-stream'
        att_file.add_header(
            'Content-Disposition',
            'attachment', filename=('gbk', '', file))
        return att_file

    def add_content(self):
        html = '<html><body><p>您好,这是昨日报表,请您查阅。</p></body></html>'
        att_text = MIMEText(html, 'html')
        return att_text

    def send_email(self):
        msg = self.create_email()
        with self.smtp_server as conn:
            conn.login(self.sender_act, self.password)
            conn.sendmail(self.sender_act, self.receiver, msg.as_string())
            print('邮件发送成功')

相关文章

网友评论

      本文标题:用python发邮件

      本文链接:https://www.haomeiwen.com/subject/fbizzxtx.html