Python: How do I check email with a loop without there being a message in the inbox?

StackOverflow https://stackoverflow.com/questions/5315537

  •  24-10-2019
  •  | 
  •  

سؤال

import serial
import imaplib
from time import sleep

IMAP_SERVER='imap.gmail.com'
IMAP_PORT=993
ser= serial.Serial ('/dev/ttyACM0',9600)

M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
rc, resp = M.login('user@gmail.com', 'password')
print rc, resp

while True: 
    M.select()
    for msg_num in M.search("INBOX", "UNDELETED")[1][0].split():
        msg = M.fetch('1', '(BODY.PEEK[TEXT])') 
        String = msg[1][0][1][139:161]
        print String
        if String == "This is just a test...":
            ser.write('0')
    sleep(1)

I'm a new beginner in python programming and the above python code is one that I'm using for a program I want to do. When I run this in a terminal I get the response that I have authenticated my account and then it displays the message between characters 139 & 161, which is the following in the example email:

This is just a test...

This is printed out in the terminal. If I delete the message in my inbox this comes out:

String = msg[1][0][1][139:161]
TypeError: 'NoneType' object is unsubscriptable

I believe that this is due to that I don't have any messages in the inbox. Now what I want to do is that if there are no messages to run again and again until a message shows up in my inbox & do an according action pending on the message

هل كانت مفيدة؟

المحلول

A quick and dirty fix is to catch the TypeError. Something like this:

try:
    String = msg[1][0][1][139:161]
except TypeError:
    continue

That said, this could stand to be improved. For one thing, you can use

if 'This is just a test...' in String:
    # ...

instead of slicing your message body to bits and relying on exact placement. You might also want to confirm that msg[1][0] is the body tuple, or iterate through the items in msg until you find it.

You may also be interested in reading PEP 8. Others are more likely to be able to quickly read your code if you stick to it when you can.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top