Why Memory Stream does not work with FluentEMail.Core.Model.Attachment for sending files?

59 views Asked by At

I was creating an action method for sending emails in asp.net web api using FluentEmail. I wanted to send multiple attachments with my email.

I first used Memory Stream to copy the file into the FluentEmail.Core.Models.Attachment class.

        using FluentEmail.Core.Models;
        public async Task<IActionResult> SendMail(IFormFileCollection files)
        {
            var attachmentList = new List<Attachment>();
            foreach (var file in files)
            {
                var attachment = new Attachment()
                {
                    Data = new MemoryStream(),
                    ContentType = file.ContentType,
                    Filename = file.FileName
                };
                await file.CopyToAsync(attachment.Data);
                attachmentList.Add(attachment);
            }

            var response = await _fluentEmail
                .To(_senderEmail)
                .Subject("SUBJECT")
                .Body("MESSAGE")
                .ReplyTo(_receiverEmail)
                .Attach(attachmentList)
                .SendAsync();

            return Ok();
        }

The Email was triggered but the Files attached to it were empty (Sizes were in few bytes, may be because only file headers were passed and not the file content).

Although after debugging I found that the file content was being passed into the .Attach() method perfectly.

I also tried making the method synchronous, but all in vain.

So I updated my code and used OpenReadStream instead.

                var attachment = new FluentEmail.Core.Model.Attachment()
                {
                    Data = file.OpenReadStream(),
                    ContentType = file.ContentType,
                    Filename = file.FileName
                };
                attachmentList.Add(attachment);

With this I was able to get the files along with their contents in the email perfectly.

I think it could be because the scope of the MemoryStream was being disposed off(as I faced similar issue with it before), but I am not sure.

Can anyone explain why MemoryStream didn't worked?

1

There are 1 answers

0
jstedfast On

Most likely the problem is because you didn’t set the MemoryStream’s Position property back to 0 after copying the content into it.

Any code that reads from a stream will start at the current position in the stream, which is not necessarily the beginning of the stream.

By setting the position back to the beginning, code that reads from a stream will start reading from the beginning.