如何使用 Xamarin.Essentials 将 PDF 作为电子邮件附件附加?

How to attach a PDF as a EmailAttachment using Xamarin.Essentials?

我正在使用 James Montemagno 在 Xamarin Essentials 上关于如何使用 IEmailService 附加文档的教程。如何将 Syncfusion PDFDocument 作为电子邮件附件附加?

using (MyTestPdfDocument document = new MyTestPdfDocument())
{
    //Save the document
    using (MemoryStream pdfStream = new MemoryStream())
    {
        document.Save(pdfStream);
        FormattableString formattedEmail = $"\n-ExWU version-\nExpress WriteUp";

        try
        {
            var message = new EmailMessage
            {
                Subject = "Hello",
                Body = "World",
            };

            //var fn = "Attachment.pdf";
            var file = Path.Combine(FileSystem.CacheDirectory, document);//Close the document

            message.Attachments.Add(new EmailAttachment(file));

            await _emailService.ComposeAsync(message);

            }
            catch (FeatureNotSupportedException)
            {
                await PageDialogService.DisplayAlertAsync("", "Email is not supported on this device", "Ok");
            }
            catch (Exception ex)
            {

            }
        }
    }
}

我使用下面的 DependencyService 解决了我的问题。 EmailAttachment 构造函数需要您保存的文档的文件路径,而不是实际文档。在对 James 的代码稍作修改后,我能够为我的 pdf 创建一个文件路径和一个依赖服务以将我的 pdf 内容绘制到流中。

try
{
    var message = new EmailMessage
    {
        Subject = "Hello",
        Body = "World",
    };

    var fn = "attachment.pdf";
    var filePath = Path.Combine(FileSystem.CacheDirectory, fn);
    string folderPath = DependencyService.Get<IDirectoryService>().SavePath(pdfStream, filePath);

    message.Attachments.Add(new EmailAttachment(folderPath));
    await _emailService.ComposeAsync(message);
}


catch (FeatureNotSupportedException)
{
    await PageDialogService.DisplayAlertAsync("", "Email is not supported on this device", "Ok");
}

catch (Exception ex)
{

}

iOS 实施

public class DirectoryService : IDirectoryService
{
    public string SavePath(Stream inputStream, string fileName)
    {
        //Create a new file with the input file name in the Library folder
        var m_filepath = fileName;

        //Write the contents of the pdf to the newly created file
        using (MemoryStream tempStream = new MemoryStream())
        {
            inputStream.Position = 0;
            inputStream.CopyTo(tempStream);
            File.WriteAllBytes(m_filepath, tempStream.ToArray());
        }
        return m_filepath;
    }
}

我们可以通过以下步骤使用 Xamarin Essentials 将 Syncfusion PDF 文档附加为电子邮件附件,

  • 创建 PDF 文档并将其保存到文件夹中
  • 获取PDF文件的完整路径
  • 使用 Xamarin Essentials 将该 PDF 文档发送到电子邮件附件

我们已经创建了相同的示例,可以从下面下载 link,

Sample to attach PDF as an Email attachment