We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

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

Platform: Xamarin.iOS |
Control: PdfViewer |
.NET Framework: 4.5.1

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:

http://www.syncfusion.com/downloads/support/directtrac/general/ze/GETTIN~1-794587130https://www.syncfusion.com/downloads/support/directtrac/general/ze/GETTIN~1-794587130

2X faster development

The ultimate Xamarin UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile