【问题标题】:Use XMLSerializer to stream directly into a MailMessage Attachment使用 XMLSerializer 直接流式传输到 MailMessage 附件
【发布时间】:2016-05-03 11:51:16
【问题描述】:

我正在使用 XMLSerializer,我需要将其直接写入邮件消息附件,最好不要先将其保存到文件中。

我的代码

var smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new System.Net.NetworkCredential("email@gmail.com", "password"),
            EnableSsl = true
        };

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(XmlRoot));

        ser.Serialize(ms, model);

        var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");

        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

        message.To.Add("tothisemail@gmail.com");
        message.Subject = String.Format("{0}", some subject name);
        message.From = new System.Net.Mail.MailAddress("email@gmail.com");
        message.Body = "empty content";
        message.Attachments.Add(attachment);

        smtp.Send(message);

发生的情况是电子邮件已成功发送,但它写入的 xml 文件完全为空。

【问题讨论】:

    标签: c# smtp gmail xmlserializer mailmessage


    【解决方案1】:
    ser.Serialize(ms, model);
    
    ms.Position = 0;
    
    var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");
    

    Writing to then reading from a MemoryStream

    【讨论】:

    • 那么我的代码中的错误是什么?由于 ms.Position 在最后,它是从头到尾写的,所以什么都没有?
    • 是的,smtp 客户端类正在尝试从流的当前位置读取直到结束,因此找不到要读取的任何内容。我刚刚回答了一个非常相似的问题,stackoverflow.com/questions/35022001/…,其中部分解决方案还归结为需要将位置重置回开始。
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2018-02-18
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多