Python发邮件带附件详解编程语言

import os 
import sys 
from smtplib import SMTP 
from email.MIMEMultipart import MIMEMultipart 
from email.mime.application import MIMEApplication 
import time 
 
def sendFildByMail(config): 
 
    print 'Preparing...',  
 
    message = MIMEMultipart( )  
    message['from'] = config['from']  
    message['to'] = config['to']  
    message['Reply-To'] = config['from']  
    message['Subject'] = config['subject']  
    message['Date'] = time.ctime(time.time())  
 
    message['X-Priority'] =  '3'  
    message['X-MSMail-Priority'] =  'Normal'  
    message['X-Mailer'] =  'Microsoft Outlook Express 6.00.2900.2180'  
    message['X-MimeOLE'] =  'Produced By Microsoft MimeOLE V6.00.2900.2180'  
 
    #注意这一段 
    f=open(config['file'], 'rb')  
    file = MIMEApplication(f.read()) 
    f.close() 
    file.add_header('Content-Disposition', 'attachment', filename= os.path.basename(config['file']))  
    message.attach(file)  
 
    print 'OK'  
    print 'Logging...',  
 
    smtp = SMTP(config['server'], config['port']) 
    smtp.ehlo() 
    smtp.starttls() 
    smtp.ehlo() 
    smtp.login(config['username'], config['password']) 
 
    print 'OK' 
    print 'Sending...', 
 
    smtp.sendmail (config['from'], [config['from'], config['to']], message.as_string()) 
 
    print 'OK' 
 
    smtp.close() 
 
    time.sleep(1) 
 
if __name__ == "__main__": 
    if len(sys.argv) < 2:  
        print 'Usage: python %s <file path>' % os.path.basename(sys.argv[0])  
        #sys.exit(-1)  
    else: 
        #587,  25 
        sendFildByMail({  
            'from': "[email protected]", 
            'to': [email protected]',  
            'subject': '[pysend]Send file %s' % sys.argv[1],  
            'file': sys.argv[1],  
            'server': 'smtp.xxx.com',  
            'port': 587, 
            'username': 'username',  
            'password': 'password'}) 
    wait=raw_input("end.")

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/8523.html

(0)
上一篇 2021年7月18日 19:45
下一篇 2021年7月18日 19:45

相关推荐

发表回复

登录后才能评论