Пример #1
0
def copy(uid: str, con: imaplib.IMAP4_SSL) -> Optional[bool]:
    try:
        con.create('ARCHIVE')
        con.select('INBOX')
        status, data = con.uid('COPY', uid, 'ARCHIVE')
        return status == 'OK'
    except Exception as error:
        logging.error(error)
Пример #2
0
def load(con: imaplib.IMAP4_SSL) -> Optional[dict]:
    try:
        con.select('INBOX')
        status, data = con.uid('SEARCH', None, 'ALL')
        if status == 'OK':
            uids = data[0].split()
            msgs = dict()
            for uid in uids:
                status, data = con.uid('FETCH', uid, '(RFC822)')
                if status == 'OK':
                    msg = email.message_from_bytes(data[0][1])
                    msgs[uid] = msg
            return msgs
    except Exception as error:
        logging.error(error)
Пример #3
0
def get_latest_email(imap_session: imaplib.IMAP4_SSL) -> Message:
    status, messages = imap_session.select("Matt")
    latest_email_id = int(messages[0])
    logging.info("Fetching latest email")
    res, message = imap_session.fetch(str(latest_email_id), "(RFC822)")

    for response in message:
        if isinstance(response, tuple):
            return email.message_from_bytes(response[1])
    def imapConnection(self):
        # Connexion au serveur IMAP
        try:
            imap = IMAP(self.imap_host)
            print(
                '\nConnection to IMAP server intitialization of IMAP instance\n'
            )
            imap.login(self.imap_user, self.imap_pass)
            print('Log in !\n')
            imap.select('INBOX')
            self.deleteMails(imap)

            return imap
        except gaierror:
            print('Can\'t reach IMAP server\n')
        except IMAP.error as e:
            print('Log in failed.\n')
            print(str(e) + '\n')
def loop():
    server = IMAP(HOST, 993)
    server.login(USER, PWD)
    server.select(FOLDER, readonly=True)
    status, folder_status = server.status(FOLDER, "(UNSEEN)")
    print(status)
    print(folder_status)
    match = re.search("UNSEEN (\d+)",
                      folder_status[0].decode(encoding="UTF-8"))
    print(match.group(0))
    print(match.group(1))
    if (match.group(1) == 1):
        print("You have mail!")
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        print("No unread mail")
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)
Пример #6
0
def loop():
    server = IMAP(HOSTNAME, 993)
    server.login(USERNAME, PASSWORD)
    server.select(MAILBOX, readonly=True)
    result, folder_status = server.status(MAILBOX, '(UNSEEN)')
    #print(folder_status)
    m = re.search('UNSEEN (\d+)', folder_status[0].decode(encoding='UTF-8'))
    #print(m.group(0))
    #print(m.group(1))

    print("You have " + m.group(1) + " unread emails.")
    if (int(m.group(1)) > 0):
        GPIO.output(outpin1, True)
        GPIO.output(outpin2, False)
    else:
        GPIO.output(outpin1, False)
        GPIO.output(outpin2, True)

    time.sleep(3)
    def _check_sent(self, verbose: bool, imap: IMAP4_SSL, timeout: int,
                    uid_to_from_address: Dict[uuid.UUID, str]) -> None:
        handle_response("select INBOX", imap.select())

        end = time.time() + timeout
        while True:
            if time.time() > end:
                # We sort the addresses to get a stable output.
                unresponsive = ", ".join(
                    uid for uid in sorted(uid_to_from_address.values()))
                raise CommandError("timeout; did not get answers for "
                                   f"{unresponsive}")
            remaining_uids = {}

            # Sending a noop prompts some IMAP servers to *really* check
            # whether there have been new emails delivered. Without it, it
            # takes longer for us to find the emails we are looking for.
            handle_response("noop", imap.noop())

            # It may be possible to reduce the number of queries to the IMAP
            # server by ORing the SUBJECT queries. However, it complicates the
            # code quite a bit.
            for uid, from_address in uid_to_from_address.items():
                if verbose:
                    self.stdout.write(f"Searching for: {uid} from "
                                      f"{from_address}...")
                mess_uid = \
                    handle_response("search",
                                    imap.uid(
                                        "search",
                                        f'SUBJECT "{uid}" '  # type: ignore
                                        f'FROM "{from_address}"'))
                if mess_uid[0] == b"":
                    remaining_uids[uid] = from_address
                else:
                    if verbose:
                        self.stdout.write(f"Found {uid}!")
                    answer = handle_response(
                        "store",
                        imap.uid(
                            "store",
                            mess_uid[0],
                            "+FLAGS",  # type: ignore
                            r"(\Deleted \Seen)"  # type: ignore
                        ))
                    if verbose:
                        self.stdout.write(repr(answer))

            if len(remaining_uids) == 0:
                break

            uid_to_from_address = remaining_uids
            # Give a bit of respite to the IMAP server.
            time.sleep(1)
