想要把邮件转换成PDF?整起!

310 阅读2分钟

当需要将电子邮件的内容嵌入Web或桌面应用程序中时,可能会出现各种情况。在某些情况下,需要将电子邮件转换为易于嵌入和显示的格式,可能的解决方案之一是电子邮件到PDF的转换。本文提供了有关如何使用C#将电子邮件转换为PDF的分步指南和代码示例。

Aspose.Email是一个C#类库,旨在从.NET应用程序内部创建和处理流行的电子邮件格式。该API与Aspose.Words for .NET结合使用,可以使您以高保真度将电子邮件转换为PDF格式。(点击下载

电子邮件处理类库Aspose.Email功能教程:使用C#将电子邮件转换为PDF

使用C#将电子邮件转换为PDF的步骤

以下是在C#中将电子邮件转换为PDF格式的步骤。

  • 使用MailMessage类加载电子邮件文件。

    // Load email message using file
    MailMessage mailMsg = MailMessage.Load("message.msg");
    
  • 将电子邮件保存为默认MHTML格式的MemoryStream对象。

    // Create memory stream
    MemoryStream ms = new MemoryStream();
    
    // Save email message into memory stream
    MailMessage.Save(ms, Aspose.Email.SaveOptions.DefaultMhtml);
    
  • 创建Aspose.Words.LoadOptions类的实例,并将加载格式设置为MHTML。

    // Create and set load options
    var loadOptions = new Aspose.Words.LoadOptions();
    loadOptions.LoadFormat = LoadFormat.Mhtml;
    
  • 实例化Aspose.Words.Document类,并将MemoryStream和LoadOptions对象作为参数传递给其构造函数。

    // Create an instance of Document and load the MTHML from MemoryStream
    var document = new Aspose.Words.Document(ms, loadOptions);
    
  • 创建一个Aspose.Words.Saving.PdfSaveOptions类的实例。

    // create an instance of PDFSaveOptions class
    var pdfSaveOptions = new Aspose.Words.Saving.PdfSaveOptions();
    
  • 使用Document.Save(“ email-to-pdf.pdf”,PdfSaveOptions)方法将电子邮件转换为PDF 。

    // Save email as PDF
    document.Save("email-to-pdf.pdf", pdfSaveOptions);
    

使用C#将电子邮件转换为PDF完整代码

// Load email message
MailMessage mailMsg = MailMessage.Load("message.msg");

MemoryStream ms = new MemoryStream();
mailMsg.Save(ms, Aspose.Email.SaveOptions.DefaultMhtml);

// create an instance of LoadOptions and set the LoadFormat to Mhtml
var loadOptions = new Aspose.Words.LoadOptions();
loadOptions.LoadFormat = LoadFormat.Mhtml;

// create an instance of Document and load the MTHML from MemoryStream
var document = new Aspose.Words.Document(ms, loadOptions);

// create an instance of HtmlSaveOptions
var saveOptions = new Aspose.Words.Saving.PdfSaveOptions();
document.Save("email-to-pdf.pdf", saveOptions);

如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。