SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplibemail两个模块,email负责构造邮件,smtplib负责发送邮件。学习了一下,以后也许用得着!!


#!/usr/bin/env python

#coding:utf8



from email import encoders

from email.header import Header

from email.mime.text import MIMEText

from email.utils import parseaddr,formataddr

import smtplib


mail_host = 'smtp.gmail.com'

mail_user = 'xxx@gmail.com'

mail_pwd = "123456"

to_maillist = ['abc@163.com','abc@139.com']


def send_mail(content,mailto,get_sub):

    print 'Setting MIMEText'

    msg = MIMEText(content.encode('utf8'),_subtype='html',_charset='utf8')

    msg['From'] = mail_user

    msg['Subject'] = '<%s>' %get_sub

    msg['To'] = ",".join(mailto)

    

    try:

print 'connecting' ,mail_host

s  = smtplib.SMTP_SSL(mail_host,465)

s.set_debuglevel(1)

print 'login to mail_host'

s.login(mail_user,mail_pwd)

print 'send email'

s.sendmail(mail_user,mailto,msg.as_string())

print 'close the connection between the mail server'

s.quit()

    except Exception as e:

print 'exception',e



c= " <html><body><h1>Hello</h1><p>send by <a href = 'http://www.baidu.com'> 百度</a></p></body><html>"

send_mail(c,to_maillist,'各位好,快下班了,送上祝福!!')