如何使用python自动检测新电子邮件

时间:2017-09-09 18:59:59

标签: python email

我有使用IMAP从我的Gmail收件箱中读取的代码

import imaplib
import email

email_address = 'myemail@gmail.com' # Placeholder
email_pass = 'mypassword' # Placeholder

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(email_address, email_pass)
mail.select('inbox')

type, data = mail.search(None, '(UNSEEN)')
mail_ids = data[0]
id_list = mail_ids.split()

if len(id_list) > num_of_mail:
    print('New Mail Found...\n')

    for i in range(int(id_list[-1]), int(id_list[0]) -1, -1):
        typ, data = mail.fetch(i, '(RFC822)')

        for response_part in data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                email_subject = msg['subject']
                email_from = msg['from']
                email_body = msg.get_payload()[0].get_payload()
                print('\nFrom: %s' % email_from)
                print('\nSubject: %s' % email_subject)
                print('\nEmail Body: %s \n' % email_body)

这很好但我每次想要阅读我的电子邮件时都必须运行该程序 如何将此代码放入循环中以便每次收到新电子邮件时它会自动检测并打印内容或将其写入文本文件?

我尝试了这个,但它不起作用:

import imaplib
import email

email_address = 'myemail@gmail.com' # Placeholder
email_pass = 'mypassword' # Placeholder

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(email_address, email_pass)

num_of_mail = 0

while True:

    mail.select('inbox')

    type, data = mail.search(None, '(UNSEEN)')
    mail_ids = data[0]
    id_list = mail_ids.split()

    if len(id_list) > num_of_mail:
        print('New Mail Found...\n')

        for i in range(int(id_list[-1]), int(id_list[0]) -1, -1):
            typ, data = mail.fetch(i, '(RFC822)')

            for response_part in data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    email_subject = msg['subject']
                    email_from = msg['from']
                    email_body = msg.get_payload()[0].get_payload()
                    file = open('EMAIL.txt','w')
                    file.write(email_from)
                    file.write(email_subject)
                    file.write(email_body)
                    file.close()
        num_of_mail = len(id_list)

当我运行它时,它会找到我已经拥有的任何看不见的电子邮件,但如果我在运行该程序后收到新电子邮件,则它不会检测到它。这是为什么 ?它每次都在查看ID,因此它应该检测到新的电子邮件。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:0)

试试这个

import imaplib, serial, struct, time
class Mail():
    def __init__(self):
        self.user= 'USER'
        self.password= 'PASS'
        self.ser = serial.Serial('/dev/tty.usbmodem621', 9600)
        self.M = imaplib.IMAP4_SSL('imap.gmail.com', '993')
        self.M.login(self.user, self.password)      
    def checkMail(self):
        self.M.select()
        self.unRead = self.M.search(None, 'UnSeen')
        return len(self.unRead[1][0].split())  
    def sendData(self):
        self.numMessages= self.checkMail()
        #turn the string into packed binary data to send int
        self.ser.write(struct.pack('B', self.numMessages))       
email = Mail()
# check for new mail every minute
while 1:
    print 'Sending'
    email.sendData()
    time.sleep(60)