python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。但由于这个smtplib用起来也不是特别方便,于是对smtplib的各个参数作了进一步加工。写了一个比较实用的发送邮件的函数。
整个函数需要传递七个参数,包括收件人地址(列表类型,可以一次发送到多个人),主题,内容,附件(列表类型,列表里的每个值是附件所在位置),发件人(可选参数),发件人密码(可选参数)。邮箱后缀(可选参数)。
写了一个测试文件,所有代码张贴如下:
# !/usr/bin/env python# -*- coding:utf-8 -*-# 导入smtplib和MIMETextfrom email
import encodersfrom email.header
import
Headerfrom email.mime.text
import
MIMETextfrom email.mime.base
import
MIMEBasefrom email.mime.multipart
import
MIMEMultipartfrom email.utils
import parseaddr, formataddrimport smtplib## ## ## ## ## ## ## ## ## ## #
# 设置服务器,用户名、口令以及邮箱的后缀mail_host="smtp.163.com"mail_user="***@163.com"mail_pass="*******"mail_postfix="163.com"## ## ## ## ## ## ## ## ## ## ##
def send_mail(to_list,sub,content,attachment,user=mail_user,pwd=mail_pass,host=mail_host):‘‘‘to_list:发给谁(接受的参数是列表)sub:主题content:内容attachment:附件的地址(接受的参数是列表)user:发件人的邮箱(可选参数)pwd:发件人邮箱的密码(可选参数)return : True:发送成功False:发送失败ex: send_mail(["a@cym.so"],"sub","content","/Users/lanyy/Desktop/screenshot_at_2014-11-5_0_34_25.png","/Users/lanyy/Desktop/hannuo.py")‘‘‘me = _format_addr(u‘<%s>
<%s>‘ %
(mail_user,mail_user))msg =
MIMEMultipart()msg[‘Subject‘]
=
submsg[‘From‘]
= memsg[‘To‘]
=
";".join(to_list)msg.attach(MIMEText(content,
‘plain‘,
‘utf-8‘))for file
in attachment:# add file:with open(file,
‘rb‘)
as f:mime =
MIMEText(f.read(),
‘base64‘,
‘gb2312‘)mime["Content-Type"]
=
‘application/octet-stream‘mime["Content-Disposition"]
=
‘attachment; filename=‘+file.split("/")[-1]# mime = MIMEBase(‘image‘, ‘png‘, filename=‘screenshot_at_2014-11-5_0_34_25.png‘)msg.attach(mime)try:s = smtplib.SMTP()s.connect(host)s.login(user,mail_pass)s.sendmail(me,
to_list, msg.as_string())s.close()return
Trueexcept
Exception, e:print str(e)return
Falsedef _format_addr(s):name, addr
= parseaddr(s)return formataddr((
\Header(name,
‘utf-8‘).encode(),
\addr.encode(‘utf-8‘)
if isinstance(addr,
unicode)
else addr))if __name__
==
‘__main__‘:if send_mail(["****@163.com","*****@qq.com"],"测试邮件","这是一封测试邮件",[]):print
"发送成功"else:print
"发送失败"
我们可以把它作为一个util,需要的时候直接import进来就可以了。
转自:http://blog.saymagic.cn/2014/11/19/python-send-email.html
原文地址:http://blog.csdn.net/saymagic/article/details/43909627