发送email给列表中的邮箱--python
#!/usr/bin/python# -*- coding: utf-8 -*- #from email.Header import Headerfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartimport smtplib, datetimeimport os,sysimport datetimeimport timeemail_code='utf-8'email_header='本周周报'server_port='25'main_msg=''list_file='send_list.dat'#当前日期#print datetime.date.today()#求指定日期前的datebegin_date=datetime.date.today()-datetime.timedelta(days=7)#格式化日期#print begin_date.strftime("%Y%m%d")#print time.strftime("%Y%m%d",time.localtime())file_path='/home/nantian/tmp/工作情况汇报_%s-%s.docx' %(begin_date.strftime("%Y%m%d"),\ time.strftime("%Y%m%d",time.localtime()))try: send_addr=sys.argv[1] send_passwd=sys.argv[2] server_addr='smtp.%s' % send_addr.split('@')[1]except IndexError,e: print "Usage:%s address password!" % sys.argv[0] quit()def send_email(rcv_text,rcv_addr,send_file): msg = MIMEMultipart() txt = MIMEText(rcv_text,'utf-8') msg.attach(txt) try: att = MIMEText(open(file_path, 'rb').read(), 'base64', email_code) msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]='ISO-8859-1,"%s"' % email_code att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment;filename="%s"' % os.path.basename(file_path) msg.attach(att) except IOError,e: pass msg['to'] = rcv_addr msg['from'] = send_addr msg['subject'] = Header(email_header,email_code) server.sendmail(msg['from'], msg['to'],msg.as_string())server = smtplib.SMTP()server.connect(server_addr,server_port)try: server.login(send_addr, send_passwd) list_line=open(list_file,'rb')except smtplib.SMTPAuthenticationError,e: print "Error:Username or password error!" quit()except IOError: print "Eorro:Open file [%s] error!" % list_file quit()if not os.path.exists(file_path) : email_header='本周周报没有写!,或者文档名称不正确!' send_email("本周周报没写!","admin@qq.com","") quit()for eachline in list_line: addr=eachline.split("|")[0] main_msg=eachline.split("|")[1] if addr[0] == '#': continue send_email(main_msg,addr,file_path)server.close
因为工作中需要发送工作报告给领导,说不定那天玩游戏就忘记了。这样写一个工具加到crontab中,提醒自己。
之需要将文档放在指定目录下,脚本就会email。
ps:需要维护一个邮件列表。可以适当修改,将自己的用户密码加密保存。