python发送带附件的邮件

# coding=utf8
import os, smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header


class SendMail():

    reportpath = os.path.join(os.getcwd(), 'report')
    def getreport(self):
        dirs = os.listdir(self.reportpath)

        dirs.sort(key=lambda fn:os.path.getmtime(self.reportpath+'//'+fn))

        report = os.path.join(self.reportpath,dirs[-1])
        print report
        return report

    def sendmail(self,report):
        # 定义服务器类型,登录名密码,发送人和接受人,发送邮件主题
        smtpserver = 'smtp.qq.com'

        user = '[email protected]'
        passwd = 'odvfqndlamxobfhh'

        sender = '[email protected]'
        receiver = ['[email protected]','[email protected]','[email protected]']

        header = 'Happy New Year!!!!!  from fyf'

        content = '这是测试用的哦'

        #构造附件内容
        f = open(report,'rb')
        sendfile = f.read()
        f.close()

        att = MIMEText(sendfile,'base64','utf-8')
        att["Content-Type"] = 'application/octet-stream'
        #外面用单引号,里面文件名用双引号
        att["Content-Disposition"] = 'attachment;filename="1.txt"'

        msgRoot = MIMEMultipart()
        msgRoot.attach(MIMEText(content,'html','utf-8'))
        msgRoot['From'] = sender
        msgRoot['To'] = ','.join(receiver)
        msgRoot['Subject'] = Header(header,'utf-8')
        msgRoot.attach(att)

        # 发送邮件,端口用465, keyfile = 'vxkdfejinpifbeaj'
        smtp = smtplib.SMTP_SSL(smtpserver, 465)

        smtp.helo(smtpserver)  # 向服务器标识用户身份
        smtp.ehlo(smtpserver)  # 服务器返回结果确认

        # 直接登录,之前是登录前写了smtp.connect()
        smtp.login(user, passwd)
        smtp.sendmail(sender, receiver, msgRoot.as_string())

        smtp.quit()


if __name__ == "__main__":
    mail = SendMail()
    report = mail.getreport()
    mail.sendmail(report)




猜你喜欢

转载自blog.csdn.net/qq_35958094/article/details/78953322