简体   繁体   中英

How do I download attachments from unread emails in Outlook 2013?

I'm trying to download all of the attachments of the unread messages in a specific folder. As a test, I tried to loop print the subject line of each unread message, but am only getting the top email's. Please help. Also, is there a way to mark the message as read?

Thanks,

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('The Machine').Folders('Delivered Assets').Folders('Daily')
messages = inbox.Items
message = messages.GetLast()
attachments = message.Attachments
attachment = attachments.Item(1)
#attachment.SaveAsFile('C:\\temp\\' + attachment.FileName) #this downloads the attachment to specified path

for item in messages: 
    if item.Unread==True:
        print message.Subject #this only prints the top email's subject

First of all, you need to iterate over all unread emails in the folder. To get this done you need to use the Find / FindNext or Restrict methods of the Items class. You can read more about these methods and find the sample code in the following articles:

For example, in C# it will look like the code listed below:

string restrictCriteria = "[UnRead] = true";
StringBuilder strBuilder = null;
Outlook.Items folderItems = null;
Outlook.Items resultItems = null;
Outlook._MailItem mail = null;
int counter = default(int);
object item = null;
try
{
    strBuilder = new StringBuilder();
    folderItems = folder.Items;
    resultItems = folderItems.Restrict(restrictCriteria);
    item = resultItems.GetFirst();
    while (item != null)
    {
        if (item is Outlook._MailItem)
        {
            counter++;
            mail = item as Outlook._MailItem;
            strBuilder.AppendLine("#" + counter.ToString() +
                               "\tSubject: " + mail.Subject);
        }
        Marshal.ReleaseComObject(item);
        item = resultItems.GetNext();
    }
    if (strBuilder.Length > 0)
        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);
    if (resultItems != null) Marshal.ReleaseComObject(resultItems);
}

To save the attached file you need to use the SaveAsFile method of the Attachment class. The Attachments property of the MailItem class returns an Attachments object that represents all the attachments for the specified item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM