python smtplib 發送郵件

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 = '[email protected]'

mail_pwd = "123456"

to_maillist = ['[email protected]','[email protected]']


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,'各位好,快下班了,送上祝福!!')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章