python中的邮箱通信

来源:互联网 发布:品茗bim软件下载 编辑:程序博客网 时间:2024/05/16 10:29

主要的参考资料:http://pymotw.com/2/imaplib/#module-imaplib

参考以上资料,写了一个小程序。小程序的主要功能是实现从163邮箱向qq邮箱发送信息,并在qq邮箱中读取邮件的内容。

遇到的主要问题是:配置文件的读取;邮件内容的匹配。

一下是主要 的代码:

'''Created on Oct 22, 2013@author: lsy'''import imaplibimport smtplibimport emailimport re, os, sysimport timeimport ConfigParserdef open_connection():    config = ConfigParser.ConfigParser()    config.read("/home/lsy/Desktop/2.txt")    hostname = config.get('server', 'hostname')    username = config.get('account', 'username')    password = config.get('account', 'password')    try:        conn = imaplib.IMAP4_SSL(hostname)        print 'Connecting to:', hostname    except:        print 'Connect to the server is failed.'        exit(1)    try:        conn.login(username, password)    except:        print 'Login failed.'        exit(1)    return conn'''pattern = re.compile(r'\((?p<flags>.*?)\) "(?p<delimiter>.*)" (?p<mailbox_name>.*)')def deal_with_pattern(line):    mailbox_name = pattern.match(line)    mailbox_name = mailbox_name.strip('"')    return mailbox_name'''def accept_mail():     #accpet the mail and deal with the email    conn = open_connection()    try:        conn.select('INBOX', readonly = True)        typ, data = conn.fetch('1', '(BODY.PEEK[TEXT])')        for response_part in data:            if isinstance(response_part, tuple):                print response_part[1]                if response_part[1] == 'start\r\n\r\n\r\n':                    return 0    finally:        try:            conn.close()        except:            pass        conn.logout()        def send_mail():     #send email    try:        handle = smtplib.SMTP('smtp.163.com', 25)        handle.login("XXXXX@163.com", "XXXXXX")        msg = 'To: XXXX@qq.com\r\nFrom: XXXX@163.com\r\nSubject: startpc \r\n\r\nstart\r\n'        #print msg        handle.sendmail("XXXX@163.com", "XXXX@qq.com", msg)        return 1    except:        return 0    finally:        handle.close()    if __name__ == '__main__':    while send_mail() == 0:        time.sleep(2)    while 1:        time.sleep(5)        if accept_mail() == 0:            os.system("/sbin/shutdown -h now")