python读txt并带附件发邮件

      需求:

      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.异常信息处理

 

            效果:

             

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值