如何在c#中将XElement作为附件附加到SMTP消息上

本文关键字:SMTP 消息 中将 XElement | 更新日期: 2023-09-27 18:13:00

我正在尝试将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文件剪辑在最后,没有最后两个字符…

我错过了什么吗?

谢谢

如何在c#中将XElement作为附件附加到SMTP消息上

Encoding.Default在您的系统上是什么编码?

如果它是UTF-16,我希望这两个字节是一个BOM(由于某种原因)不包括在字节计数中。

建议:

  • xmlMsg.ToString()放入本地变量中,并在调试器中检查。
  • 查看memoryStream
  • 中的字节数
  • 查看电子邮件的原始内容,可能会复制未编码的附件,以便您可以手动解码为二进制文件。

Ie。检查每一步,尽可能少地自动重新解释(例如: