SMTP 郵件發送

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等等。

普通文本郵件


  1. # -*- coding: UTF-8 -*-

  2. '''''

  3. 發送txt文本郵件

  4. '''

  5. import smtplib    

  6. from email.mime.text import MIMEText    

  7. mailto_list=[[email protected]]  

  8. mail_host="smtp.XXX.com"#設置服務器

  9. mail_user="XXXX"#用戶名

  10. mail_pass="XXXXXX"#口令

  11. mail_postfix="XXX.com"#發件箱的後綴

  12. def send_mail(to_list,sub,content):    

  13.    me="hello"+"<"+mail_user+"@"+mail_postfix+">"

  14.    msg = MIMEText(content,_subtype='plain',_charset='gb2312')    

  15.    msg['Subject'] = sub    

  16.    msg['From'] = me    

  17.    msg['To'] = ";".join(to_list)    

  18. try:    

  19.        server = smtplib.SMTP()    

  20.        server.connect(mail_host)    

  21.        server.login(mail_user,mail_pass)    

  22.        server.sendmail(me, to_list, msg.as_string())    

  23.        server.close()    

  24. returnTrue

  25. except Exception, e:    

  26. print str(e)    

  27. returnFalse

  28. if __name__ == '__main__':    

  29. if send_mail(mailto_list,"hello","hello world!"):    

  30. print"發送成功"

  31. else:    

  32. print"發送失敗"


html郵件的發送


  1. # -*- coding: utf-8 -*-

  2. '''''

  3. 發送html文本郵件

  4. '''

  5. import smtplib    

  6. from email.mime.text import MIMEText    

  7. mailto_list=["[email protected]"]  

  8. mail_host="smtp.XXX.com"#設置服務器

  9. mail_user="XXX"#用戶名

  10. mail_pass="XXXX"#口令

  11. mail_postfix="XXX.com"#發件箱的後綴

  12. def send_mail(to_list,sub,content):  #to_list:收件人;sub:主題;content:郵件內容

  13.    me="hello"+"<"+mail_user+"@"+mail_postfix+">"#這裏的hello可以任意設置,收到信後,將按照設置顯示

  14.    msg = MIMEText(content,_subtype='html',_charset='gb2312')    #創建一個實例,這裏設置爲html格式郵件

  15.    msg['Subject'] = sub    #設置主題

  16.    msg['From'] = me    

  17.    msg['To'] = ";".join(to_list)    

  18. try:    

  19.        s = smtplib.SMTP()    

  20.        s.connect(mail_host)  #連接smtp服務器

  21.        s.login(mail_user,mail_pass)  #登陸服務器

  22.        s.sendmail(me, to_list, msg.as_string())  #發送郵件

  23.        s.close()    

  24. returnTrue

  25. except Exception, e:    

  26. print str(e)    

  27. returnFalse

  28. if __name__ == '__main__':    

  29. if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五義</a>"):    

  30. print"發送成功"

  31. else:    

  32. print"發送失敗"



發送帶附件的郵件


  1. # -*- coding: cp936 -*-

  2. '''''

  3. 發送帶附件郵件

  4. '''

  5. from email.mime.text import MIMEText  

  6. from email.mime.multipart import MIMEMultipart  

  7. import smtplib  

  8. #創建一個帶附件的實例

  9. msg = MIMEMultipart()  

  10. #構造附件1

  11. att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')  

  12. att1["Content-Type"] = 'application/octet-stream'

  13. att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字

  14. msg.attach(att1)  

  15. #構造附件2

  16. att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')  

  17. att2["Content-Type"] = 'application/octet-stream'

  18. att2["Content-Disposition"] = 'attachment; filename="123.txt"'

  19. msg.attach(att2)  

  20. #加郵件頭

  21. msg['to'] = '[email protected]'

  22. msg['from'] = '[email protected]'

  23. msg['subject'] = 'hello world'

  24. #發送郵件

  25. try:  

  26.    server = smtplib.SMTP()  

  27.    server.connect('smtp.XXX.com')  

  28.    server.login('XXX','XXXXX')#XXX爲用戶名,XXXXX爲密碼

  29.    server.sendmail(msg['from'], msg['to'],msg.as_string())  

  30.    server.quit()  

  31. print'發送成功'

  32. except Exception, e:    

  33. print str(e)  

利用MIMEimage發送圖片


  1. # -*- coding: cp936 -*-

  2. import smtplib  

  3. import mimetypes  

  4. from email.mime.text import MIMEText  

  5. from email.mime.multipart import MIMEMultipart  

  6. from email.mime.image import MIMEImage  

  7. def AutoSendMail():  

  8.    msg = MIMEMultipart()  

  9.    msg['From'] = "[email protected]"

  10.    msg['To'] = "[email protected]"

  11.    msg['Subject'] = "hello world"

  12.    txt = MIMEText("這是中文的郵件內容哦",'plain','gb2312')      

  13.    msg.attach(txt)  

  14.    file1 = "C:\\hello.jpg"

  15.    image = MIMEImage(open(file1,'rb').read())  

  16.    image.add_header('Content-ID','<image1>')  

  17.    msg.attach(image)  

  18.    server = smtplib.SMTP()  

  19.    server.connect('smtp.XXX.com')  

  20.    server.login('XXX','XXXXXX')  

  21.    server.sendmail(msg['From'],msg['To'],msg.as_string())  

  22.    server.quit()  

  23. if __name__ == "__main__":  

  24.    AutoSendMail()  

