打印
[活动]

【项目挑战】Offline Email Box贴子之二 使用python脚本验证收...

[复制链接]
2168|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
zhanzr21|  楼主 | 2016-3-31 16:08 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 zhanzr21 于 2016-3-31 17:15 编辑

上文的理论知识过后, 动手验证邮件收发流程。事先试验过,板子上的python是2.7的,所以我也特地下载了python2.7在我的开发主机上。关于版本一定要注意。python3在桌面开发上成主流了。不过很多嵌入式环境都只支持python2的版本。为了开发效率,最好在桌面上也使用python2来开发验证,到了开发板就不会再来一次移植.关于python2, python3之间的恩怨差别等等,请参考这个连接:我就不详叙了。后面提到的python都是说的python2.
给纠结python2与python3的人看的连接

先来试验python发邮件, python就有一个smtplib管这事情的,所以相对简单,但是板子上面的python2缺少email这个package, 这个package用来管理email信息组织的。我采取了简单的解决方案:
直接把桌面python2的email相关的.py文件给copy到板子的/usr/lib/python2.7/路径,因为python的特点就是代码级别的跨平台。所以还真解决了我的问题。当然这不是解决问题的正确的方法,道德高尚的人应该重新编译内核才对。我暂且这么用着吧。参考的连接是:
Python smtplib 参考
上代码:
import smtplib
import time
from email.message import Message
from time import sleep
import email.utils
import base64

smtpserver='smtp-mail.outlook.com'
username='yourname@outlook.com'
password='password'
from_addr='from@from.com'
to_addr='b@qq.com'
cc_addr='a@foxmail.com'

time=email.utils.formatdate(time.time(),True)

message=Message()
message['Subject']='Mail Subject'
message['From']=from_addr
message['To']=to_addr
message['Cc']=cc_addr
message.set_payload('mail content'+time)
msg=message.as_string()

sm=smtplib.SMTP(smtpserver, port=587, timeout=20)
sm.set_debuglevel(1)

