1、smtplib模塊
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP類構造函數,表示與SMTP服務器之間的連接,通過這個連接可以向smtp服務器發送指令,執行相關操作(如:登陸、發送郵件)。所有參數都是可選的。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :發送郵件。這裡要注意一下第三個參數,msg是字符串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。
2、email模塊
class email.mime.text.MIMEText(_text[, _subtype[, _charset]])
用於生成MIME對象的主體文本:_text指定郵件內容,_subtype指定郵件類型,_charset指定編碼。
class email.mime.multipart.MIMEMultipart()
用於生成包含多個部分的郵件體的MIME對象
class email.mime.base.MIMEBase(_maintype, _subtype, **_params)
這是MIME的一個基類。一般不需要在使用時創建實例。其中_maintype是內容類型,如text或者image。_subtype是內容的minor type 類型,如plain或者gif。 **_params是一個字典,直接傳遞給Message.add_header()。
class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]
MIMEBase的一個子類,多個MIME對象的集合,_subtype默認值為mixed。boundary是MIMEMultipart的邊界,默認邊界是可數的
class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]])
MIME二進制文件對象。
下面用python寫個發送郵件 帶附件的郵件
# -*- coding: utf-8 -*-
#!/usr/bin/python
# Filename : mail.py
# From www.biuman.com
import smtplib,mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['From'] = "biuman@163.com"
msg['To'] = "tobiuman@163.com"
msg['Subject'] = "subject here"
#添加內容
txt = MIMEText('郵件內容')
msg.attach(txt)
#添加附件
fileName = r'e:/psb.jpg'
ctype, encoding = mimetypes.guess_type(fileName) #獲取附件的類型
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
att = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype)
att.add_header('Content-Disposition', 'attachment', filename = fileName)
msg.attach(att)
try:
smtp =smtplib.SMTP()
smtp.connect("smtp.163.com",'25')
smtp.login("biuman@163.com","password")
smtp.sendmail('biuman@163.com', 'tobiuman@163.com', msg.as_string())
smtp.quit()
print u'發送成功'
except Exception, e:
print str(e)