2015-08-03 53 views
2

我使用控制台应用程序使用IMAP服务从邮件中下载文档。我在IMAP的应用程序中使用“S22.Imap”程序集。我收到了包含IEnumerable中附加文件的所有邮件。我怎样才能下载这些文件?如何使用IMAP从C#下载gmail的附件?

using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true)) 
     { 
      IEnumerable<uint> uids = client.Search(SearchCondition.Subject("Attachments")); 
      IEnumerable<MailMessage> messages = client.GetMessages(uids, 
       (Bodypart part) => 
       { 
        if (part.Disposition.Type == ContentDispositionType.Attachment) 
        { 
         if (part.Type == ContentType.Application && 
          part.Subtype == "VND.MS-EXCEL") 
         { 
          return true; 
         } 
         else 
         { 
          return false; 
         } 
        } 
        return true; 
       } 
      ); 
     } 

enter image description here

我将不胜感激,如果你给一个解决方案

+1

的截图,扩大基地,而你应该得到[ContentStream(https://msdn.microsoft.com/en-us/library/System.Net.Mail。附件%28v = vs.110%29.aspx) – Martheen

回答

5

附件类型上有一个名为ContentStream的属性,您可以在msdn文档中看到此内容:https://msdn.microsoft.com/en-us/library/system.net.mail.attachment(v=vs.110).aspx

使用,你可以使用这样的事情,然后保存文件:编辑

using (var fileStream = File.Create("C:\\Folder")) 
{ 
    part.ContentStream.Seek(0, SeekOrigin.Begin); 
    part.ContentStream.CopyTo(fileStream); 
} 

GetMessages完成后 所以,你可以这样做:

foreach(var msg in messages) 
{ 
    foreach (var attachment in msg.Attachments) 
    { 
     using (var fileStream = File.Create("C:\\Folder")) 
     { 
      attachment.ContentStream.Seek(0, SeekOrigin.Begin); 
      attachment.ContentStream.CopyTo(fileStream); 
     } 
    } 
} 
0
messages.Attachments.Download(); 
messages.Attachments.Save("location", fileSaveName) 

这样你可以使用IMAP下载电子邮件中的附件

0

此代码将存储att下载文件夹中的c驱动器内的achment文件。

foreach (var msg in messages) 

         { 
          foreach (var attachment in msg.Attachments) 
          { 

           byte[] allBytes = new byte[attachment.ContentStream.Length]; 
           int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length); 

           string destinationFile = @"C:\Download\" + attachment.Name; 

           BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); 
           writer.Write(allBytes); 
           writer.Close(); 
          } 

       } 

希望帮助别人

相关问题