Nix*_*een 5 c# pdf msg gembox-document gembox-email
我正在使用GemBox.Email和GemBox.Document将电子邮件转换为 PDF。
这是我的代码:
static void Main()
{
MailMessage message = MailMessage.Load("input.eml");
DocumentModel document = new DocumentModel();
if (!string.IsNullOrEmpty(message.BodyHtml))
document.Content.LoadText(message.BodyHtml, LoadOptions.HtmlDefault);
else
document.Content.LoadText(message.BodyText, LoadOptions.TxtDefault);
document.Save("output.pdf");
}
Run Code Online (Sandbox Code Playgroud)
该代码适用于 EML 文件,但不适用于 MSG( 和MailMessage.BodyHtml)MailMessage.BodyText均为空。
我怎样才能让味精也能做到这一点?
问题发生在 RTF 正文中没有 HTML 内容、而是具有原始 RTF 正文的特定 MSG 文件中。
该类MailMessage当前不公开 RTF 正文的 API(仅限纯文本和 HTML 正文)。不过,您可以将其检索为Attachment名为“ Body.rtf ”的文件。
另外仅供参考,您遇到的另一个问题是电子邮件 HTML 正文中的图像未内联,因此在导出为 PDF 时您会丢失它们。
无论如何,尝试使用以下方法:
static void Main()
{
// Load an email (or retrieve it with POP or IMAP).
MailMessage message = MailMessage.Load("input.msg");
// Create a new document.
DocumentModel document = new DocumentModel();
// Import the email's body to the document.
LoadBody(message, document);
// Save the document as PDF.
document.Save("output.pdf");
}
static void LoadBody(MailMessage message, DocumentModel document)
{
if (!string.IsNullOrEmpty(message.BodyHtml))
{
var htmlOptions = LoadOptions.HtmlDefault;
// Get the HTML body with embedded images.
var htmlBody = message.GetEmbeddedBodyHtml();
// Load the HTML body to the document.
document.Content.End.LoadText(htmlBody, htmlOptions);
}
else if (message.Attachments.Any(a => a.FileName == "Body.rtf"))
{
var rtfAttachment = message.Attachments.First(a => a.FileName == "Body.rtf");
var rtfOptions = LoadOptions.RtfDefault;
// Get the RTF body from the attachment.
var rtfBody = rtfOptions.Encoding.GetString(rtfAttachment.Data.ToArray());
// Load the RTF body to the document.
document.Content.End.LoadText(rtfBody, rtfOptions);
}
else
{
// Load TXT body to the document.
document.Content.End.LoadText(message.BodyText, LoadOptions.TxtDefault);
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息(例如如何添加电子邮件标题和附件以输出 PDF),请查看将电子邮件转换为 PDF示例。
| 归档时间: |
|
| 查看次数: |
8404 次 |
| 最近记录: |