Articles in this section
Category / Section

How to open the default mail app with a PDF attachment from the PDF viewer in .NET MAUI?

7 mins read

This article explains how to build a .NET MAUI application that opens the device’s default mail app and attaches a PDF document currently loaded in the Syncfusion MAUI PDF Viewer.

The .NET MAUI PDF Viewer allows you to load and work with PDFs in your applications. You can easily share these documents via email by saving them to the file system using the SaveDocument API and then attaching them to an email using Email API.

Prerequisites

Step 1: Install Required NuGet Package

To get started, create a new Maui app and ensure the following package is installed in your .NET MAUI project:

Syncfusion.Maui.PdfViewer

You can install this package using the NuGet Package Manager or the NuGet CLI.

Step 2: Initialize the PDF Viewer in XAML

Start by adding the Syncfusion PDF Viewer control to your XAML file.

a. Add the Syncfusion namespace in your MainPage.xaml:

Define the XAML namespace to enable access to the PDF Viewer.

XAML

xmlns:syncfusion="clr-namespace:Syncfusion.Maui.PdfViewer;assembly=Syncfusion.Maui.PdfViewer"

b. Add the PDF Viewer control to your layout:

Initialize the SfPdfViewer in the XAML file. This will display the PDF Viewer in your app. You can load any PDF document into this Viewer.

XAML

<syncfusion:SfPdfViewer x:Name="pdfViewer" Grid.Row="1"/>

c. Load the PDF in the PDF Viewer control:

Load the PDF document as an embedded resource using the DocumentSource API in the PDF Viewer.

C#

pdfViewer.DocumentSource = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SharePdfThroughEmail.Assets.PDF_Succinctly.pdf");

Step 3: Add a Share PDF through the Mail Button in XAML

Add a button to share the PDF through the mail in XAML.

XAML

<Button Text="Share PDF through Mail"        
       FontSize="24"
       TextColor="White"
       VerticalOptions="Start"
       HorizontalOptions="End"               
       WidthRequest="60" 
       HeightRequest="50"
       Margin="0,0,5,0"
       Clicked="SharePDFThroughMail_Clicked"/>

This button will trigger the logic to open the mail app with the PDF attached.

Step 4: Implement Email Sharing Logic in Code-Behind

  1. Access the saved stream from the SaveDocument API to acquire the PDF content.

  2. Generate a temporary file to store the PDF data extracted from the saved stream.

  3. Check if the default mail service allows email composition using the Email.Default.IsComposeSupported.

  4. Create an EmailMessage with a descriptive subject, message body, and identified recipient.

  5. Attach the previously generated file to the EmailMessage.Attachments.

  6. Refer to the following code snippets to share the PDF to the default mail service.

C#

 private async void SharePDFThroughMail_Clicked(object sender, EventArgs e)
 {
     try
     {
         // Define the file name and path for the saved PDF document.
         string fileName = Path.Combine(FileSystem.Current.AppDataDirectory, "ModifiedDocument.pdf");

         // Save the PDF document to the specified file location.
         using (FileStream pdfStream = File.Create(fileName))
         {
             // Using pdfViewer instance to save the PDF document to a stream.
             pdfViewer.SaveDocument(pdfStream);
         }

         // Verify if the file exists at the specified path.
         if (File.Exists(fileName))
         {
             // Define a temporary file path for the PDF content to be used for email attachments.
             var tempFilePath = Path.Combine(FileSystem.CacheDirectory, "ModifiedDocument.pdf");

             // Copy the PDF content to the temporary file to prepare for email attachment.
             File.Copy(fileName, tempFilePath, true);

             // Check if email composition is supported on the device.
             if (Email.Default.IsComposeSupported)
             {
                 // Define the email's subject and body text.
                 string subject = "PDF Document Shared through MAUI SfPdfViewer";
                 string body = "Please find the PDF document attached.";

                 // Create the email message with the subject, body, and recipient.
                 var message = new EmailMessage
                 {
                     Subject = subject,
                     Body = body,
                     BodyFormat = EmailBodyFormat.PlainText,
                     To = new List<string> { "recipient@example.com" } // Placeholder recipient email
                 };

                 // Attach the modified PDF file to the email message.
                 message.Attachments?.Add(new EmailAttachment(tempFilePath));

                 // Open the default mail application to compose the email with the attached PDF.
                 await Email.Default.ComposeAsync(message);
             }
             else
             {
                 // Display an alert if email composition is not supported on the device.
                 await DisplayAlert("Email Not Supported", "This device does not support composing emails.", "OK");
             }
         }
         else
         {
             // Display an alert if the PDF file does not exist.
             await DisplayAlert("File Error", "Unable to locate the modified PDF file.", "OK");
         }
     }
     catch (Exception ex)
     {
         // Handle exceptions and display any error messages to the user.
         await DisplayAlert("Error", ex.Message, "OK");
     }
 }

Step 5: Run the app

Build and run your .NET MAUI application. The PDF Viewer will display the loaded PDF document, and tapping the “Share PDF through Mail” button will open the default email app on the device with the PDF file attached and ready to send.

Output:

SharePdfThroughEmail.gif

Sample Link :

View sample in GitHub

Conclusion

I hope this article helped you learn how to build a .NET MAUI application that opens the default mail app and shares a PDF document loaded in the Syncfusion MAUI PDF Viewer.

You can refer to our MAUI PDFViewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied