# -*- coding:utf-8 -*- import smtplib,os,sys,string import mimetypes from email import Encoders from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage import time import datetime mail_host="smtp.126.com" mail_user="用户名" mail_pass="授权码,不是网页登录密码" mail_postfix="126.com" to_list="a@126.com;b@126.com;" today=datetime.date.today() oneday=datetime.timedelta(days=1) yesterday=today-oneday sub="[数据中心]" + yesterday.strftime('%Y-%m-%d') + "新增账号数据" content="每日注册用户。请查阅附件。" attachment_list="m.txt" ###################### def send_mail(): me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msgRoot = MIMEMultipart() msg = MIMEText(content,'html',_charset='utf8') msgRoot['Subject'] = sub msgRoot['From'] = me msgRoot['To'] = to_list inputfilename_list=attachment_list.split(',') try: msgRoot.attach(msg) #for inputfilename in mailattachlist: for inputfilename in inputfilename_list: if inputfilename: basename=os.path.basename(inputfilename) att = MIMEText(open(inputfilename, 'rb').read(), 'base64', 'utf8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="'+basename+'"' msgRoot.attach(att) s = smtplib.SMTP() #s.set_debuglevel(1) s.connect(mail_host) s.login(mail_user,mail_pass) #s.ehlo() #s.starttls() s.sendmail(me, string.splitfields(to_list,";"), msgRoot.as_string()) s.close() return True except Exception, e: print str(e) print inputfilename return False if send_mail(): print 'ok' else: print 'false'