Python 发送邮件

#coding=utf-8
__author__ = 'Xue'
'''
邮件发送
version 1.0
'''

import smtplib
from email.mime.text import MIMEText

class xmail():
    mail_host=''
    mail_from=''
    mail_user=''
    mail_pwd=''
    def __init__(self,host,from_addr,user,pwd):
        self.mail_host=host
        self.mail_from=from_addr
        self.mail_user=user
        self.mail_pwd=pwd

    #收件人列表
    #标题
    #内容
    def send(self,to_list,title,content):
        msg=MIMEText(content,_subtype='html',_charset='gb2312')#设置为html格式
        msg['Subject']=title
        msg['From']=self.mail_from
        msg['To']=';'.join(to_list)
        try:
            s=smtplib.SMTP()
            s.connect(self.mail_host) #连接SMTP
            s.login(self.mail_user,self.mail_pwd)#登陆
            s.sendmail(self.mail_from,to_list,msg.as_string())
            s.close()
            return True
        except Exception, e:
            return False

if __name__=="__main__":
    #注意,内容前要加u,否则中文会乱码
    cont=u'''
    经测试,本内容真实有效!绝对是真的!
    '''

    m=xmail('smtp.163.com','***@163.com','***@163.com','***')
    res= m.send(['***@qq.com'],'测试python发送邮件',cont)
    if res:
        print('sucess')
    else:
        print('fail')

原文地址:https://www.cnblogs.com/babycool/p/4734780.html