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

发布于 2024-12-12 12:45:20 字数 941 浏览 2 评论 0原文

我正在尝试将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰火雁神 2024-12-19 12:45:20

您的系统上的 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:

  • Put xmlMsg.ToString() into a local variable, and check it in the debugger.
  • Have a look at the bytes in memoryStream
  • Look at the content of the email message in the raw, possibly copying the unencoded attachment so you can manually decode as a binary file.

Ie. check each step with as little automatic re-interpretation (eg. by an XML viewer) as possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文