python學習筆記(十一)使用email與smtplib

在一些網站註冊中,會自動發送一封郵件用於驗證。python也可以實現發送郵件,使用email與smtplib這兩個模塊。本文介紹兩個模塊的大致作用,在文末給出學習項目中正在使用中的例子。
email模塊主要用於構建郵件的內容,其本質是一個格式化的工具。smtplib作用主要是發送郵件,使用SMTP協議。

開始

在發送郵件之前需要了解郵件的大致結構。

郵件的結構

一封郵件的主要構成有寄件人(From)、收信人(To)、主題(Subject)、內容。
使用email中的模塊來構造一個文字郵件內容:

from email.mime.text import MIMEText

msg = MIMEText(u'注意:\r\n具體內容見附件','plain','utf-8')
msg_mt['Subject'] = u'通知'
msg_mt['From'] = 'XXXX<[email protected]>'
msg_mt['To'] = "[email protected]"

在構造對象時即可傳入其內容。也可以使用set_payload函數。

發送郵件

發送郵件時,必須連接一個郵件服務器,通常需要用戶名和口令。

smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, msg_mt['To'], msg_mt.as_string())
smtp.quit()

一個例子

email庫中包含許多基於MIMEBase的mime類,可以通過MIMEMultipart()結合起來,發送附件(addfile()函數)。

#coding: utf-8  
import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.header import Header
from email import encoders
import mimetypes

class email_sender(object):
    def __init__(self,usrname,password,sever = 'smtp.163.com'):
        self.usrname = usrname
        self.password = password
        self.sever = sever
        self.content = ''
        self.msg = MIMEMultipart()
        self.file_list = []


    def add_text(self,str):
        self.content = self.content + str

    def add_file(self,fname):

        mimetype,mimeencoding = mimetypes.guess_type(fname)
        if mimeencoding or (mimetype is None):
            mimetype = "application/octet-stream"
        maintype,subtype = mimetype.split("/")

        with open(fname,'rb') as fin:
            mime = None
            if mimetype == 'text':
                mime = MIMEText(fin.read(),_subtype = subtype)
            else:
                mime = MIMEBase(maintype,subtype)
                mime.set_payload(fin.read())
                encoders.encode_base64(mime)
            mime.add_header('Content-Disposition','attachment',filename=fname)
            scount = str(len(self.file_list))
            mime.add_header('Content-ID', '<'+scount+'>')
            mime.add_header('X-Attachment-Id', scount)

            self.file_list.append(mime)

    def sendto(self,subject,dst_addr):
        self.msg['Subject'] = Header(subject, 'utf-8')
        print Header(subject, 'utf-8')
        self.msg['From'] = 'dljgs<%s>'%self.usrname
        print 'dljgs<%s>'%self.usrname
        self.msg['To'] = dst_addr
        print dst_addr

        self.msg.attach(MIMEText(self.content,'plain','utf-8'))
        for item in self.file_list:
            self.msg.attach(item)
        smtp = smtplib.SMTP()
        smtp.connect(self.sever)
        smtp.login(self.usrname, self.password)
        smtp.sendmail(self.usrname, dst_addr, self.msg.as_string())
        smtp.quit()

參考資料:
SMTP:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000
import錯誤:http://blog.csdn.net/spring292713/article/details/45077649
添加附件:http://blog.chinaunix.net/uid-199788-id-99454.html

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