首页 > 编程语言 > 详细

python读txt并带附件发邮件

时间:2016-04-15 02:27:47      阅读:332      评论:0      收藏:0      [点我收藏+]

? ? ? 需求:

? ? ? 1.读取txt为邮件的正文

? ? ? 2.把.txt作附件发送

?

? ? ? ?实现:

?

? ? ? ? 看代码

?

? ? ? ? ??#!/usr/bin/env python

# _*_ coding:utf-8 _*_
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import sys,os
# import chardet




mail_host = "smtp.exmail.qq.com"
mail_user "
mail_pass =" "

module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir,‘command_list‘)
mail_content = open(file_path)


mail_to = sys.argv[1]
subject = sys.argv[2]
#content = sys.argv[3]
content = mail_content.read()
mail_content.close()
print  content

def send_mail(mail_user, mail_to, sub, content):

    # msg = MIMEText(content, _subtype=‘plain‘)
    msg = MIMEMultipart()
    msg[‘Subject‘] = sub
    msg[‘From‘] = mail_user
    msg[‘To‘] = mail_to
    msg[‘content‘] = content
    msg.attach(MIMEText(content))
    print  msg
    att = MIMEApplication(open(‘command_list‘, ‘rb‘).read())
    att.add_header(‘Content-Disposition‘, ‘attachment‘, filename="commlist_list.txt")
    # att["Content-Type"] = ‘application/octet-stream‘
    att["Content-Disposition"] = ‘download‘
    msg.attach(att)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user, mail_pass)
        s.sendmail(mail_user, mail_to, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print e.message
        return False
if __name__ == ‘__main__‘:
    send_mail(mail_user, mail_to, subject, content.decode("ascii").encode("utf-8"))
    print  content

?

? ? ? ? ? 后期改进:

? ? ? ? ? ? ? ? ?1.加入class,方便项目引用

? ? ? ? ? ? ? ? ?2.异常信息处理

?

? ? ? ? ? ? 效果:

? ? ? ? ? ? ?
bubuko.com,布布扣
?

python读txt并带附件发邮件

原文:http://hugoren.iteye.com/blog/2290161

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!