生成Word文档并附加/发送电子邮件而不保存?

时间:2013-08-02 17:17:48

标签: c# html asp.net email attachment

我有一个包含html的字符串。我已经能够将它作为.doc文件保存到我的计算机/服务器,但我希望能够从C#发送电子邮件而不将其保存到服务器中。我所拥有的是:

 MailMessage msg = new MailMessage();

        msg.From = "from@email.com";
        msg.To = "to@email.com";
        msg.Subject = "Subject";
        msg.Body = "Body";

        string body = "<html><head></head><body><p>Word doc body here</p></body></html>";
        byte[] data = Encoding.ASCII.GetBytes(body);
        MemoryStream ms = new MemoryStream(data);
        Attachment att = new Attachment(ms, "Interview-Questions-Template.doc", "application/application/msword");
        msg.Attachments.Add(att);

        SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SmtpPrimaryServer"]);

如果我拿出附件,他们会发送电子邮件。我得到的错误是:

System.FormatException: The specified content type is invalid.
at System.Net.Mime.ContentType.ParseValue()
at System.Net.Mime.ContentType..ctor(String contentType)
at System.Net.Mime.MimePart.SetContent(Stream stream, String name, String mimeType)
at System.Net.Mail.Attachment..ctor(Stream contentStream, String name, String mediaType)
at EmailClass.sendEmail(String To, String Bcc, String Cc, String From, String Subject, String body) in <i took out the file path>

错误的最后一行指向代码中的行:

Attachment att = new Attachment(ms, "Interview-Questions-Template.doc", "application/application/msword");

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

确定。我想通了,问题是我将字符串转换为byte []的地方。通过使用静态方法:

static byte[] GetData()
{
    string s = "<html><head></head><body><p>Word doc body here</p></body></html>";
    byte[] data = Encoding.ASCII.GetBytes(s);
    return data;
}
问题解决了。