使用python实现发送邮件方法

这篇文章介绍使用python实现发送邮件方法

# coding=utf-8import smtplib
from time import sleep
from email.mime.text import mimetext
from email.mime.multipart import mimemultipartdef send_email(**param):
”’
发送邮件
author:cdq
:param param:{“username”:””,”password”:””,”from_addr”:””,”to_addr”:””,”smtpserver”:””,”subject”:””,”file_path”:””}
:file_path=文件路径
:return:
”’
error = “”
flag = true
try:
# from conf_isms.adconf import local_host_ip
if not param[‘is_send’]:
flag = false
msg = mimemultipart()
content = ‘您好:’ \
‘ 数据报表已发至邮箱,请您查看’ \
‘ 祝您生活愉快!’
body = mimetext(content, _subtype=”html”, _charset=”utf-8″)
msg.attach(body)
if isinstance(param[‘file_path’], list):
for m in param[‘file_path’]:
att = mimetext(open(m, ‘rb’).read(), ‘base64’, ‘utf-8’)
file_name = m.split(‘/’)[-1]
att[“content-type”] = ‘application/octet-stream’
att[“content-disposition”] = ‘attachment; filename=”%s”‘ % file_name.encode(‘gbk’) # 防止下载文件名乱码
msg.attach(att)
msg[‘to’] = ‘;’.join(param[‘to_addr’])
msg[‘from’] = param[‘from_addr’]
msg[‘subject’] = param[‘subject’]
sm = smtplib.smtp(param[‘smtpserver’], port=25)
# sm.set_debuglevel(1)
sm.ehlo()
sm.starttls()
sm.ehlo()
sm.login(param[‘username’], param[‘password’])
sm.sendmail(param[‘from_addr’], param[‘to_addr’], msg.as_string())
sleep(5)
sm.quit()
print “%s send successfully” % param[‘file_path’]
flag = true
except exception, ex:
traceback.print_exc()
print “send failed ”
flag = false
error = “error %s” % str(ex)
finally:
return flag, error

以上就是使用python实现发送邮件方法 的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论