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

python发送附件的邮件

2013-03-27 15:15 274 查看
这里是代码,attachment函数不理解的,可以参考我的另一篇blog,/article/8318568.html

sendmail_mime.py

# -*- coding: utf8 -*-
import smtplib
from email import Utils,Encoders
import mimetypes,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
#############
#要发给谁,这里发给2个人
#mailto_list=["mjzheng@xxxxx.com","xxxxx@qq.com"]
#####################
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="mail.xxxxx.com"
mail_user="mjzheng@xxxxx.com"
mail_pass="password"
mail_postfix="xxxxx.com"
######################
#构造添加附件的函数attachment
def attachment(filename):
fd = open(filename,'rb')
mimetype,mimeencoding = mimetypes.guess_type(filename)
if mimetype or (mimeencoding is None):
mimetype = 'application/octet-stream'
maintype,subtype = mimetype.split('/')
if maintype == 'text':
retval = MIMEText(fd.read(),_subtype=subtype)
else:
retval = MIMEBase(maintype,subtype)
retval.set_payload(fd.read())
Encoders.encode_base64(retval)
retval.add_header('Content-Disposition','attachment',filename = filename)
fd.close()
return retval

def send_mail(to_list,sub,content):
'''
to_list:发给谁
sub:主题
content:内容
send_mail("aaa@126.com","sub","content")
'''
me=mail_user
msg = MIMEMultipart()
msg['Subject'] = sub
msg['From'] = me
msg['To'] = to_list
msg['Date'] = Utils.formatdate(localtime=1)
msg['Message-ID'] = Utils.make_msgid()
body = MIMEText(content)
msg.attach(body)
for filename in sys.argv[1:]:
msg.attach(attachment(filename))
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail("xxxxx@qq.com","hello jason","do you know me!"):
print "发送成功"
else:
print "发送失败"


python sendmail_mime.py mail.txt mail.txt.tar.gz
这里发送了两个附件mail.txt和mail.txt.tar.gz

我自己写的,在windows上测试过,可以是用的,大家可以试试看,按照自己的需求来修改。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: