0

I'm working on a code in python, which should search all the email-addresses in a csv-file (they're saved with their passwords) for a specifig subject. Everything works fine, but if i put a specifig subject to the search, i get a big problem.

This is the line:

type, data = mail.search(None, '(UNSEEN) (TEXT example)')

if i delete (TEXT example), it works, but i want to search only emails with this subject...

I found a code which seeked emails with a specific subject, but i want to use the automatic data-using from the csv file, too and i didnt solve the problem to combine these features.. :(

///// START CODE:

import email
import imaplib
import csv
import smtpd
import time




smtp_server = 'imap.arcor.de'
smtp_port = 993



def acccheck():
    with open('pipi.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=';')
        for row in csv_reader:

            readmail(row[0], row[1])
            print(row[0], row[1])


def readmail(username, password):

    try:
        mail = imaplib.IMAP4_SSL(smtp_server)
        mail.login(username, password)

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

        for i in reversed(id_list):
            type, data = mail.fetch(i, '(RFC822)')

            for response_part in data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1].decode('utf-8', errors='ignore'))
                    email_subject = msg['subject']
                    email_from = msg['from']
                    print('From: ' + email_from)
                    print('Subject: ' + email_subject + '\n')


    except Exception as e:
        print('ERROR: ' + str(e))



acccheck()

END CODE ////

ERROR:

ERROR: FETCH command error: BAD [b"Error in IMAP command FETCH: Unexpected ')' (0.001 + 0.000 secs)."] email_1 pw_1 ERROR: FETCH command error: BAD [b"Error in IMAP command FETCH: Unexpected ')' (0.001 + 0.000 secs)."] email_2 pw_2 ERROR: FETCH command error: BAD [b"Error in IMAP command FETCH: Unexpected ')' (0.001 + 0.000 secs)."] email_3 pw_3

1 Answers1

0

Try this:

resp, data = mail.uid('search', None, 'X-GM-RAW', r'"subject:{}"'.format(search_term))
mail_ids = data[0]
id_list = mail_ids.split()
for ID in id_list:
  typ, mail_stuff = mail.uid('fetch', ID, '(RFC822)')

kalidurge
  • 279
  • 2
  • 11