Python Forum
Mark outlook emails as read using Python!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mark outlook emails as read using Python!
#1
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)
            

    
Reply
#2
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.
Reply
#3
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Outlook Inbox for set of values cubangt 1 975 Jun-28-2023, 09:29 PM
Last Post: cubangt
  Save image from outlook email cubangt 1 648 Jun-07-2023, 06:52 PM
Last Post: cubangt
  [Solved]Help Displaying Emails properly via Python Extra 5 1,126 Sep-28-2022, 09:28 PM
Last Post: deanhystad
  Read All Emails from Outlook and add the word counts to a DataFrame sanaman_2000 0 1,818 Sep-15-2022, 07:32 AM
Last Post: sanaman_2000
  Sending Emails on Autopilot Gyga_Hawk 3 1,627 Mar-15-2022, 08:20 AM
Last Post: Larz60+
  Doctesting a function which prints a students name along with the maximum mark scored sean1 5 2,220 Feb-01-2022, 12:20 PM
Last Post: Pedroski55
  Trying out the parsing/reading of emails from my outlook cubangt 0 6,053 Jan-12-2022, 08:59 PM
Last Post: cubangt
  Help Needed | Read Outlook email Recursively & download attachment Vinci141 1 4,018 Jan-07-2022, 07:38 PM
Last Post: cubangt
  Need Outlook send email code using python srikanthpython 3 8,092 Feb-28-2021, 01:53 PM
Last Post: asyswow64
  Something wrong with the quotation mark in dictionary definition Mark17 1 1,958 Jan-29-2021, 03:34 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020