python send email with attachment

# 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):
         # Define server type, login name and password, sender and receiver, subject of sending mail
         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 = 'This is for testing'
 #construct attachment content
 f = open (report, 'rb' )
        
                
        sendfile = f.read()
        f.close()

        att = MIMEText (sendfile, 'base64' , 'utf-8' )
        att[ "Content-Type" ] = 'application/octet-stream'
 #Single quotes outside, double quotes inside the file name
 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)

        # Send mail, use port 465, keyfile = 'vxkdfejinpifbeaj'
         smtp = smtplib.SMTP_SSL(smtpserver, 465 )

        smtp.helo(smtpserver)   # Identifies the user identity to the server
         smtp.ehlo(smtpserver)   # The server returns the result confirmation
         # Direct login, I wrote smtp.connect() before login
 smtp.login(user, passwd)
        
        smtp.sendmail(sender, receiver, msgRoot.as_string())

        smtp.quit()


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




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325841961&siteId=291194637