您的位置:首页 > 编程语言 > Python开发

python 发送邮件 -- 解析配置文件

2014-02-15 15:24 615 查看
昨天做了一个用python发送邮件的模块。因为是用在项目中,所以写得比较模块化一点,增加了账户的配置文件,所以其中也用到了Python 配置文件解析模块。把他们集中在一起,以供新手参考,对有同样需求的新手,望有所帮助。实现过程中参考了 这两篇文章,特此感谢

python发送邮件参考1 和这个
python 配置文件解析。

发送邮件模块

import ConfigParser
import smtplib
from email.mime.text import MIMEText

conf = ConfigParser.ConfigParser()
conf.read('test.cfg')

#sections = conf.sections()
#options = conf.options('section_a')

mail_to = conf.get('section_a','mail_to')
mail_host = conf.get('section_a','mail_host')
mail_user = conf.get('section_a','mail_user')
mail_passwd = conf.get('section_a','mail_passwd')
mail_postfix = conf.get('section_a','mail_postfix')

def send_mail(mail_to, subject, content):
me = mail_user + '@' + mail_postfix
msg = MIMEText(content,_subtype='plain',_charset='utf-8')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = mail_to

try:
sv = smtplib.SMTP()
sv.connect(mail_host)
sv.login(mail_user, mail_passwd)
sv.sendmail(me,mail_to, msg.as_string())
sv.close()
return True
except Exception, e:
print str(e)
return False

if __name__ == '__main__':
subject = 'Python test'
content = 'Nothing in this world is free!'
if send_mail(mail_to,subject,content):
print 'sent success'
else:
print 'sent failed'

配置文件 test.cfg 。当然,上面的例子中 这个文件是和 .py 文件是在同一个目录下的,如果不在,配置路径就可以。
[section_a]
mail_host = smtp.163.com
mail_user = yourusername
mail_postfix = 163.com
mail_passwd = yourpasswd
mail_to = mail_to_account@126.com

整个模块就是这样了,包含了 python 发送邮件 和 python 配置文件解析的 主要用法,如果深入学习,可以就里面出现的具体的部分到 python 的官方文档中阅读。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息