如何使用IMAP从C#格式的gmail下载附件?
我使用一个控制台应用程序,使用IMAP服务从邮件下载文档。我在Imap应用程序中使用“S22.Imap”程序集。我得到的所有邮件都包含IEnumerable中的附件。我如何下载这些文件如何使用IMAP从C#格式的gmail下载附件?,c#,.net,imap,C#,.net,Imap,我使用一个控制台应用程序,使用IMAP服务从邮件下载文档。我在Imap应用程序中使用“S22.Imap”程序集。我得到的所有邮件都包含IEnumerable中的附件。我如何下载这些文件 using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true)) { IEnumerable<uint> uids = cl
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;
}
);
}
使用(ImapClient client=new ImapClient(主机名,993,用户名,密码,AuthMethod.Login,true))
{
IEnumerable uids=client.Search(SearchCondition.Subject(“附件”);
IEnumerable messages=client.GetMessages(UID,
(车身部件)=>
{
if(part.Disposition.Type==ContentDispositionType.Attachment)
{
if(part.Type==ContentType.Application&&
part.Subtype==“VND.MS-EXCEL”)
{
返回true;
}
其他的
{
返回false;
}
}
返回true;
}
);
}
如果您能提供解决方案,我将不胜感激我认为最好的来源是文档请参阅此链接是关于从电子邮件下载附件的
附件类型有一个名为
ContentStream的属性。您可以在msdn文档中看到此属性:
使用该选项,您可以使用类似以下内容来保存文件:
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);
}
}
}
通过这种方式,您可以使用IMAP下载电子邮件中的附件。此代码将附件文件存储在下载文件夹中的c驱动器中
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();
}
}
希望能对某人有所帮助的确如此。OP应该检查示例,就像OP询问使用IMAP和特定库一样。你发布的链接是关于POPAt的,在屏幕截图上,展开Base,你应该可以
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();
}
}