SMTPLIB 模塊
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP類構造函數,表示與SMTP服務器之間的連接,通過這個連接可以向smtp服務器發送指令,執行相關操作(如:登陸、發送郵件)。所有參數都是可選的。
host:smtp服務器主機名
port:smtp服務的端口,默認是25;如果在創建SMTP對象的時候提供了這兩個參數,在初始化的時候會自動調用connect方法去連接服務器。
smtplib模塊還提供了SMTP_SSL類和LMTP類,對它們的操作與SMTP基本一致。
smtplib.SMTP提供的方法:
SMTP.set_debuglevel(level):設置是否爲調試模式。默認爲False,即非調試模式,表示不輸出任何調試信息。
SMTP.connect([host[, port]]):連接到指定的smtp服務器。參數分別表示smpt主機和端口。注意: 也可以在host參數中指定端口號(如:smpt.yeah.net:25),這樣就沒必要給出port參數。
SMTP.docmd(cmd[, argstring]):向smtp服務器發送指令。可選參數argstring表示指令的參數。
SMTP.helo([hostname]) :使用"helo"指令向服務器確認身份。相當於告訴smtp服務器“我是誰”。
SMTP.has_extn(name):判斷指定名稱在服務器郵件列表中是否存在。出於安全考慮,smtp服務器往往屏蔽了該指令。
SMTP.verify(address) :判斷指定郵件地址是否在服務器中存在。出於安全考慮,smtp服務器往往屏蔽了該指令。
SMTP.login(user, password) :登陸到smtp服務器。現在幾乎所有的smtp服務器,都必須在驗證用戶信息合法之後才允許發送郵件。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :發送郵件。這裏要注意一下第三個參數,msg是字符串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。
SMTP.quit() :斷開與smtp服務器的連接,相當於發送"quit"指令。
EMAIL模塊
emial模塊用來處理郵件消息,包括MIME和其他基於RFC 2822 的消息文檔。使用這些模塊來定義郵件的內容,是非常簡單的。其包括的類有(更加詳細的介紹可見:http://docs.python.org/library/email.mime.html):
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.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一個子類。
class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音頻對象
class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二進制文件對象。
class email.mime.message.MIMEMessage(_msg[, _subtype]):具體的一個message實例,使用方法如下:
msg=mail.Message.Message() #一個實例
msg['to']='[email protected]' #發送到哪裏
msg['from']='[email protected]' #自己的郵件地址
msg['date']='2012-3-16' #時間日期
msg['subject']='hello world' #郵件主題
class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本對象,其中_text是郵件內容,_subtype郵件類型,可以是text/plain(普通文本郵件),html/plain(html郵件), _charset編碼,可以是gb2312等等。
普通文本郵件
# -*- coding: UTF-8 -*-
'''''
發送txt文本郵件
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=[[email protected]]
mail_host="smtp.XXX.com"#設置服務器
mail_user="XXXX"#用戶名
mail_pass="XXXXXX"#口令
mail_postfix="XXX.com"#發件箱的後綴
def send_mail(to_list,sub,content):
me="hello"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
returnTrue
except Exception, e:
print str(e)
returnFalse
if __name__ == '__main__':
if send_mail(mailto_list,"hello","hello world!"):
print"發送成功"
else:
print"發送失敗"
html郵件的發送
# -*- coding: utf-8 -*-
'''''
發送html文本郵件
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=["[email protected]"]
mail_host="smtp.XXX.com"#設置服務器
mail_user="XXX"#用戶名
mail_pass="XXXX"#口令
mail_postfix="XXX.com"#發件箱的後綴
def send_mail(to_list,sub,content): #to_list:收件人;sub:主題;content:郵件內容
me="hello"+"<"+mail_user+"@"+mail_postfix+">"#這裏的hello可以任意設置,收到信後,將按照設置顯示
msg = MIMEText(content,_subtype='html',_charset='gb2312') #創建一個實例,這裏設置爲html格式郵件
msg['Subject'] = sub #設置主題
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host) #連接smtp服務器
s.login(mail_user,mail_pass) #登陸服務器
s.sendmail(me, to_list, msg.as_string()) #發送郵件
s.close()
returnTrue
except Exception, e:
print str(e)
returnFalse
if __name__ == '__main__':
if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五義</a>"):
print"發送成功"
else:
print"發送失敗"
發送帶附件的郵件
# -*- coding: cp936 -*-
'''''
發送帶附件郵件
'''
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
#創建一個帶附件的實例
msg = MIMEMultipart()
#構造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
msg.attach(att1)
#構造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)
#加郵件頭
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
msg['subject'] = 'hello world'
#發送郵件
try:
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXX')#XXX爲用戶名,XXXXX爲密碼
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print'發送成功'
except Exception, e:
print str(e)
利用MIMEimage發送圖片
# -*- coding: cp936 -*-
import smtplib
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
def AutoSendMail():
msg = MIMEMultipart()
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "hello world"
txt = MIMEText("這是中文的郵件內容哦",'plain','gb2312')
msg.attach(txt)
file1 = "C:\\hello.jpg"
image = MIMEImage(open(file1,'rb').read())
image.add_header('Content-ID','<image1>')
msg.attach(image)
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXXX')
server.sendmail(msg['From'],msg['To'],msg.as_string())
server.quit()
if __name__ == "__main__":
AutoSendMail()
利用MIMEimage發送圖片,依然是以附件形式發送的
認證
獲得服務器的特性,如:允許發送的郵件大小。
查看服務器是否支持SSL和TLS安全傳輸。
查看在發送郵件之前是否需要認證。
#!/usr/bin/env python
#-*-coding = UTF-8-*-
#SMTP_email.py
#auth@:xfk
#date@:2012-04-30
import sys
import smtplib
import socket
from getpass import getpass
if len(sys.argv) < 4:
print"[*]usage:%s server fromaddr toaddr " % sys.argv[0]
sys.exit(1)
server = sys.argv[1]
fromaddr = sys.argv[2]
toaddr = sys.argv[3]
message = """
TO: %s
From: %s
Subject: Test Message from SMTP_mail.py
Hello ,This a simple SMTP_mail example.
""" % (','.join(toaddr),fromaddr)
def get_size():
"""獲得服務器允許發送郵件的大小"""
try:
s = smtplib.SMTP(server) #連接到服務器
code = s.ehlo()[0] #返回服務器的特性
usesesmtp = 1
ifnot (200 <= code <=299): #在200到299之間都是正確的返回值
usesesntp = 0
code = s.helo()[0]
ifnot (200 <= code <=299):
raise SMTPHeloError(code,resp)
if usesesmtp and s.has_extn('size'): #獲得服務器允許發送郵件的大小
print"Maxinum message size is ",s.esmtp_features['size']
if len(message) > int(s.esmtp_features['size']):
print"Message too large;aborting."
sys.exit(2)
s.sendmail(fromaddr,toaddr,message)
except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
print"***Your message may not have been sent!"
print e
sys.exit(1)
else:
print"***Message successful sent to %d recipient(s)" % len(toaddr)
def ssl_tls():
"""使用SSL安全套階層和TLS安全傳輸層進行郵件傳輸,確保密碼在傳輸中的安全"""
try:
s = smtplib.SMTP(server) #連接到服務器
code = s.ehlo()[0] #返回服務器的特性
usesesmtp = 1
ifnot (200 <= code <=299): #在200到299之間都是正確的返回值
usesesntp = 0
code = s.helo()[0]
ifnot (200 <= code <=299):
raise SMTPHeloError(code,resp)
if usesesmtp and s.has_extn('starttls'): #查看服務器是否支持TLS
print"Negotiating TLS......"
s.starttls()
code = s.ehlo()[0]
ifnot (200 <= code <=299): #在支持TLS的服務器上是否連接回話成功
print"Couldn't EHLO after STARTTLS."
sys.exit(5)
print"Using TLS connection."
else:
print"Server does not suport TLS; using normal connection."
s.sendmail(fromaddr,toaddr,message) #如果連接TLS成功則使用加密傳輸;若連接TLS出錯則使用普通的傳輸
except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
print"***Your message may not have been sent!"
print e
sys.exit(1)
else:
print"***Message successful sent to %d recipient(s)" % len(toaddr)
def auth_login():
"""當發送郵件時,服務器需要驗證,則輸入用戶名密碼方可發送郵件"""
sys.stdout.write("Enter username: ")
username = sys.stdin.readline().strip()
password = getpass("Enter password: ")
try:
s = smtplib.SMTP(server) #連接到服務器
code = s.ehlo()[0] #返回服務器的特性
usesesmtp = 1
ifnot (200 <= code <=299): #在200到299之間都是正確的返回值
usesesntp = 0
code = s.helo()[0]
ifnot (200 <= code <=299):
raise SMTPHeloError(code,resp)
if usesesmtp and s.has_extn('auth'): #查看服務器是否支持認證
print"Using Authentication connect."
try:
s.login(username,password)
except smtplib.SMTPException,e:
print"Authentication failed:",e
sys.exit(1)
else:
print"Server does not suport Authentication; using normal connect."
s.sendmail(fromaddr,toaddr,message) #如果支持認證則輸入用戶名密碼進行認證;不支持則使用普通形式進行傳輸
except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
print"***Your message may not have been sent!"
print e
sys.exit(1)
else:
print"***Message successful sent to %d recipient(s)" % len(toaddr)
if __name == "__mian__":
get_size()
ssl_tls()
auth_login()