How can I send my email message only once per email?

I am making a Python script that checks emails from login. Here is my code:

#!/usr/bin/python
import imaplib, getpass

mail = imaplib.IMAP4_SSL('imap.gmail.com')
u = raw_input('Your Gmail Address: ')
p = getpass.getpass()
mail.login(u, p)
mail.select("inbox")

while 1:
        r, data = mail.search(None, "ALL")
        ids = data[0]
        id_list = ids.split()
        latest_email_id = id_list[-1]
        r, data = mail.fetch(latest_email_id, "(RFC822)")
        raw_email = data[0][1]
        print raw_email

      

The problem is it keeps showing the same email over and over (until a new one is received) due to the loop while

.

How to do it:

  • Show only received email once until a new one is received.
  • Show only once
  • Repeat forever
+3


source to share


2 answers


I found a solution:

list = []

while 1:
        mail.select('inbox')
        r, data = mail.search(None, "ALL")
        ids = data[0]
        id_list = ids.split()
        latest_email_id = id_list[-1]
        r, data = mail.fetch(latest_email_id, "(RFC822)")
        raw_email = data[0][1]
        if not raw_email in list:
                print raw_email
                list.append(raw_email)

      

Basically, it creates a list called list

:

list = []

      



And then, in a loop, it's basically the same, except at the beginning, it checks the mailbox again:

while 1:
    mail.select('inbox')

      

And then, at the end, it will print

raw_email

if it's not

in list

, and then adds it to list

, so it won't be print

ed again :

if not raw_email in list:
                print raw_email
                list.append(raw_email)

      

0


source


So, you basically want to develop an email listener ... In the following code, I will just load invisible emails so that we only have the relevant data. Then, after the email has been sent, I mark it as read so that it doesn't come back again:

while 1:
        r, search_data = mail.search(None, "UNSEEN") #gets only the unseen emails
        ids = data[0]
        id_list = ids.split()
        latest_email_id = id_list[-1]
        r, data = mail.fetch(latest_email_id, "(RFC822)")
        raw_email = data[0][1]
        print raw_email
        mail.store(search_data[0].replace(' ',','),'+FLAGS','\Seen') #marks as read

      



Now, at least your code won't print the same email over and over. IMAP

is generally more reliable than POP3

receiving new emails quickly. However, this may take some time.

+1


source







All Articles