'How to get mapi to loop through the body in the email's file attachment
I am trying to get my code to loop through the file attachment's body in the particular subfolder such that if certain word exists in the file attachment's body, the email's body will be read.
Currently, I only know how to read the email's body using:
import win32com.client
outlook=win32com.client.Dispatch('outlook.application')
mapi=outlook.GetNamespace("MAPI")
inbox=mapi.GetDefaultFolder(6).Folders['Email']
messages=inbox.Items
for message in messages:
body = message.body
but when it comes to reading the file attachment's body without saving all the file attachments one by one, I am stuck.
Solution 1:[1]
You can use the Table object which represents a set of item data from a Folder or Search object, with items as rows of the table and properties as columns of the table. Use Folder.GetTable to obtain a Table object that represents a set of items in a folder or search folder. If the Table object is obtained from Folder.GetTable, you can further specify a filter (in Table.Restrict) to obtain a subset of the items in the folder. If you don't specify any filter, you'll obtain all the items in the folder.
The following sample code sample uses a DAV Searching and Locating (DASL) syntax to specify a query. To construct the filter, the code sample first checks whether Instant Search is enabled in the default store to determine whether to use the ci_phrasematch keyword for an exact phrase match to "office" in any attachment. The sample then applies the filter to the GetTable method on the Inbox and obtains the results in a Table object. The code sample then displays the subject of each of the returned items in the Table. The following sample is in C#, but the Outlook object model is common for all kind of applications, so there shouldn't be a problem in understand the approach described:
using Outlook = Microsoft.Office.Interop.Outlook;
private void DemoSearchAttachments()
{
string filter;
const string PR_SEARCH_ATTACHMENTS =
"http://schemas.microsoft.com/mapi/proptag/0x0EA5001E";
if (Application.Session.DefaultStore.IsInstantSearchEnabled)
{
filter = "@SQL=" + "\""
+ PR_SEARCH_ATTACHMENTS + "\""
+ " ci_phrasematch 'office'";
Outlook.Table table = Application.Session.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderInbox).GetTable(
filter, Outlook.OlTableContents.olUserItems);
while (!table.EndOfTable)
{
Outlook.Row row = table.GetNextRow();
Debug.WriteLine(row["Subject"]);
// or
// Debug.WriteLine(row["Body"]);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eugene Astafiev |
