首页 > 技术文章 > python 发送邮件

miranda-tang 2016-06-12 17:43 原文

#!/usr/bin/python
# -*- encoding:utf-8 -*-


 

import smtplib
from email.mime.text import MIMEText
 
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class mailsender(object):
    def __init__(self):
        self.mail_host="smtp.163.com"   #设置服务器
        self.mail_user="miranda_tang"      #用户名
        self.mail_pass="123456"          #密码(用户名和密码我都是随便写的)
        self.mail_postfix="163.com"     #设置邮箱后缀
    def send_mail(self,to_list,sub,content):
        me=self.mail_user+"<"+self.mail_user+"@"+self.mail_postfix+">"
        msg=MIMEText(content,_subtype='plain',_charset='utf-8')
        msg['Subject']=sub
        msg['From']=me
        msg['To']=";".join(to_list)
        try:
            server=smtplib.SMTP()
            server.connect(self.mail_host)
            server.login(self.mail_user,self.mail_pass)
            server.sendmail(me,to_list,msg.as_string())
            server.close()
            return True
        except Exception,e:
            print str(e)
            return False

if __name__=='__main__':
    mailto_list=['tangxin2@meilele.com']
    content="测试邮件"
    if mailsender().send_mail(mailto_list,u"测试测试",content):
        print 'success'
    else:
        print 'fail'

推荐阅读