使用XMLSerializer直接流式传输到MailMessage附件

时间:2016-01-26 19:12:48

标签: c# smtp gmail xmlserializer mailmessage

我正在使用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文件完全为空。

1 个答案:

答案 0 :(得分: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