我正在尝试从存储在Gmail收件箱中的电子邮件下载电子邮件附件。使用S22.Imap lib(https://github.com/smiley22/S22.Imap)我获取消息列表,然后迭代它们以下载附件。我遇到的问题是MailMessage.Attachments.Count始终为0,即使附加了文件也是如此。这是我下载附件的代码。
foreach (MailMessage m in messages)
{
if(m.Subject.Contains("Activity Statement") && (m.Attachments.Count > 0))
{
foreach (Attachment a in m.Attachments)
{
var fileStream = File.Create(Properties.Settings.Default.ETL_ATTACHMENT_PROCESSING_DIR + a.Name);
a.ContentStream.Seek(0, SeekOrigin.Begin);
a.ContentStream.CopyTo(fileStream);
fileStream.Close();
}
}
}
答案 0 :(得分:0)
你去.. Net.Mail.Attachment.ContentStream
会给你一个你可以复制到文件的流。要检查尺寸,请使用ContentStream.Length
foreach (Attachment attachment in message.Attachments)
{
byte[] allBytes = new byte[attachment.ContentStream.Length];
int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);
string destinationFile = @"C:\\Path\\" + attachment.Name;
BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
writer.Write(allBytes);
writer.Close();
}