Python read email subject

Let me start by saying that I don’t speak English and I use a translator. I hope you will understand what I write.
I have python code (I put it together from a few examples from the Internet) to read emails from a particular sender, but unfortunately it can only read one new email. If there is more then an error pops up. Can anyone point out a solution to this problem then I would appreciate it.

import imaplib
import email
import subprocess
#import time


Alarm_Wlaczony = ["Alarmon"]
Alarm_Wylaczony = ["Alarmoff"]
Lampa_Wlaczona = ["Lampaon"]
Lampa_Wylaczona = ["Lampaoff"]

#temat = (msg['subject'])

if __name__ == '__main__':
    email_user = "login1@tlen.pl"
    email_pass = "1234"
    mail = imaplib.IMAP4_SSL("poczta.o2.pl", 993)
    mail.login(email_user, email_pass)
    mail.select()
    type, data = mail.search(None, '(UNSEEN)', '(FROM "login2@tlen.pl")')
    mail_ids = data[0].decode('utf-8')
    id_list = mail_ids.split()
    mail.select('INBOX')  # z tym dziala
    for i in id_list:
        typ, msg_data = mail.fetch(str(i), '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])
                #print(msg['from']+"\t"+msg['subject'])
                print(msg['subject'])
                mail.store(mail_ids, '+FLAGS', '\Seen')
                if msg['subject'] in (Alarm_Wlaczony):
                    #subprocess.run("/home/pi/Alarm/Alarm_on.sh")
                    print("Alarm Wlaczony")
                elif msg['subject'] in (Alarm_Wylaczony):
                    #subprocess.run("/home/pi/Alarm/Alarm_off.sh")
                    print("Alarm Wylaczony")
                elif msg['subject'] in (Lampa_Wlaczona):
                    #subprocess.run("/home/pi/Przekazniki/dwa_przekazniki_on.py")
                    print("Lampa Wlaczona")
                elif msg['subject'] in (Lampa_Wylaczona):
                    #subprocess.run("/home/pi/Przekazniki/dwa_przekazniki_off.py")
                    print("Lampa Wylaczona")

                #mail.store(mail_ids, '+FLAGS', '\Seen')

when there is one unread e-mail

==>> python Sterowanie_mailem.py 
Alarmon
Alarm Wlaczony

when there is several unread e-mails

==>> python Sterowanie_mailem.py 
Lampaon
Traceback (most recent call last):
  File "/home/wiini2/Dokumenty/Raspberry/Skrypty_z_malinki_2/Mail_python/Sterowanie_mailem.py", line 35, in <module>
    mail.store(mail_ids, '+FLAGS', '\Seen')
  File "/usr/lib/python3.10/imaplib.py", line 851, in store
    typ, dat = self._simple_command('STORE', message_set, command, flags)
  File "/usr/lib/python3.10/imaplib.py", line 1230, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python3.10/imaplib.py", line 1055, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Bad message data item (MARKER:c19r688630qcqlkiq0en)']

This is unfortunately beyond my capabilities.

The purpose of this script is to be able to control the Raspberry Pi with emails

1 Like

Now it works, maybe it will be useful to someone.
:slightly_smiling_face:

import imaplib
import email
import subprocess

Alarm_Wlaczony = ["Wlacz"]
Alarm_Wylaczony = ["Wylacz"]
Lampa_Wlaczona = ["Lampaon"]
Lampa_Wylaczona = ["Lampaoff"]

if __name__ == '__main__':
    email_user = "login1@tlen.pl"
    email_pass = "1234"
    mail = imaplib.IMAP4_SSL("poczta.o2.pl", 993)
    mail.login(email_user, email_pass)
    mail.select()
    type, data = mail.search(None, '(UNSEEN)', '(FROM "login2@tlen.pl")')
    mail_ids = data[0].decode('utf-8')
    id_list = mail_ids.split()
    mail.select('INBOX')  # z tym dziala
    ilosc = len(data[0].split())
    for i in id_list:
        typ, msg_data = mail.fetch(str(i), '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])
                print(msg['subject'])
                if msg['subject'] in (Alarm_Wlaczony):
                    #subprocess.run("/home/pi/Alarm/Alarm_on.sh")   
                    print ("Wlaczam Alarm")
                elif msg['subject'] in (Alarm_Wylaczony):
					#subprocess.run("/home/pi/Alarm/Alarm_off.sh")
                    print ("Wylaczam Alarm")
                elif msg['subject'] in (Lampa_Wlaczona):
					#subprocess.run("/home/pi/Przekazniki/dwa_przekazniki_on.py")
                    print ("Wlaczam Lampe")
                elif msg['subject'] in (Lampa_Wylaczona):
					#subprocess.run("/home/pi/Przekazniki/dwa_przekazniki_off.py")
                    print ("Wylaczylem Lampe")

    if ilosc==0:
       exit()
    else:
       mail.store(data[0].decode('utf-8').replace(' ',','), '+FLAGS', r'\Seen')
2 Likes