C# 如何使用Xamarin.Essentials将PDF附加为电子邮件附件?
我正在使用詹姆斯·蒙特马诺(James Montemagno)的本教程,介绍如何在使用IEmailService时附加文档。如何将Syncfusion PDF文档作为电子邮件附件附加C# 如何使用Xamarin.Essentials将PDF附加为电子邮件附件?,c#,xamarin,xamarin.forms,syncfusion,C#,Xamarin,Xamarin.forms,Syncfusion,我正在使用詹姆斯·蒙特马诺(James Montemagno)的本教程,介绍如何在使用IEmailService时附加文档。如何将Syncfusion PDF文档作为电子邮件附件附加 using (MyTestPdfDocument document = new MyTestPdfDocument()) { //Save the document using (MemoryStream pdfStream = new MemoryStream()) { d
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解决了我的问题<代码>电子邮件附件构造函数需要保存的文档的文件路径,而不是实际文档。在对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)
{
}
我们可以使用Xamarin Essentials通过以下步骤将Syncfusion PDF文档作为电子邮件附件附加
- 创建PDF文档并将其保存到文件夹中
- 获取PDF文件的完整路径
- 使用Xamarin Essentials将该PDF文档发送到电子邮件附件
免责声明:我不使用Syncfusion或Xamarin。在我看来,您可能需要a)将生成的PDF保存到文件中,然后附加到该文件,或者b)(假设EmailAttachment和Syncfusion支持此功能)将生成的PDF写入
MemoryStream
并从中创建附件。
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;
}
}