我尝试下载特定文件夹中未读邮件的所有附件。作为测试,我试图循环打印每条未读消息的主题行,但我只收到顶级电子邮件。请帮忙。另外,有没有办法将邮件标记为已读?
谢谢,
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
答案 0 :(得分:0)
首先,您需要遍历文件夹中的所有未读电子邮件。要完成此操作,您需要使用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对象,该对象表示指定项的所有附件。