c# - 来自内存流的电子邮件附件错误,但仅在第一次发送后
问题描述
我做了一个循环以将具有相同附件的电子邮件发送到不同的电子邮件:第一次发送没有问题,从第二次发送附件已损坏:
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);
一切正常,但只有在第一次发送附件损坏后才能读取!
谢谢你的帮助
解决方案
到达流的末尾后,您将无法从中读取更多数据。这就是为什么你应该在使用后将其设置为 0。
ms.位置=0;
推荐阅读
- makefile - 使用 make -j4 编译项目时出错,但使用 make j1 编译时通过
- python - 用熊猫从excel中读取大量数据
- postgresql - 从远程计算机连接到 localhost PgAdmin 服务器
- python-3.x - 如何在 Fernet 中使用 decrypt_at_time 函数(Python 3.9)
- django - 由于 FOREIGN KEY 约束失败(IntegrityError),Django 反对创建失败
- linux - 使用 autogen 和 cmake 构建时共享 protobuf 库的 SONAME 不一致
- python - Python 代码在尝试处理异常时卡住了
- api - Binance API,通过股票代码简单获取价格,不起作用
- vbscript - T-21 天的 Vb 脚本(这里 T 是当前日期)
- highcharts - 如何在图表堆栈中制作一些列,同时保持其他列分开?