<code>#! /usr/bin/env python #coding=gbk import sys, smtplib, os from datetime import date from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase import email.iterators import email.generator from email import Encoders ############# #读取邮件列表 file_object = open('list.txt') try: all_the_text = file_object.readlines( ) finally: file_object.close( ) #读取配置文件 mailto_list = all_the_text file_object = open('set.txt') try: all_the_text = file_object.readlines( ) finally: file_object.close( ) set_list = all_the_text #########格式化配置文件############# def get_mail_fomat(index): return_str = set_list[index] return_str = return_str.replace("\n","") return_str = return_str.split('=')[1] return return_str ##########发送邮件############ def send_mail(to_list,sub,content): ''' to_list:发给谁 sub:主题 content:内容 send_mail("[email protected]","sub","content") ''' me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content) msg['Subject'] = sub msg['From'] = me #msg['To'] = ";".join(to_list) msg['To'] = to_list try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': send_succeed_num = 0 send_fail_num = 0 ##################### #设置服务器,用户名、口令,邮箱的后缀以及标题和内容 mail_host = get_mail_fomat(0) mail_user = get_mail_fomat(1) mail_pass = get_mail_fomat(2) mail_postfix = get_mail_fomat(3) mail_subject = get_mail_fomat(4) mail_content = get_mail_fomat(5) for i in mailto_list: if send_mail(i,mail_subject,mail_content): send_succeed_num +=1 print "%s-->发送成功"%i else: send_fail_num +=1 print "%s-->发送失败"%i print "\n-------------发送成功%d条" %send_succeed_num print "\n-------------发送失败%d条" %send_fail_num</code>
配置文件
list.txt 用于配置要发送的邮件地址列表,每个邮件地址一行
<a href="mailto:[email protected]">[email protected]</a>
<a href="mailto:[email protected]">[email protected]</a>
<a href="mailto:[email protected]">[email protected]</a>
set.txt 用于配置邮件发送设置 请在正式应用时去掉#以及之后的内容。
mail_host=smtp.163.com smtp#服务器
mail_user=axi#用户名
mail_pass=xxx#密码
mail_subject=testsubject#邮件标题
mail_content=testcontent#邮件内容
python就是这样简单好用,一共84行代码而已.
本文转自独弹古调 51CTO博客,原文链接:http://blog.51cto.com/hunkz/1689263,如需转载请自行联系原作者