python附件发送到邮箱

编程入门 行业动态 更新时间:2024-10-17 19:29:39

python附件<a href=https://www.elefans.com/category/jswz/34/1771348.html style=发送到邮箱"/>

python附件发送到邮箱

需求:

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"

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

效果:

更多推荐

python附件发送到邮箱

本文发布于:2024-02-16 23:11:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1691783.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   附件   邮箱   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!