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

来源:互联网 发布:python 编辑器 编辑:程序博客网 时间:2024/04/28 11:51

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

发送邮件模块

import ConfigParserimport smtplibfrom email.mime.text import MIMETextconf = 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 Falseif __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.commail_user = yourusernamemail_postfix = 163.commail_passwd = yourpasswdmail_to = mail_to_account@126.com

整个模块就是这样了,包含了 python 发送邮件 和 python 配置文件解析的 主要用法,如果深入学习,可以就里面出现的具体的部分到 python 的官方文档中阅读。



0 0