代码之家  ›  专栏  ›  技术社区  ›  Soulzityr

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

  •  0
  • Soulzityr  · 技术社区  · 9 年前

    我使用的是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 回复  |  直到 9 年前
        1
  •  1
  •   Community ƒernando Valle    7 年前
    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