Error in Email Attachment from memory stream but only after first send

Viewed 309

I do a loop to send an email with the same attachments to different email: with the first sending there are no problems, from the second the attachments are corrupt:

    public Dictionary<MemoryStream, string> GetDocumentsForEmail(int idCorso)
    {
        string response = string.Empty;
        var dictionary = new Dictionary<MemoryStream, string>();

        var documents = (from d in db.Documents
                         where d.IDCorso == idCorso
                         select d).ToList();
        if (documents.Count > 0)
        {
            foreach (var doc in documents)
            {
                var file = new MyFileHelper().GetDownloadFile(idCorso, doc.IDFileType);
                if (file != null)
                {
                    dictionary.Add(file.Item1, file.Item2);
                }
            }
            return dictionary;
        }
        return null;
    }

In helper file I've this:

    public Tuple<MemoryStream, string> GetDownloadFile(int IDCorso, int fileType)
    {
        var document = (from d in db.Documents
                         where d.IDCorso == IDCorso && d.IDFileType == fileType
                         select d).FirstOrDefault();
        if (document != null)
        {
            string fileName = document.FileName.Trim() + document.FileExtension.Trim();
            byte[] fileBytes = document.FileContent;
            MemoryStream ms = new MemoryStream(fileBytes);
            return Tuple.Create(ms, fileName);
         }
        return null;
    }

Here call sendmail with loop

    ...
    var listAttachment = new List<Dictionary<MemoryStream, string>>();
    listAttachment.Add(GetDocumentsForEmail(idCorso));
    foreach (var item in users)
    {
        listTo.Clear();
        var emailUser = GetEmailUser(item.ci.IDUser).ToString();
        listTo.Add(emailUser);
        mail.SendEmail(listTo, ..., listAttachment);
    }

In other helper file send email

public class MyMailHelper
{
    public void SendEmail(List<string> mailTOList..., List<Dictionary<MemoryStream, string>> mailAttachment = null)
    {
       ...
       SmtpClient SmtpServer = new SmtpClient();
       MailMessage mail = new MailMessage(){...}
       ...
       if (mailAttachment != null)
       {
          foreach (var item in mailAttachment)
          {
             foreach (var key in item.Keys)
             {
                mail.Attachments.Add(new Attachment(key, item[key]));
             }
          }
        }
        SmtpServer.Send(mail);

Everything works fine, but only with the first sending the attachments are readable, after they are corrupt!
Thanks for your help

1 Answers

Once you've reached the end of your stream, you won't be able to read more data from it. that's why you should set it to 0 after using it.

ms.Position=0;

Related