sm.ehlo()
#send: 'ehlo [127.0.1.1]\r\n'
#reply:b'250-BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\r\n'
#reply:b'250-TURN\r\n'
#reply:b'250-SIZE 41943040\r\n'
#reply:b'250-ETRN\r\n'
#reply:b'250-PIPELINING\r\n'
#reply:b'250-DSN\r\n'
#reply:b'250-ENHANCEDSTATUSCODES\r\n'
#reply:b'250-8bitmime\r\n'
#reply:b'250-BINARYMIME\r\n'
#reply:b'250-CHUNKING\r\n'
#reply:b'250-VRFY\r\n'
#reply:b'250-TLS\r\n'
#reply:b'250-STARTTLS\r\n'
#reply:b'250 OK\r\n'
#reply:retcode (250); Msg: b'BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\nTURN\nSIZE 41943040\nETRN\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\n8bitmime\nBINARYMIME\nCHUNKING\nVRFY\nTLS\nSTARTTLS\nOK'
#(250, b'BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\nTURN\nSIZE 41943040\nETRN\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\n8bitmime\nBINARYMIME\nCHUNKING\nVRFY\nTLS\nSTARTTLS\nOK')
sm.starttls()
#send: 'STARTTLS\r\n'
#reply:b'220 2.0.0 SMTP server ready\r\n'
#reply:retcode (220); Msg: b'2.0.0 SMTP server ready'
#(220, b'2.0.0 SMTP server ready')
sm.ehlo()
#send: 'ehlo [127.0.1.1]\r\n'
#reply:b'250-BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\r\n'
#reply:b'250-TURN\r\n'
#reply:b'250-SIZE 41943040\r\n'
#reply:b'250-ETRN\r\n'
#reply:b'250-PIPELINING\r\n'
#reply:b'250-DSN\r\n'
#reply:b'250-ENHANCEDSTATUSCODES\r\n'
#reply:b'250-8bitmime\r\n'
#reply:b'250-BINARYMIME\r\n'
#reply:b'250-CHUNKING\r\n'
#reply:b'250-VRFY\r\n'
#reply:b'250-AUTH LOGIN PLAIN XOAUTH2\r\n'
#reply:b'250 OK\r\n'
#reply:retcode (250); Msg: b'BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\nTURN\nSIZE 41943040\nETRN\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\n8bitmime\nBINARYMIME\nCHUNKING\nVRFY\nAUTH LOGIN PLAIN XOAUTH2\nOK'
#(250, b'BLU436-SMTP196.smtp.hotmail.com Hello [171.43.226.36]\nTURN\nSIZE 41943040\nETRN\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\n8bitmime\nBINARYMIME\nCHUNKING\nVRFY\nAUTH LOGIN PLAIN XOAUTH2\nOK')
sm.login(username, password)
#send: 'AUTH PLAIN AGNldGVzdHNoaaaabbbbsb29rLmNvbQBpZGxlUFlUSE9O\r\n'
#reply:b'235 2.7.0 Authentication succeeded\r\n'
#reply:retcode (235); Msg: b'2.7.0 Authentication succeeded'
#(235, b'2.7.0 Authentication succeeded')
sm.sendmail(from_addr, to_addr, msg)
#send: 'mail FROM:<from@from.com> size=135\r\n'
#reply:b'250 2.1.0 from@from.com....Sender OK\r\n'
#reply:retcode (250); Msg: b'2.1.0 from@from.com....Sender OK'
#send: 'rcpt TO:<a@qq.com>\r\n'
#reply:b'250 2.1.5 d[url=home.php?mod=space&uid=752448]@qq.com[/url] \r\n'
#reply:retcode (250); Msg: b'2.1.5 b@qq.com'
#send: 'data\r\n'
#reply:b'354 Start mail input; end with <CRLF>.<CRLF>\r\n'
#reply:retcode (354); Msg: b'Start mail input; end with <CRLF>.<CRLF>'
#data: (354, b'Start mail input; end with <CRLF>.<CRLF>')
#send: b'Subject: Mail Subject\r\nFrom: from@from.com\r\nTo: ashi@qq.com\r\nCc: a@b.com\r\n\r\nmail contentSat, 27 Feb 2016 02:18:47 +0800\r\n.\r\n'
#reply:b'250 2.6.0 <BLU436-SMTP196pH71y00000fb9@BLU436-SMTP196.smtp.hotmail.com> Queued mail for delivery\r\n'
#reply:retcode (250); Msg: b'2.6.0 <BLU436-SMTP196pH71y00000fb9@BLU436-SMTP196.smtp.hotmail.com> Queued mail for delivery'
#data: (250, b'2.6.0 <BLU436-SMTP196pH71y00000fb9@BLU436-SMTP196.smtp.hotmail.com> Queued mail for delivery')
#{}
sleep(5)

sm.quit()
#send: 'quit\r\n'
#reply:b'221 2.0.0 BLU436-SMTP196.smtp.hotmail.com Service closing transmission channel\r\n'
#reply:retcode (221); Msg: b'2.0.0 BLU436-SMTP196.smtp.hotmail.com Service closing transmission channel'
#(221, b'2.0.0 BLU436-SMTP196.smtp.hotmail.com Service closing transmission channel')



注意用户名密码我修改了,你们要用得改成你们自己的。smtp的地址也的相应修改。

再来imap的收邮件, python中也有个package叫做imaplib
文档在python官网上找,imap的部分我参考了sina博客上面的一个同学的代码,但是现在搜索不到了,所以没法给连接了,代码中有他名字
代码分两部分:
checkMail.py
#-*- encoding: utf-8 -*-
#author : rayment
#CreateDate : 2012-06-24
import imaplib
import email
import InfoOutPut

import sys
reload(sys)
sys.setdefaultencoding('gbk')


def my_unicode(s, encoding):
    if encoding:
        return unicode(s, encoding)
    else:
        return unicode(s)


def checkMail(mailhost, accout, password):
    con = imaplib.IMAP4_SSL(mailhost)
    con.login(accout, password)
    try:
        con.select('INBOX', readonly=True)
        flag, data = con.search(None, 'ALL')
        InfoOutPut.initOutPut()
        InfoOutPut.InfoOutPut('Accout : ' + accout)
        for num in (data[0]).split(' '):
            typ, msg_data = con.fetch(num, '(RFC822)')
            InfoOutPut.InfoOutPut('No : ' + num)
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    ls = msg["From"].split(' ')
                    strfrom = ''
                    if(len(ls) == 2):
                        fromname = email.Header.decode_header((ls[0]).strip('\"'))
                        strfrom = 'From : ' + my_unicode(fromname[0][0], fromname[0][1]) + ls[1]
                        InfoOutPut.InfoOutPut(strfrom, 2)
                    else:
                        strfrom = 'From : ' + msg["From"]
                        InfoOutPut.InfoOutPut(strfrom, 2)
                    strdate = 'Date : ' + msg["Date"]
                    InfoOutPut.InfoOutPut(strdate, 2)
                    subject = email.Header.decode_header(msg["Subject"])
                    strsub = 'Subject : ' + my_unicode(subject[0][0], subject[0][1])
                    InfoOutPut.InfoOutPut(strsub)      
    finally:
        try:
            con.close()
        except:
            pass
        con.**ut()

