Articles in this section
Category / Section

How to attach the PDF document loaded in PDF viewer control to default mail service in Xamarin.iOS platform?

4 mins read

You can compose a new mail using the native User Interface available in Xamarin.Forms (iOS, Android, and UWP). The following code snippets illustrate how to open the default mail service of the platform and attach the PDF to the mail.

Portable

Define the following interface in the portable project

C#

public interface IMailService
{
   void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, Stream documentStream);
}

 

Call the ComposeMail method in code behind using the DependencyService when the mail is to be composed, e.g., when a button is clicked.

C#

private void OnSendEmailClicked(object sender, EventArgs e)
{
//Dependency service to open the native mail composer with the attachment
                   Xamarin.Forms.DependencyService.Get<IMailService>().ComposeMail("MailAttachment.pdf", null, "Mail Attachment", "Syncfusion", pdfViewerControl.InputFileStream);
}

 

Android

Implement the interface in Android platform.

C#

//Register the Android implementation of the IMailService interface with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.Droid.MailService))]
 
namespace GettingStarted_PDFViewer.Droid
{
    public class MailService : IMailService
    {
        public MailService()
        {
        }
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, Stream filestream)
        {
            string exception = string.Empty;
 
            string root = null;
            //Get the root folder of the application
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
 
            //Create a new folder with the name Syncfusion in the root folder
            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();
 
            //Create a new file with the file name in the Syncfusion folder
            Java.IO.File file = new Java.IO.File(myDir, fileName);
 
            //If the file already exists delete it
            if (file.Exists()) file.Delete();
 
            try
            {
                //Save the input filestream to the created file
                using (MemoryStream documentStream = new MemoryStream())
                {
                    filestream.Position = 0;
                    filestream.CopyTo(documentStream);
                    Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file);
                    outs.Write(documentStream.ToArray());
 
                    outs.Flush();
                    outs.Close();
                }
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }
 
            Intent email = new Intent(Android.Content.Intent.ActionSend);
            //Specify the path of the PDF document
            var uri = Android.Net.Uri.Parse("file:///" + file.AbsolutePath);
            //Adding subject to the Email
            email.PutExtra(Android.Content.Intent.ExtraSubject, subject);
            //Adds the file stream from the uri
            email.PutExtra(Intent.ExtraStream, uri);
            //Type of document to be shared
            email.SetType("application/pdf");
            //Launches the current activity.
            Forms.Context.StartActivity(email);
        }
    }
}

 

iOS

Implement the interface in iOS platform. At least, one email account must be enabled on the device.

C#

//Register the iOS implementation of the interface IMailService with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.iOS.MailService))]
namespace GettingStarted_PDFViewer.iOS
{
    public class MailService : IMailService
    {
        public MailService()
        {
        }
 
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, Stream stream)
        {
            if (MFMailComposeViewController.CanSendMail)
            {
                //Native mail composer ViewController
                var mailer = new MFMailComposeViewController();
                //Sets the given message to the body of the Email.
                mailer.SetMessageBody(messagebody ?? string.Empty, false);
                //Add the given subject to email
                mailer.SetSubject(subject ?? subject);
                mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });
 
 
                string exception = string.Empty;
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                //Path of the file to which the input stream is to be saved
                string filePath = Path.Combine(path, fileName);
                //Save the input stream to the created file
                try
                {
                    FileStream fileStream = File.Open(filePath, FileMode.Create);
                    stream.Position = 0;
                    stream.CopyTo(fileStream);
                    fileStream.Flush();
                    fileStream.Close();
                }
                catch (Exception e)
                {
                    exception = e.ToString();
                }
                finally
                {
                }
 
                //Attach the PDF document in the filepath to mail composer
                mailer.AddAttachmentData(NSData.FromFile(filePath), "application/pdf", Path.GetFileName(fileName));
 
 
                //Gets the root ViewController
                UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }
                //Adds the MFMailComposeViewController to the View
                vc.PresentViewController(mailer, true, null);
            }
        }
    }
}

 

UWP

Implement the interface in UWP platform.

C#

//Register the UWP implementation of the interface IMailService with DependencyService
[assembly: Dependency(typeof(GettingStarted_PDFViewer.UWP.MailService))]
namespace GettingStarted_PDFViewer.UWP
{
    public class MailService : IMailService
    {
        public async void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, Stream stream)
        {
            //Creates native mail composer in WP
            var emailMessage = new EmailMessage
            {
                Subject = subject,
                Body = messagebody
            };
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
 
            //The path of the file to which the input stream is to be saved
            StorageFile outFile = await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
 
            //Write the stream to the created file
            using (Stream outStream = await outFile.OpenStreamForWriteAsync())
            {
                using (MemoryStream documentStream = new MemoryStream())
                {
                    stream.Position = 0;
                    stream.CopyTo(documentStream);
                    outStream.Write(documentStream.ToArray(), 0, (int)documentStream.Length);
                }
            }
            //Attaches the document given in the fileName.
            emailMessage.Attachments.Add(new EmailAttachment(fileName, outFile));
 
            //Shows the mail composer with the attachment.
            await EmailManager.ShowComposeNewEmailAsync(emailMessage);
        }
    }
}
 

 

Sample link:


Conclusion

I hope you enjoyed learning about how to attach the PDF document loaded in PDF viewer control to default mail service in Xamarin.Forms platform.


You can refer to our Xamarin.iOS PDFViewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our  Xamarin.iOS PDFViewer example to understand how to create and manipulate data.


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 forumsDirect-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 sign in to leave a comment
Access denied
Access denied