Reputation: 1
I used this code to download the PDF file from attachment. And when I connecting to gmail IMAP it's working great. But when I try to connect another IMAP server DecodeToAsync just can't decode it to MemoryStream. In debug I can see that mimePart.Content.Stream has value. What could be the reason? The code below:
public async Task<EmailFileInfo> GetFileAsync(string messageId, string fileId, string fileName, string folderId = null)
{
using var client = await ConnectToImapServerAsync();
var currentFolder = await GetFolderAsync(client, folderId);
await currentFolder.OpenAsync(FolderAccess.ReadWrite);
if (!int.TryParse(messageId, out int parsedMessageId))
{
return null;
}
var message = await currentFolder.GetMessageAsync(parsedMessageId);
var mimePart = GetMessageAttachmentFilter(message, fileId, fileName);
if (mimePart is null)
{
return null;
}
using MemoryStream memoryStream = new MemoryStream();
await mimePart.Content.DecodeToAsync(memoryStream);
return new EmailFileInfo { Name = mimePart.FileName, ContentType = mimePart.ContentType.MimeType, Stream = memoryStream };
}
private MimePart GetMessageAttachmentFilter(MimeMessage message, string fileId, string fileName)
{
foreach (var attachment in message.Attachments)
{
var mimePart = (MimePart)attachment;
if (mimePart.ContentId == fileId || mimePart.FileName == fileName)
{
return mimePart;
}
}
foreach (var part in message.BodyParts)
{
var mimePart = (MimePart)part;
if (mimePart.ContentId == fileId || mimePart.FileName == fileName)
{
return mimePart;
}
}
return null;
}
So I expected that this code will work for each IMAP connection. But it's not
Upvotes: 0
Views: 35
Reputation: 38528
You have 2 problems in your code:
using MemoryStream memoryStream = new MemoryStream();
await mimePart.Content.DecodeToAsync(memoryStream);
The first is that the using
statement will cause the memoryStream to get disposed at the end of your method.
The second issue is that you need to rewind the stream.
Change your code to this:
MemoryStream memoryStream = new MemoryStream();
await mimePart.Content.DecodeToAsync(memoryStream);
memoryStream.Position = 0;
Upvotes: 0