I have gotten some of the features I want but need help with 2 others.
I would like to flag the message "Mark as Done" (it's one of the Flag statuses). I have not found how to do this.
If I wanted to do this same thing for 4 other emails how would I do it, with 4 other save paths?
import win32com.client
import os
Outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inboxfolder = Outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference
inbox = inboxfolder.Items
message = inbox.GetFirst()
subject = message.Subject
sender = message.SenderEmailAddress
for m in inbox:
if m.Class == 43: # this is to make sure it is an email item and not something else.
if m.SenderEmailAddress == 'John#email.com' and m.Unread == True:
path = 'C:\\User\\Path\\Data\\John'
print ('Subject as: ' and message)
for attached in message.Attachments:
attached.SaveASFile(os.path.join(path,attached.FileName)) #Saves attachment to current folder
print (attached)
message.Unread = False
print (message.FlagStatus)
message.FlagStatus = 1 # This is to "mark as Done" but it doesn't work
message = inbox.GetNext()
elif m.SenderEmailAddress == 'Jane#email.com' and m.Unread == True:
path = 'C:\\User\\Path\\Data\\Jane'
# ... How would you add 4 more?
message = inbox.GetNext()
else:
message = inbox.GetNext()
You have to save it message.Save(), Example
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(win32com.client.constants.olFolderInbox)
for Item in Inbox.Items:
if Item.Class == 43:
Item.FlagStatus = 1
Item.Save()
For multiple emails & path use dictionary, Example
emails_with_path = {
"email#one.com": "path_one",
"email#two.com": "path_two",
"email#three.com": "path_three"
}
for m in inbox:
if m.Class == 43:
for email, path in emails_with_path.items():
if m.SenderEmailAddress == email and m.UnRead:
print(email)
print(path)
Related
I am new to python. I am trying to save all the attachment from the email without specifying the attachment name from the outlook.
We need to download the attachment with the subject name.
because attachment can come in any name and also i need to download the attachment only for past 2 days.
Could anyone help me. Below is my code
from win32com.client import Dispatch
import time
import datetime
import re
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()
sub_today = 'test4'
att_today = '20201018_2.xlsx'
#att_today = re.match(regex_, )
for msg in all_inbox:
if msg.Subject.find(sub_today) != -1 and msg.SentOn.date() == val_date:
break
for att in msg.Attachments:
if att.FileName == att_today:
print(att_today)
break
try:
print(att.FileName)
#att.SaveAsFile("C:/Users/Shwettha/Downloads/attachment/"+ att.FileName)
att.SaveAsFile(os.path.join("D:\Script\Monitoring",att.FileName))
print("SUCCESSFUL","Attachments Downloaded")
except:
print("ERROR","Attachment Download Failed")
In my outlook, I have 2 accounts(account 1 and account 2). Account 1 is the default account.
I am trying to read the email from the account 2 from the python code. I tried different approach, but it did not work.
Am posting a my code where it reads from my default account. Could you please help me to read the emails from the account 2(which is not default)
from win32com.client import Dispatch
import time
import datetime
import re
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()
sub_today = 'test4'
att_today = '20201018_2.xlsx'
#att_today = re.match(regex_, )
for msg in all_inbox:
if msg.Subject.find(sub_today) != -1 and msg.SentOn.date() == val_date:
break
for att in msg.Attachments:
if att.FileName == att_today:
print(att_today)
break
try:
print(att.FileName)
#att.SaveAsFile("C:/Users/Shwettha/Downloads/attachment/"+ att.FileName)
att.SaveAsFile(os.path.join("D:\Script\Monitoring",att.FileName))
print("SUCCESSFUL","Attachments Downloaded")
except:
print("ERROR","Attachment Download Failed")
Try setting your inbox like the following
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders["0m3r#Email.com"].Folders["Inbox"]
Or use GetSharedDefaultFolder method (Outlook)
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Recip = olNs.CreateRecipient("0m3r#Email.com")
Recip.Resolve()
shared_inbox = olNs.GetSharedDefaultFolder(Recip, "6")
for Item in shared_inbox.Items:
print(Item.Subject)
I am trying to download attachments from Outlook using Python, as of now am able to download the attachments by subject line but in my case I want to download multiple attachments from multiple emails where subject line starts with some string, For Ex:
Subjects are: Query 123654, Query 56975, Query 5698 like this and I want to download all of them where subject name starts with "Query".
My current code is below:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()
sub_today = 'Query 123654'
att_today = ''
for msg in all_inbox:
if msg.Subject == sub_today and msg.Senton.date() == val_date:
break
for att in msg.Attachments:
if att.FileName == att_today:
break
try:
att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
messagebox.showerror("ERROR","Attachment Download Failed")
You could use find() to search specific data.
sub_today = 'Query'
if msg.Subject.find(sub_today) != -1 break
If subject not include “Query”, it will return “-1”.
This is the complete code:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()
sub_today = 'Query'
att_today = ''
for msg in all_inbox:
if msg.Subject.find(sub_today) != -1 and msg.Senton.date() == val_date:
break
for att in msg.Attachments:
if att.FileName == att_today:
break
try:
att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
messagebox.showerror("ERROR","Attachment Download Failed")
For more information, please refer to this link:
Python String find() Method
I'm trying to get a python script which looks through my gmail inbox using imap and prints out the subject and sender of any emails which are unseen. I've started but at the moment I don't think it can sort the unseen emails or extract from these the subject and sender.
Does anyone know how to finish this code?
import imaplib
import email
user = "x"
password = "y"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user, password)
mail.list()
mail.select('inbox')
unseen_emails = mail.search(None, 'UnSeen')
print unseen_emails
If you were willing to use poplib, this should work.
import poplib
mymail = []
host = "pop.gmail.com"
mail = poplib.POP3_SSL(host)
print (mail.getwelcome())
print (mail.user("user#gmail.com"))
print (mail.pass_("password"))
print (mail.stat())
print (mail.list())
print ("")
if mail.stat()[1] > 0:
print ("You have new mail.")
else:
print ("No new mail.")
print ("")
numMessages = len(mail.list()[1])
numb=0
for i in range(numMessages):
for j in mail.retr(i+1)[1]:
numb+=1
if numb == 4 or numb == 5:
print(j)
mail.quit()
input("Press any key to continue.")
Just be sure to allow less secure apps in your google account here: https://myaccount.google.com/lesssecureapps
My external lib https://github.com/ikvk/imap_tools
from imap_tools import MailBox, AND
# get list of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test#mail.com', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch(AND(seen=False)):
msg.subject # str: 'some subject 你 привет'
msg.from_ # str: 'Sender#ya.ru'
NOTE: mailbox.fetch has mark_seen arg!
I am hitting a road block with exporting outlook messages as .msg files. I'm not sure on how to accomplish this task. I have a program that currently reads the email and exports the attachments and once it completes it moves the message to a processed folder so I can keep track of what has been completed. I need to add a function that exports the entire email itself to a folder on the local machine. Has anyone accomplished this using pywin32.client?
Here is the program as it stands now. (excuse the mess its still in progress)
import os
import win32com.client
import csv
import datetime
from random import randint
ATTACHMENTS_FOLDER = "C:\\EMAILS"
LOG_PATH = 'C:\\EMAILS\\log.csv'
COUNTER = 1
SUBFOLDER_LIST = ["TEST"]
UPLOAD_LIST = 'C:\\EMAILS\\logupload%d.csv' % randint(2,150000)
def ExportMessages (Folder, item):
#No IDEA!
pass
def process_attachment(sender, subject, attachment, messagedate):
"""
:param sender:
:param subject:
:param attachment:
:param messagedate:
"""
global count
count = 0
try:
filepath = os.path.join(ATTACHMENTS_FOLDER, "RAN-%dSEN-%sSUB-%s%s" % (randint(2,100000),str(sender), str(subject), attachment))
count = count +1
print "Trying", filepath
open(filepath, "r")
os.remove(filepath)
except IOError:
pass
try:
attachment.SaveAsFile(filepath)
row = [messagedate, sender, subject, count]
row2 = [messagedate, sender, subject, filepath]
w = csv.writer(csv_file)
w2 = csv.writer(csv_file2)
w.writerow(row)
w2.writerow(row2)
except:
pass
def move_message_fail(message, folder):
"""
:param message:
:param folder:
"""
print "Moving:", message.Subject
proc_folder = folder.Folders("Failed")
message.Move(proc_folder)
def move_message(folder, message):
"""
:param folder:
:param message:
"""
print "Moving:", message.Subject
proc_folder = folder.Folders("Processed")
message.Move(proc_folder)
def process_message(message, folder):
"""
:param message:
:param folder:
"""
global vin_num
vin_num = ''
print "Message:", message.Subject
vin = message.Subject
sender = message.SenderName
if folder == SUBFOLDER_LIST[0]:
for i in vin.split(' '):
if '-' in i:
vin_num = i
if vin_num:
now = datetime.datetime.now()
messagedate = now.strftime("%m-%d-%Y")
attachments = message.Attachments
for n_attachment in range(attachments.Count):
attachment = attachments.Item(n_attachment + 1)
#if attachment.Type == win32com.client.constants.CdoFileData:
process_attachment(sender, vin_num, attachment, messagedate)
#message.Update()
move_message(folder, message, up_folder)
else:
move_message_fail(message, folder)
else:
vin_num = vin.split(' ')[1]
now = datetime.datetime.now()
messagedate = now.strftime("%m-%d-%Y")
attachments = message.Attachments
for n_attachment in range(attachments.Count):
attachment = attachments.Item(n_attachment + 1)
#if attachment.Type == win32com.client.constants.CdoFileData:
process_attachment(sender, vin_num, attachment, messagedate)
#message.Update()
move_message(folder, message, up_folder)
if __name__ == '__main__':
csv_file = open(LOG_PATH, "ab")
csv_file2 = open(UPLOAD_LIST, "wb")
for i in SUBFOLDER_LIST:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
one_folder = outlook.Folders(1)
two_folder = one_folder.Folders("Inbox")
three_folder = two_folder.Folders(i)
messages = three_folder.Items
message = messages.GetFirst()
while message:
process_message(message, i)
ExportMessages(three_folder, message)
message = messages.GetNext()
Call MailItem.SaveAs and pass olMsg or olMsgUnicode as the second (Format) parameter.