利用MIMEimage發送圖片,依然是以附件形式發送的

認證

獲得服務器的特性,如:允許發送的郵件大小。
查看服務器是否支持SSL和TLS安全傳輸。
查看在發送郵件之前是否需要認證。


  1. #!/usr/bin/env python

  2. #-*-coding = UTF-8-*-

  3. #SMTP_email.py

  4. #auth@:xfk

  5. #date@:2012-04-30

  6. import sys  

  7. import smtplib  

  8. import socket  

  9. from getpass import getpass  

  10. if len(sys.argv) < 4:  

  11. print"[*]usage:%s server fromaddr toaddr " % sys.argv[0]  

  12.    sys.exit(1)  

  13. server = sys.argv[1]  

  14. fromaddr = sys.argv[2]  

  15. toaddr = sys.argv[3]  

  16. message = """

  17. TO: %s

  18. From: %s

  19. Subject: Test Message from SMTP_mail.py

  20. Hello ,This a simple SMTP_mail example.

  21. """ % (','.join(toaddr),fromaddr)  

  22. def get_size():  

  23. """獲得服務器允許發送郵件的大小"""

  24. try:  

  25.        s = smtplib.SMTP(server)     #連接到服務器

  26.        code = s.ehlo()[0]      #返回服務器的特性

  27.        usesesmtp = 1

  28. ifnot (200 <= code <=299):         #在200到299之間都是正確的返回值

  29.            usesesntp = 0

  30.            code = s.helo()[0]  

  31. ifnot (200 <= code <=299):  

  32. raise SMTPHeloError(code,resp)  

  33. if usesesmtp and s.has_extn('size'):         #獲得服務器允許發送郵件的大小

  34. print"Maxinum message size is ",s.esmtp_features['size']  

  35. if len(message) > int(s.esmtp_features['size']):  

  36. print"Message too large;aborting."

  37.                sys.exit(2)  

  38.        s.sendmail(fromaddr,toaddr,message)  

  39. except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:  

  40. print"***Your message may not have been sent!"

  41. print e  

  42.        sys.exit(1)  

  43. else:  

  44. print"***Message successful sent to %d recipient(s)" % len(toaddr)  

  45. def ssl_tls():  

  46. """使用SSL安全套階層和TLS安全傳輸層進行郵件傳輸,確保密碼在傳輸中的安全"""

  47. try:  

  48.        s = smtplib.SMTP(server)     #連接到服務器

  49.        code = s.ehlo()[0]      #返回服務器的特性

  50.        usesesmtp = 1

  51. ifnot (200 <= code <=299):         #在200到299之間都是正確的返回值

  52.            usesesntp = 0

  53.            code = s.helo()[0]  

  54. ifnot (200 <= code <=299):  

  55. raise SMTPHeloError(code,resp)  

  56. if usesesmtp and s.has_extn('starttls'):         #查看服務器是否支持TLS

  57. print"Negotiating TLS......"

  58.            s.starttls()  

  59.            code = s.ehlo()[0]  

  60. ifnot (200 <= code <=299):             #在支持TLS的服務器上是否連接回話成功

  61. print"Couldn't EHLO after STARTTLS."

  62.                sys.exit(5)  

  63. print"Using TLS connection."

  64. else:  

  65. print"Server does not suport TLS; using normal connection."

  66.        s.sendmail(fromaddr,toaddr,message)         #如果連接TLS成功則使用加密傳輸;若連接TLS出錯則使用普通的傳輸

  67. except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:  

  68. print"***Your message may not have been sent!"

  69. print e  

  70.        sys.exit(1)  

  71. else:  

  72. print"***Message successful sent to %d recipient(s)" % len(toaddr)  

  73. def auth_login():  

  74. """當發送郵件時,服務器需要驗證,則輸入用戶名密碼方可發送郵件"""

  75.    sys.stdout.write("Enter username: ")  

  76.    username = sys.stdin.readline().strip()  

  77.    password = getpass("Enter password: ")  

  78. try:  

  79.        s = smtplib.SMTP(server)     #連接到服務器

  80.        code = s.ehlo()[0]      #返回服務器的特性

  81.        usesesmtp = 1

  82. ifnot (200 <= code <=299):         #在200到299之間都是正確的返回值

  83.            usesesntp = 0

  84.            code = s.helo()[0]  

  85. ifnot (200 <= code <=299):  

  86. raise SMTPHeloError(code,resp)  

  87. if usesesmtp and s.has_extn('auth'):         #查看服務器是否支持認證

  88. print"Using Authentication connect."

  89. try:  

  90.                s.login(username,password)  

  91. except smtplib.SMTPException,e:  

  92. print"Authentication failed:",e  

  93.                sys.exit(1)  

  94. else:  

  95. print"Server does not suport Authentication; using normal connect."

  96.        s.sendmail(fromaddr,toaddr,message)         #如果支持認證則輸入用戶名密碼進行認證;不支持則使用普通形式進行傳輸

  97. except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:  

  98. print"***Your message may not have been sent!"

  99. print e  

  100.        sys.exit(1)  

  101. else:  

  102. print"***Message successful sent to %d recipient(s)" % len(toaddr)  

  103. if __name == "__mian__":  

  104.    get_size()  

  105.    ssl_tls()  

  106.    auth_login()  


原文出處:http://blog.csdn.net/wcc526/article/details/16803503

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