Пример #8
0
def searchFolder(imapServer: imaplib.IMAP4_SSL, searchQuery, type, folder):
    imapServer.select(folder)

    searchResult = imapServer.search(searchQuery, type)
    ids = searchResult[1][0].decode("utf-8").split()
    foundMessages = []
    for i in ids:
        emailData = imapServer.fetch(str(i), '(RFC822)')
        print("=======================================")
        for response_content in emailData:
            arr = response_content[0]
            if isinstance(arr, tuple):
                msg = email.message_from_string(str(arr[1], 'utf-8'))
                foundMessages.append({
                    "From": msg['From'],
                    "Subject": msg['Subject'],
                    "Date": msg["Date"],
                    "Message-ID": msg["Message-ID"]
                })
                imapServer.store(str(i), '-FLAGS', '\Flagged')
    return foundMessages
Пример #9
0
def gen_unseen_mbank_emails(
    database: KsiemgowyDB, mail: imaplib.IMAP4_SSL, imap_filter: str
) -> T.Iterator[Message]:
    """Connects to imap_server using login and password from the arguments,
    then yields a pair (mail_id_as_str, email_as_eml_string) for each of
    e-mails coming from mBank."""
    mail.select("inbox")
    _, data = mail.search(None, imap_filter)
    mail_ids = data[0]
    id_list = mail_ids.split()
    for mail_id in reversed(id_list):
        _, data = mail.fetch(mail_id, "(RFC822)")
        for mail_number, response_part in enumerate(data):
            if not isinstance(response_part, tuple):
                continue
            msg = email.message_from_string(response_part[1].decode())
            mail_key = f'{msg["Date"]}_{mail_number}'
            if database.was_imap_id_already_handled(mail_key):
                continue
            LOGGER.info("Handling e-mail id: %r", mail_id)
            yield msg
            database.mark_imap_id_already_handled(mail_key)
Пример #10
0
def find_timepie_attachments(
    imap: imaplib.IMAP4_SSL,
    should_ignore_msg: t.Callable[[MsgId], bool],
    sender: str,
    is_gmail: bool = False,
) -> t.Mapping[MsgId, t.Sequence[Ping]]:

    status: t.Any
    details: t.Any

    status, details = imap.select('INBOX')
    if status != 'OK':
        raise RuntimeError(f'select failed: {details}')

    query = (_build_gmail_query(sender)
             if is_gmail else f'HEADER FROM {json.dumps(sender)}')
    status, details = imap.search(None, query)
    if status != 'OK':
        raise RuntimeError(f'bad status on search: {status}')
    msg_ids = set(details[0].decode('utf-8').split(' '))
    logger.debug(f'pre-filter msg_ids = {msg_ids}')

    msg_ids = {m for m in msg_ids if not should_ignore_msg(m)}
    logger.debug(f'post-filter msg_ids = {msg_ids}')

    result = {}
    for msg_id in sorted(msg_ids):
        logger.info(f'fetching msg {msg_ids}')

        msg_info: t.Any
        status, msg_info = imap.fetch(msg_id, '(RFC822)')
        if status != 'OK':
            raise RuntimeError(f'bad status on fetch: {status}')
        msg = email.message_from_bytes(msg_info[0][1])
        try:
            result[msg_id] = _find_timepie_part(msg)
        except ValueError:
            logger.info(f'msg {msg_id} has no timepie part')
            continue

    return result