Home > Blockchain >  Get attachment and save in s3 bucket mailkit imap
Get attachment and save in s3 bucket mailkit imap

Time:04-13

I need to get the attachments that are in the email to save, I do the whole process of reading the email and saving as I need to, but when I try to get the attachments to save in the AWS S3 Bucket it gives an error when it tries to read the content type. Basically what I need to do is.

  1. Get the attachment.
  2. Create a FormFile for my S3 save function to save the attachments (The S3 save function is already working). I am having problem just to build the FormFile.
.
.
.
var attachmentsToS3 = new FormFileCollection();
foreach (var attachment in message.Attachments)
{
    var part = attachment as MimePart;
    var stream = new MemoryStream();
    await part.Content.DecodeToAsync(stream);
    var fileLength = stream.Length;
    var formFile = new FormFile(stream, 0, fileLength, "file[]", attachment.ContentDisposition.FileName);
    attachmentsToS3.Add(formFile);
}

await _atendimentoServices.SaveAnexoAtendimentoToS3( attachmentsToS3, idAcompanhamento, requestApi);
.
.
.

CodePudding user response:

Good Afternoon Gabriel, Analysing you code I noticed there were missing some parts of code.

the first you need to trate your attachment to like this:

if (attachment is MimePart part) await part.Content.DecodeToAsync(memory);
else await ((MessagePart)attachment).Message.WriteToAsync(memory);

With that you'll garanted your stream will be populated correctly been a mimeType or not.

The other part was missing is the header and the content type at your FormFile constructor, try that.

var formFile = new FormFile(memory, 0, bytes.Length, "file[]", attachment.ContentDisposition.FileName)
                            {
                                Headers = new HeaderDictionary(),
                                ContentType = MimeTypes.GetMimeType(attachment.ContentType.MimeType);
                            };
  • Related