如何在 C# 中将 XElement 作为附件附加到 SMTP 消息
我正在尝试将 XElement 附加到我正在发送的 SMTP 消息中。
我的代码如下所示:
XElement xmlMsg = new XElement("Test",new XElement("TestSon", "DummyValue"),new XElement("TestSon2","DummyValue"));
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] contentAsBytes = Encoding.Default.GetBytes(xmlMsg.ToString());
memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
// Set the position to the beginning of the stream.
memoryStream.Seek(0, SeekOrigin.Begin);
// Create attachment
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain;
contentType.Name = "Conversation.xml";
Attachment attachment = new Attachment(memoryStream, contentType);
mail.Attachments.Add(attachment);
Server.Send(mail);
}
但是,我收到的电子邮件的末尾带有被剪裁的 XML 文件,没有最后 2 个字符...
我在这里遗漏了什么吗?
谢谢
I'm trying to attach an XElement to an SMTP message i'm sending.
My code looks like this:
XElement xmlMsg = new XElement("Test",new XElement("TestSon", "DummyValue"),new XElement("TestSon2","DummyValue"));
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] contentAsBytes = Encoding.Default.GetBytes(xmlMsg.ToString());
memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);
// Set the position to the beginning of the stream.
memoryStream.Seek(0, SeekOrigin.Begin);
// Create attachment
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain;
contentType.Name = "Conversation.xml";
Attachment attachment = new Attachment(memoryStream, contentType);
mail.Attachments.Add(attachment);
Server.Send(mail);
}
However, my email is received with the XML file clipped at the end, without the last 2 chars...
Am i missing something here?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的系统上的
Encoding.Default
是什么编码?如果是 UTF-16,我希望这两个字节是 BOM(由于某种原因)不包含在字节计数中。
建议:
xmlMsg.ToString()
放入局部变量中,并在调试器中检查它。IE。尽可能少地自动重新解释(例如通过 XML 查看器)检查每个步骤。
What encoding is
Encoding.Default
on your system?If it is UTF-16 I expect the two bytes are a BOM which is (for some reason) not being included in the byte count.
Suggestions:
xmlMsg.ToString()
into a local variable, and check it in the debugger.memoryStream
Ie. check each step with as little automatic re-interpretation (eg. by an XML viewer) as possible.