2015-08-03 76 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(); 
          } 

       } 

希望幫助別人