if __name__ == '__main__':
    checkMail('imap-mail.outlook.com', 'yourname@outlook.com', 'password')

InfoOutput.py
#-*-coding:utf-8-*-
#author : rayment
#CreateDate : 2012-06-24


def initOutPut():
    Border = "+----------------------------------------------------------------------------+"
    print Border


def InfoOutPut(strparam, first = 0):
    '''
       Information input method
       param: string
       param: integer
    '''
    maxlen = 76
    Border = "+----------------------------------------------------------------------------+"
    Mark = "|"
    if first == 1:
        print "\n"
        print Border

    #count length of string,if it more than maxlen then break off it
    strlen = len(strparam.encode('gbk'))
    totallength = strlen
    #print "strlen = %d"%strlen
    if strlen > maxlen:
        start = 0
        end = maxlen

        while(strlen > 0):
            #print "start = %d"%start
            #print "end = %d"%end
            
            row = []
            row.append(Mark)
            row.append(strparam[start:end])

            if strlen > maxlen:
                start = start + maxlen
                if (end + maxlen) > totallength:
                    end = totallength
                else:
                    end = end + maxlen
            else:
                row.append(' ' * (maxlen - strlen))
                start = start + strlen
                end = end + strlen
                #print "last start = %d"%start
                #print "last end = %d"%end
               
            row.append(Mark)
            print ''.join(row)
            strlen = strlen - maxlen
            #print "current strlen= %d\n"%strlen
               
    else:
        newrow = []
        newrow.append(Mark)
        newrow.append(strparam)
        newrow.append(' ' * (maxlen - strlen))
        newrow.append(Mark)
        print ''.join(newrow)

    if first == 0 or first == 1:
        print Border
   
   
if __name__ == '__main__':
    '''
       test unit
    '''
    str1 = "Account : xxxxxx@126.com"
    str2 = "Account : xxxxx@163.com"
    str3 = "From : xxxx@university.com"
    str5 = "Subject : begina1a2a3a4a5a6a7yyyyyyyyyyyyyddddddddddddddddddddddddddyyyyyyy8aaaaaaaaaaaaaaaavvvvvvvvvvvvvvvvvvvvssssssssssssssssssccccccccccccccccccccc72rrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeejjjjjjjjjjjjjjjjjjjjjjjjjjjjjj5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0llllllllllluuouou"
    str4 = "Date : 2012-6-24 13:00"
    str6 = "Subject : begina1a2a3a4a5a6a7yyyyyyyyyyyyyddddddddddddddddddddddddddyyyyyyy8aaaaaaaaaaaaaaaav72rrrrrrrrrrrrrrrrrrrreeeeeee"
    str7 = "Subject : begina1a2a3a4a5a6a7yyyyyyyyyyyyyddddddddddddddddddddddddddyyyyyyy8aaaaaaaaaaaaaaaav72rrrrrrrrrrrrrrrrrrrreeeeeee9ddddddpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp4"
    initOutPut()
    InfoOutPut(str6)
    InfoOutPut(str7)
    InfoOutPut(str5)

老规矩,用户名密码我隐去了。

这两个过程我都在host机器上搞通了。又下载到板子上运行通过了。除了上面年说的email缺失之外,host与开发板子上几乎无区别.

下一篇介绍交叉编译C语言程序的过程。python毕竟只能验证过程与原理.

相关帖子

沙发
zhanzr21|  楼主 | 2016-4-27 23:17 | 只看该作者
太好了 學習了

使用特权

评论回复
板凳
cnb12345| | 2016-4-29 12:00 | 只看该作者

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

91

主题

1013

帖子

34

粉丝