首页 > 解决方案 > 来自内存流的电子邮件附件错误,但仅在第一次发送后

问题描述

我做了一个循环以将具有相同附件的电子邮件发送到不同的电子邮件:第一次发送没有问题,从第二次发送附件已损坏:

    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;
    }

在帮助文件中,我有这个:

    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;
    }

这里用循环调用sendmail

    ...
    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);
    }

在其他帮助文件中发送电子邮件

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);

一切正常,但只有在第一次发送附件损坏后才能读取!
谢谢你的帮助

标签: c#asp.net-mvc

解决方案


到达流的末尾后,您将无法从中读取更多数据。这就是为什么你应该在使用后将其设置为 0。

ms.位置=0;


推荐阅读