#!/usr/bin/python
#-*-coding:utf-8-*-
import smtplib;
from email.mime.text import MIMEText

def send_email(host,username,passwd,send_to,subject,content):
    msg = MIMEText( content.encode('utf8'), _subtype = 'html', _charset = 'utf8')
    msg['From'] = username
    msg['Subject'] = u'%s' % subject
    msg['To'] = ",".join(send_to)
    
    try:
        s = smtplib.SMTP_SSL(host,465)        
        s.login(username, passwd )
        s.sendmail(username, send_to,msg.as_string())
        s.close()
    except Exception as e:
        print 'Exception: send email failed', e

if __name__ == '__main__':
    host = 'smtp.xxx.com'
    username = 'aaa@xxx.com'
    passwd = '########'
    to_list = ['a@y.com','b@t.com']
    subject = "邮件主题"
    content = '使用Python发送邮件'
    send_email(host,username,passwd,to_list,subject,content)


注意:不能将文件名叫做email.py,否则会报 ImportError: No module named mime.text

因为在代码开头使用了 from email.mime.text import MIMEText

如果文件名叫email.py,呵呵,你懂得。。。


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