Python Forum
Mark outlook emails as read using Python! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Mark outlook emails as read using Python! (/thread-33691.html)



Mark outlook emails as read using Python! - shane88 - May-17-2021

Good morning,

I have created the following script, which downloads unread email attachments from my outlook account. How do I then mark them as read once its downloaded?
Thank you

import win32com.client
import datetime
import os
import email

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("LGW Performance")
message = inbox.items

for message in inbox.Items:
    if message.Unread == True:
        for attachment in message.Attachments:
                        print(attachment.FileName)

            



            
            
            #attachment.SaveAsFile("C:\\Users\\shanen\\Desktop\\Python\\"+ attachment.FileName)
            

    



RE: Mark outlook emails as read using Python! - cubangt - Feb-24-2022

I know this is an old thread, but I'm running into the same question, i have similar code which is already working and downloading my files, but i have a hardcoded 5 days that i process every time i run the script which isn't very efficient. I would like to do as this post, process ONLY unread messages and once i have mark them "Read" so that next time the script runs, it only processes any new emails and not more.. This is due to weekends and vacations.. since I'm currently running this manually.


RE: Mark outlook emails as read using Python! - Pedroski55 - Feb-24-2022

Well, many moons ago I wanted to get emails from students. This was for QQ mail, but I presume outlook works similarly.

You need to activate imap login and get and imap password from the email provider, if I remember correctly.

This did the trick, the last line of the function marks the emails as seen:

#! /usr/bin/python3

import sys
import imaplib
import getpass
import email
import email.header
import base64

def read(username, password, sender_of_interest=None):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.qq.com", 993)
    imap.login(username, password)
    imap.select('INBOX')
    # Use search(), not status()
    # Print all unread messages from a certain sender of interest
    if sender_of_interest:
        status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
    else:
        status, response = imap.uid('search', None, 'UNSEEN')
    if status == 'OK':
        unread_msg_nums = response[0].split()
    else:
        unread_msg_nums = []
    data_list = []
    for e_id in unread_msg_nums:
        data_dict = {}
        e_id = e_id.decode('utf-8')
        _, response = imap.uid('fetch', e_id, '(RFC822)')
        html = response[0][1].decode('utf-8')
        email_message = email.message_from_string(html)
        data_dict['mail_to'] = email_message['To']
        data_dict['mail_subject'] = email_message['Subject']
        data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
        data_dict['body'] = email_message.get_payload()[0].get_payload()
        data_list.append(data_dict)
    print(data_list)
    #print(data_dict['body'])
    #print('The length of data_dict[body] is ' + str(len(data_dict['body'])))
    #print(email_message)
    #print('This is data_dict[body][0] ' + str(data_dict['body'][0]))
    #print('This is ' + data_dict['body'][0])
    #encoded = 
    #emailText = base64.b64decode(encoded)
    #print(emailText)
    # Mark them as seen
    for e_id in unread_msg_nums:
        imap.store(e_id, '+FLAGS', '\Seen') # mark the unreads as seen
        
    return data_dict

print('Getting the email text bodiies ... ')
emailData = read('[email protected]', 'dfennzsnagameadf')
print('Got the data!') 
saveTextPath = '/home/pedro/getEmailtexts/emailTexts/'
nameOfFile = 'firstEmailText.txt'
theFile = open(pathToFiles + nameOfFile, 'w')
print('Write text to the file ...')
theFile.write(emailData['body'])
print('Save the file ... ')
theFile.close()
Maybe this will help!