[英]How do I download attachments from unread emails in Outlook 2013?
我正在嘗試將未讀郵件的所有附件下載到特定文件夾中。 作為測試,我嘗試循環打印每條未讀郵件的主題行,但只得到頂部電子郵件。 請幫忙。 另外,有沒有辦法將郵件標記為已讀?
謝謝,
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
首先,您需要遍歷文件夾中所有未讀的電子郵件。 為此,您需要使用Items類的Find
/ FindNext
或Restrict
方法。 您可以閱讀有關這些方法的更多信息,並在以下文章中找到示例代碼:
例如,在C#中,它將看起來像下面列出的代碼:
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);
}
若要保存附件,您需要使用Attachment類的SaveAsFile方法。 MailItem類的Attachments屬性返回一個Attachments對象,該對象表示指定項目的所有附件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.