当我尝试通过我的C#代码发送带有多个收件人附件的电子邮件时,会抛出一个System.Net.Mail.SmtpException,说"发送邮件失败".内部异常是"其中一个流已被使用,无法重置为原点."
我理解这种错误可能因为我的依恋而发生.我在另一个班级创建了我的附件 -
Attatchment file;
string fileContents = File.ReadAllText(fileName);
file = Attachment.CreateAttachmentFromString(fileContents, fileName);
Run Code Online (Sandbox Code Playgroud)
我将这种格式发送给发送电子邮件的班级.该课程发生以下情况 -
try
{
email.Subject = subject;
email.Body = body;
if (file != null)
{
email.Attachments.Add(file);
}
_smtpClient.Send(email);
}
catch
{
mailSent = false;
}
Run Code Online (Sandbox Code Playgroud)
邮件总是发送给第一个收件人,但所有其他收件人都失败了.任何想法为什么会发生这种情况?
在Attachment类的内部,它似乎使用a Stream来包含数据.某些类型的流不允许您将位置重置回到开头,并且会抛出InvalidOperationException您在上面看到的消息.
您的解决方案是:
Bcc字段中.这可能不起作用,但您可以尝试使用构造函数Attachment,它将流作为参数而不是字符串.将所有字符串数据放入MemoryStream允许重新定位的数据中.例如:
public Stream StringToStream(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Run Code Online (Sandbox Code Playgroud)
然后这个:
var stream = StringToStream(File.ReadAllText(fileName));
Attatchment file = new Attachment(stream, fileName);
Run Code Online (Sandbox Code Playgroud)注意:您正在错误地初始化附件对象.在带有两个参数的构造string函数中,第二个参数是媒体类型,而不是文件名.