生成Word文档并在不保存的情况下附加/发送电子邮件



我有一个包含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");

如有任何帮助,我们将不胜感激。

好的。我想明白了,问题是我把字符串转换成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;
}

问题解决了。

相关内容

  • 没有找到相关文章

最新更新