Reputation: 13
I am trying to create a code that will find letters in my mailbox using Subject field (according Outlook rules this letters will be located in folder 'TODO' for example). That's what I have for now:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("TODO")
messages = inbox.Items
message = messages.GetLast()
body_content = message.subject
print(body_content)
This code finds the last letter at the folder.
Thank you in advance.
Upvotes: 0
Views: 5378
Reputation: 49395
You need to use the Find/FindNext or Restrict methods of the Items
class. For example, to get items with Hello world
subject line you can to use the following code:
private void FindAllUnreadEmails(Outlook.MAPIFolder folder)
{
string searchCriteria = "[Subject] = `Hello world`";
StringBuilder strBuilder = null;
int counter = default(int);
Outlook._MailItem mail = null;
Outlook.Items folderItems = null;
object resultItem = null;
try
{
if (folder.UnReadItemCount > 0)
{
strBuilder = new StringBuilder();
folderItems = folder.Items;
resultItem = folderItems.Find(searchCriteria);
while (resultItem != null)
{
if (resultItem is Outlook._MailItem)
{
counter++;
mail = resultItem as Outlook._MailItem;
strBuilder.AppendLine("#" + counter.ToString() +
"\tSubject: " + mail.Subject);
}
Marshal.ReleaseComObject(resultItem);
resultItem = folderItems.FindNext();
}
if (strBuilder != null)
Debug.WriteLine(strBuilder.ToString());
}
else
Debug.WriteLine("There is no match in the "
+ folder.Name + " folder.");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (folderItems != null) Marshal.ReleaseComObject(folderItems);
}
}
Read more about these methods in the following articles:
Also, you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch
method in Outlook are:
Read more about this method in the Advanced search in Outlook programmatically: C#, VB.NET article.
Upvotes: 1
Reputation: 113
The below code will search in all the messages of TODO folder and if the subject matches with the String to be searched, it will print found message
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("TODO")
messages = inbox.Items
for message in messages:
if message.subject == 'String To be Searched':
print("Found message")
Upvotes: 2