Ejemplo n.º 1
0
        public void CreateEmail(List <string> emailAddresses, List <string> ccs, string subject, string body, string htmlBody)
        {
            var vc = new MFMailComposeViewController();

            vc.MailComposeDelegate = this;

            if (emailAddresses?.Count > 0)
            {
                vc.SetToRecipients(emailAddresses.ToArray());
            }

            if (ccs?.Count > 0)
            {
                vc.SetCcRecipients(ccs.ToArray());
            }

            vc.SetSubject(subject);
            vc.SetMessageBody(htmlBody, true);
            vc.Finished += (sender, e) =>
            {
                vc.DismissModalViewController(true);
            };



            UIApplication.SharedApplication.Windows[0].
            RootViewController.PresentViewController(vc, true, null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Shows the draft.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="html">if set to <c>true</c> [HTML].</param>
        /// <param name="to">To.</param>
        /// <param name="cc">The cc.</param>
        /// <param name="bcc">The BCC.</param>
        /// <param name="attachments">The attachments.</param>
        public void ShowDraft(
            string subject,
            string body,
            bool html,
            string[] to,
            string[] cc,
            string[] bcc,
            IEnumerable <string> attachments = null)
        {
            var mailer = new MFMailComposeViewController();

            mailer.SetMessageBody(body ?? string.Empty, html);
            mailer.SetSubject(subject ?? string.Empty);
            mailer.SetCcRecipients(cc);
            mailer.SetToRecipients(to);
            mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });

            if (attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    mailer.AddAttachmentData(NSData.FromFile(attachment), GetMimeType(attachment), Path.GetFileName(attachment));
                }
            }

            UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController;

            while (vc.PresentedViewController != null)
            {
                vc = vc.PresentedViewController;
            }
            vc.PresentViewController(mailer, true, null);
        }
Ejemplo n.º 3
0
    public override void ShowDraft(
        string subject,
        string body,
        bool html,
        string[] to,
        string[] cc,
        string[] bcc,
        byte[] screenshot = null)
    {
        var mailer = new MFMailComposeViewController();

        mailer.SetMessageBody(body ?? string.Empty, html);
        mailer.SetSubject(subject ?? string.Empty);
        mailer.SetCcRecipients(cc);
        mailer.SetToRecipients(to);
        mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });
        if (screenshot != null)
        {
            mailer.AddAttachmentData(NSData.FromArray(screenshot), "image/png", "screenshot.png");
        }
        UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController;

        while (vc.PresentedViewController != null)
        {
            vc = vc.PresentedViewController;
        }
        vc.PresentViewController(mailer, true, null);
    }
        public void ComposeEmail(
            IEnumerable<string> to, IEnumerable<string> cc = null, string subject = null,
            string body = null, bool isHtml = false,
            IEnumerable<EmailAttachment> attachments = null, string dialogTitle = null)
        {
            if (!MFMailComposeViewController.CanSendMail)
                throw new MvxException("This device cannot send mail");

            _mail = new MFMailComposeViewController();
            _mail.SetMessageBody(body ?? string.Empty, isHtml);
            _mail.SetSubject(subject ?? string.Empty);

            if (cc != null)
                _mail.SetCcRecipients(cc.ToArray());

            _mail.SetToRecipients(to?.ToArray() ?? new[] { string.Empty });
            if (attachments != null)
            {
                foreach (var a in attachments)
                {
                    _mail.AddAttachmentData(NSData.FromStream(a.Content), a.ContentType, a.FileName);
                }
            }
            _mail.Finished += HandleMailFinished;

            _modalHost.PresentModalViewController(_mail, true);
        }
Ejemplo n.º 5
0
		/// <summary>
		/// Shows the draft.
		/// </summary>
		/// <param name="subject">The subject.</param>
		/// <param name="body">The body.</param>
		/// <param name="html">if set to <c>true</c> [HTML].</param>
		/// <param name="to">To.</param>
		/// <param name="cc">The cc.</param>
		/// <param name="bcc">The BCC.</param>
		/// <param name="attachments">The attachments.</param>
		public void ShowDraft(
			string subject,
			string body,
			bool html,
			string[] to,
			string[] cc,
			string[] bcc,
			IEnumerable<string> attachments = null)
		{
			var mailer = new MFMailComposeViewController();

			mailer.SetMessageBody(body ?? string.Empty, html);
			mailer.SetSubject(subject ?? string.Empty);
			mailer.SetCcRecipients(cc);
			mailer.SetToRecipients(to);
			mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });

			if (attachments != null) 
			{
				foreach (var attachment in attachments) 
				{
					mailer.AddAttachmentData (NSData.FromFile (attachment), GetMimeType (attachment), Path.GetFileName (attachment));
				}
			}

			UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
		}
Ejemplo n.º 6
0
        public void ComposeEmail(
            IEnumerable <string> to, IEnumerable <string> cc = null, string subject = null,
            string body = null, bool isHtml = false,
            IEnumerable <EmailAttachment> attachments = null, string dialogTitle = null)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                throw new MvxException("This device cannot send mail");
            }

            _mail = new MFMailComposeViewController();
            _mail.SetMessageBody(body ?? string.Empty, isHtml);
            _mail.SetSubject(subject ?? string.Empty);

            if (cc != null)
            {
                _mail.SetCcRecipients(cc.ToArray());
            }

            _mail.SetToRecipients(to?.ToArray() ?? new[] { string.Empty });
            if (attachments != null)
            {
                foreach (var a in attachments)
                {
                    _mail.AddAttachmentData(NSData.FromStream(a.Content), a.ContentType, a.FileName);
                }
            }
            _mail.Finished += HandleMailFinished;

            _modalHost.PresentModalViewController(_mail, true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Opens up the ios Email Controller with pre-populated values
        /// </summary>
        /// <param name="email">Email.</param>
        public void CreateEmail(Email email)
        {
            if (CanSendEmail())
            {
                var mailController = new MFMailComposeViewController();
                mailController.SetMessageBody(email.Body, email.IsHtml);
                mailController.SetSubject(email.Subject);
                mailController.SetToRecipients(email.ToAddresses.ToArray());

                if (email.CcAddresses != null && email.CcAddresses.Count > 0 && !string.IsNullOrWhiteSpace(email.CcAddresses[0]))
                {
                    //currently assuming there will only be 1 cc address, TODO: confirm this
                    mailController.SetCcRecipients(email.CcAddresses.ToArray());
                }

                if (!string.IsNullOrWhiteSpace(email.AttachmentFileLocation))
                {
                    UIImage image = new UIImage(email.AttachmentFileLocation);
                    mailController.AddAttachmentData(image.AsJPEG(), "image/jpeg", Path.GetFileName(email.AttachmentFileLocation));
                }

                mailController.Finished += (s, args) => args.Controller.DismissViewController(true, null);
                var rootViewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                rootViewController.PresentViewController(mailController, true, null);
            }
            else
            {
                App.CurrentApp.MainPage.DisplayAlert("No Email App Available", "Unable to send email.", "OK");
            }
        }
Ejemplo n.º 8
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            if (CanSendEmail)
            {
                _mailController = new MFMailComposeViewController();
                _mailController.SetSubject(email.Subject);
                _mailController.SetMessageBody(email.Message, ((EmailMessage)email).IsHtml);
                _mailController.SetToRecipients(email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                {
                    _mailController.SetCcRecipients(email.RecipientsCc.ToArray());
                }

                if (email.RecipientsBcc.Count > 0)
                {
                    _mailController.SetBccRecipients(email.RecipientsBcc.ToArray());
                }

                foreach (var attachment in email.Attachments.Cast <EmailAttachment>())
                {
                    if (attachment.Content == null)
                    {
                        _mailController.AddAttachmentData(NSData.FromFile(attachment.FilePath), attachment.ContentType, attachment.FileName);
                    }
                    else
                    {
                        _mailController.AddAttachmentData(NSData.FromStream(attachment.Content), attachment.ContentType, attachment.FileName);
                    }
                }

                EventHandler <MFComposeResultEventArgs> handler = null;
                handler = (sender, e) =>
                {
                    _mailController.Finished -= handler;

                    var uiViewController = sender as UIViewController;
                    if (uiViewController == null)
                    {
                        throw new ArgumentException("sender");
                    }

                    uiViewController.DismissViewController(true, () => { });
                };

                _mailController.Finished += handler;

                _mailController.PresentUsingRootViewController();
            }
        }
Ejemplo n.º 9
0
        static Task ComposeWithMailCompose(EmailMessage message)
        {
            // do this first so we can throw as early as possible
            var parentController = Platform.GetCurrentViewController();

            // create the controller
            var controller = new MFMailComposeViewController();

            if (!string.IsNullOrEmpty(message?.Body))
            {
                controller.SetMessageBody(message.Body, message.BodyFormat == EmailBodyFormat.Html);
            }
            if (!string.IsNullOrEmpty(message?.Subject))
            {
                controller.SetSubject(message.Subject);
            }
            if (message?.To?.Count > 0)
            {
                controller.SetToRecipients(message.To.ToArray());
            }
            if (message?.Cc?.Count > 0)
            {
                controller.SetCcRecipients(message.Cc.ToArray());
            }
            if (message?.Bcc?.Count > 0)
            {
                controller.SetBccRecipients(message.Bcc.ToArray());
            }

            if (message?.Attachments?.Count > 0)
            {
                foreach (var attachment in message.Attachments)
                {
                    var data = NSData.FromFile(attachment.FullPath);
                    if (data == null)
                    {
                        throw new FileNotFoundException($"Attachment {attachment.FileName} not found.", attachment.FullPath);
                    }

                    controller.AddAttachmentData(data, attachment.ContentType, attachment.FileName);
                }
            }

            // show the controller
            var tcs = new TaskCompletionSource <bool>();

            controller.Finished += (sender, e) =>
            {
                controller.DismissViewController(true, null);
                tcs.TrySetResult(e.Result == MFMailComposeResult.Sent);
            };
            parentController.PresentViewController(controller, true, null);

            return(tcs.Task);
        }
Ejemplo n.º 10
0
 public void ShowDraft(string subject, string body, bool html, string[] to, string[] cc, string[] bcc)
 {
     var mailer = new MFMailComposeViewController();
     mailer.SetMessageBody(body ?? string.Empty, html);
     mailer.SetSubject(subject ?? string.Empty);
     mailer.SetCcRecipients(cc);
     mailer.SetToRecipients(to);
     mailer.Finished += (s, e) =>
     {
         ((MFMailComposeViewController)s).DismissViewController(true, () => { });
     };
 }
Ejemplo n.º 11
0
        static Task DoSendEmail(EmailMessage email)
        {
            return(Thread.UI.Run(() =>
            {
                MailController = new MFMailComposeViewController();
                MailController.SetSubject(email.Subject);
                MailController.SetMessageBody(email.Message, email.IsHtml);
                MailController.SetToRecipients(email.Recipients.ToArray());

                if (email.RecipientsCc.Any())
                {
                    MailController.SetCcRecipients(email.RecipientsCc.ToArray());
                }

                if (email.RecipientsBcc.Any())
                {
                    MailController.SetBccRecipients(email.RecipientsBcc.ToArray());
                }

                email.Attachments.Do(a =>
                {
                    if (a.Content == null)
                    {
                        var data = a.FilePath.IsUrl() ? NSData.FromUrl(new NSUrl(a.FilePath)) : NSData.FromFile(a.FilePath);
                        MailController.AddAttachmentData(data, a.ContentType, a.FileName);
                    }
                    else
                    {
                        MailController.AddAttachmentData(NSData.FromStream(a.Content), a.ContentType, a.FileName);
                    }
                });

                EventHandler <MFComposeResultEventArgs> handler = null;
                handler = (sender, e) =>
                {
                    MailController.Finished -= handler;

                    var uiViewController = sender as UIViewController;
                    if (uiViewController == null)
                    {
                        throw new ArgumentException("sender");
                    }

                    uiViewController.DismissViewController(animated: true, completionHandler: () => { });
                };

                MailController.Finished += handler;

                ((UIViewController)UIRuntime.NativeRootScreen).PresentViewController(MailController, animated: true, completionHandler: () => { });

                return Task.CompletedTask;
            }));
        }
Ejemplo n.º 12
0
        public void ShowDraft(string subject, string body, bool html, string[] to, string[] cc, string[] bcc)
        {
            var mailer = new MFMailComposeViewController();

            mailer.SetMessageBody(body ?? string.Empty, html);
            mailer.SetSubject(subject ?? string.Empty);
            mailer.SetCcRecipients(cc);
            mailer.SetToRecipients(to);
            mailer.Finished += (s, e) =>
            {
                ((MFMailComposeViewController)s).DismissViewController(true, () => { });
            };
        }
Ejemplo n.º 13
0
        public void ShowDraft(string subject, string body, bool html, string[] to, string[] cc, string[] bcc, IEnumerable<string> attachments)
        {
            var mailer = new MFMailComposeViewController();
            mailer.SetMessageBody(body ?? string.Empty, html);
            mailer.SetSubject(subject ?? string.Empty);
            mailer.SetCcRecipients(cc);
            mailer.SetToRecipients(to);
            mailer.Finished += (s, e) =>
            {
                ((MFMailComposeViewController)s).DismissViewController(true, () => { });
            };

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
        }
Ejemplo n.º 14
0
        public void ComposeEmail(string to, string cc, string subject, string body, bool isHtml)
        {
            if (!MFMailComposeViewController.CanSendMail)
                return;

            _mail = new MFMailComposeViewController();
            _mail.SetMessageBody(body ?? string.Empty, isHtml);
            _mail.SetSubject(subject ?? string.Empty);
            _mail.SetCcRecipients(new[] {cc ?? string.Empty});
            _mail.SetToRecipients(new[] {to ?? string.Empty});
            _mail.Finished += HandleMailFinished;

            _presenter.PresentModalViewController(_mail, true);
        }
Ejemplo n.º 15
0
        public void ComposeEmail(string to, string cc, string subject, string body, bool isHtml)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                return;
            }

            _mail = new MFMailComposeViewController();
            _mail.SetMessageBody(body ?? string.Empty, isHtml);
            _mail.SetSubject(subject ?? string.Empty);
            _mail.SetCcRecipients(new[] { cc ?? string.Empty });
            _mail.SetToRecipients(new[] { to ?? string.Empty });
            _mail.Finished += HandleMailFinished;

            _modalHost.PresentModalViewController(_mail, true);
        }
Ejemplo n.º 16
0
		public void ComposeEmail(string to, string cc, string subject, string body, bool isHtml, byte[] attachment)
		{
			
			if (!MFMailComposeViewController.CanSendMail)
				return;
			
			_mail = new MFMailComposeViewController ();
			_mail.SetMessageBody (body ?? string.Empty, isHtml);
			_mail.SetSubject(subject ?? string.Empty);
			_mail.SetCcRecipients(new [] {cc ?? string.Empty});
			_mail.SetToRecipients(new [] {to ?? string.Empty});
			_mail.AddAttachmentData(NSData.FromArray(attachment), "image/jpeg", "screenshot.jpg");
			_mail.Finished += HandleMailFinished;
			
			_presenter.PresentModalViewController(_mail, true);
		}
Ejemplo n.º 17
0
        private void SendEmailConfirmationJobAccepted(string dbFileName)
        {
            string[] tst = dbFileName.Split(' ');

            long   customerNumber = 0;
            long   jobID          = 0;
            string emailSender    = "";

            try {
                customerNumber = Convert.ToInt64(tst[1]);
                jobID          = Convert.ToInt64(tst [2]);
                emailSender    = tst[4] + "@puratap.com";
            } catch {
            }
            Customer c = _jobs.Customers.Find(customer => customer.CustomerNumber == customerNumber);

            if (c != null)
            {
                var mail = new MFMailComposeViewController();

                Action act = delegate { };

                string msg = String.Format("Dear office,\r\n\r\n I hereby inform you that job {0} for customer {1} has been accepted.", jobID, c.CustomerNumber);

                mail.SetSubject(String.Format("RE: Job accepted -- CN# {0} {1} {2}, job ID {3}", c.CustomerNumber, c.FirstName, c.LastName, jobID));
                mail.SetToRecipients(new string[] { emailSender });
                mail.SetCcRecipients(new string[] { "*****@*****.**" });
                mail.SetMessageBody(msg, false);

                mail.Finished += delegate(object sender, MFComposeResultEventArgs e) {
                    if (e.Result == MFMailComposeResult.Sent)
                    {
                        var sendSuccess = new UIAlertView("", "Mail sent", null, "OK");
                        sendSuccess.Show();
                    }
                    else if (e.Result == MFMailComposeResult.Failed)
                    {
                        var sendFailed = new UIAlertView("Error", "Failed to send message: " + e.Error.Description, null, "OK");
                        sendFailed.Show();
                    }

                    mail.DismissViewController(true, act);
                };

                _tabs.PresentViewController(mail, true, act);
            }
        }
Ejemplo n.º 18
0
        Task <string> SendEMAIL(string message, string[] emailId, string[] cc, string[] bcc, string subject)
        {
            var task = new TaskCompletionSource <string>();

            try
            {
                if (emailId != null)
                {
                    MFMailComposeViewController mailController;
                    if (MFMailComposeViewController.CanSendMail)
                    {
                        mailController = new MFMailComposeViewController();
                        mailController.SetToRecipients(emailId);
                        mailController.SetCcRecipients(cc);
                        mailController.SetBccRecipients(bcc);
                        mailController.SetSubject(subject);
                        var bodyContent = message;

                        mailController.SetMessageBody(bodyContent, true);
                        mailController.Finished += (object s, MFComposeResultEventArgs args) =>
                        {
                            var result = args.Result.ToString();
                            if (result.Equals("Sent"))
                            {
                                task.SetResult("true");
                            }
                            else if (result.Equals("Cancelled"))
                            {
                                task.SetResult("false");
                            }
                            args.Controller.DismissViewController(true, null);
                        };

                        //mailController.Delegate = this;
                        var controller = GetController();
                        controller.PresentViewController(mailController, true, null);
                    }
                }
            }
            catch (Exception ex)
            {
                task.SetResult("false");
            }

            return(task.Task);
        }
Ejemplo n.º 19
0
        private static async Task ComposeEmailWithMFAsync(EmailMessage message)
        {
            if (UIApplication.SharedApplication.KeyWindow?.RootViewController == null)
            {
                throw new InvalidOperationException("Root view controller is null, API called too early in the application lifecycle.");
            }

#if __MACCATALYST__ // catalyst https://github.com/xamarin/xamarin-macios/issues/13935
            throw new InvalidOperationException("Not supported on catalyst (https://github.com/xamarin/xamarin-macios/issues/13935)");
#else
            var controller = new MFMailComposeViewController();

            if (!string.IsNullOrEmpty(message?.Body))
            {
                controller.SetMessageBody(message.Body, true);
            }

            if (!string.IsNullOrEmpty(message?.Subject))
            {
                controller.SetSubject(message.Subject);
            }

            if (message?.To?.Count > 0)
            {
                controller.SetToRecipients(
                    message.To.Select(r => r.Address).ToArray());
            }

            if (message?.CC?.Count > 0)
            {
                controller.SetCcRecipients(
                    message.CC.Select(cc => cc.Address).ToArray());
            }

            if (message?.Bcc?.Count > 0)
            {
                controller.SetBccRecipients(
                    message.Bcc.Select(bcc => bcc.Address).ToArray());
            }

            await UIApplication.SharedApplication.KeyWindow?.RootViewController.PresentViewControllerAsync(controller, true);

            await controller.DismissViewControllerAsync(true);
#endif
        }
Ejemplo n.º 20
0
        /// <summary>
        /// iOS Open the native email control
        /// </summary>
        public void ShowDraft(string subject, string body, string[] to, string[] cc, string[] bcc)
        {
            var mailer = new MFMailComposeViewController();

            mailer.SetMessageBody(body ?? string.Empty, false);
            mailer.SetSubject(subject ?? string.Empty);
            if (cc != null)
            {
                mailer.SetCcRecipients(cc);
            }
            if (bcc != null)
            {
                mailer.SetBccRecipients(bcc);
            }
            mailer.SetToRecipients(to);
            mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
        }
Ejemplo n.º 21
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
                throw new ArgumentNullException("email");

            if (CanSendEmail)
            {
                _mailController = new MFMailComposeViewController();
                _mailController.SetSubject(email.Subject);
                _mailController.SetMessageBody(email.Message, ((EmailMessage) email).IsHtml);
                _mailController.SetToRecipients(email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                    _mailController.SetCcRecipients(email.RecipientsCc.ToArray());

                if (email.RecipientsBcc.Count > 0)
                    _mailController.SetBccRecipients(email.RecipientsBcc.ToArray());

                foreach (var attachment in email.Attachments.Cast<EmailAttachment>())
                {
                    _mailController.AddAttachmentData(NSData.FromStream(attachment.Content),
                        attachment.ContentType, attachment.FileName);
                }

                EventHandler<MFComposeResultEventArgs> handler = null;
                handler = (sender, e) =>
                {
                    _mailController.Finished -= handler;

                    var uiViewController = sender as UIViewController;
                    if (uiViewController == null)
                    {
                        throw new ArgumentException("sender");
                    }

                    uiViewController.DismissViewController(true, () => { });
                };

                _mailController.Finished += handler;

                _mailController.PresentUsingRootViewController();
            }
        }
Ejemplo n.º 22
0
        private void SendEmail(string pathToCsvFile)
        {
            if (MFMailComposeViewController.CanSendMail)
            {
                MFMailComposeViewController mailController = new MFMailComposeViewController();
                mailController.SetToRecipients(new[] { "*****@*****.**" });
                mailController.SetCcRecipients(new [] { "*****@*****.**" });
                mailController.SetSubject("hfghfghfghfg");
                mailController.SetMessageBody("not html ody", false);
                NSData fileData = NSData.FromFile(pathToCsvFile);
                mailController.AddAttachmentData(fileData, "text/plain", "filedata.csv");


                mailController.Finished += (object s, MFComposeResultEventArgs args) =>
                {
                    Console.WriteLine(args.Result.ToString());
                    args.Controller.DismissViewController(true, null);
                };

                this.PresentViewController(mailController, true, null);
            }



            //var email = new Intent(Intent.ActionSend);
            //email.PutExtra(Intent.ExtraEmail, new string[]
            //{
            //        ResourceManager.GetString("send_email_to");
            //});
            //email.PutExtra(Android.Content.Intent.ExtraCc, new string[] {
            //        GetString(Resource.String.send_email_to_cc)
            //    });

            //email.PutExtra(Intent.ExtraSubject, GetString(Resource.String.send_email_subj));

            //var file = new Java.IO.File(pathToCsvFile);
            //email.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file:///" + pathToCsvFile));

            //file.SetReadable(true, false);

            //email.SetType("plain/text");
            //StartActivity(Intent.CreateChooser(email, "Send email..."));
        }
Ejemplo n.º 23
0
        public async Task LaunchMailto(CancellationToken ct, string subject = null, string body = null, string[] to = null, string[] cc = null, string[] bcc = null)
        {
#if !__MACCATALYST__  // catalyst https://github.com/xamarin/xamarin-macios/issues/13935
            if (!MFMailComposeViewController.CanSendMail)
            {
                return;
            }

            var mailController = new MFMailComposeViewController();

            mailController.SetToRecipients(to);
            mailController.SetSubject(subject);
            mailController.SetMessageBody(body, false);
            mailController.SetCcRecipients(cc);
            mailController.SetBccRecipients(bcc);

            var finished = new TaskCompletionSource <object>();
            var handler  = new EventHandler <MFComposeResultEventArgs>((snd, args) => finished.TrySetResult(args));

            try
            {
                mailController.Finished += handler;
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);

                using (ct.Register(() => finished.TrySetCanceled()))
                {
                    await finished.Task;
                }
            }
            finally
            {
                await CoreDispatcher
                .Main
                .RunAsync(CoreDispatcherPriority.High, () =>
                {
                    mailController.Finished -= handler;
                    mailController.DismissViewController(true, null);
                })
                .AsTask(CancellationToken.None);
            }
#endif
        }
Ejemplo n.º 24
0
        private static async Task ComposeEmailWithMFAsync(EmailMessage message)
        {
            if (UIApplication.SharedApplication.KeyWindow?.RootViewController == null)
            {
                throw new InvalidOperationException("Root view controller is null, API called too early in the application lifecycle.");
            }

            var controller = new MFMailComposeViewController();

            if (!string.IsNullOrEmpty(message?.Body))
            {
                controller.SetMessageBody(message.Body, true);
            }

            if (!string.IsNullOrEmpty(message?.Subject))
            {
                controller.SetSubject(message.Subject);
            }

            if (message?.To?.Count > 0)
            {
                controller.SetToRecipients(
                    message.To.Select(r => r.Address).ToArray());
            }

            if (message?.CC?.Count > 0)
            {
                controller.SetCcRecipients(
                    message.CC.Select(cc => cc.Address).ToArray());
            }

            if (message?.Bcc?.Count > 0)
            {
                controller.SetBccRecipients(
                    message.Bcc.Select(bcc => bcc.Address).ToArray());
            }

            await UIApplication.SharedApplication.KeyWindow?.RootViewController.PresentViewControllerAsync(controller, true);

            await controller.DismissViewControllerAsync(true);
        }
Ejemplo n.º 25
0
        static Task PlatformComposeAsync(EmailMessage message)
        {
            // do this first so we can throw as early as possible
            var parentController = Platform.GetCurrentViewController();

            // create the controller
            var controller = new MFMailComposeViewController();

            if (!string.IsNullOrEmpty(message?.Body))
            {
                controller.SetMessageBody(message.Body, message?.BodyFormat == EmailBodyFormat.Html);
            }
            if (!string.IsNullOrEmpty(message?.Subject))
            {
                controller.SetSubject(message.Subject);
            }
            if (message?.To.Count > 0)
            {
                controller.SetToRecipients(message.To.ToArray());
            }
            if (message?.Cc.Count > 0)
            {
                controller.SetCcRecipients(message.Cc.ToArray());
            }
            if (message?.Bcc.Count > 0)
            {
                controller.SetBccRecipients(message.Bcc.ToArray());
            }

            // show the controller
            var tcs = new TaskCompletionSource <bool>();

            controller.Finished += (sender, e) =>
            {
                controller.DismissViewController(true, null);
                tcs.SetResult(e.Result == MFMailComposeResult.Sent);
            };
            parentController.PresentViewController(controller, true, null);

            return(tcs.Task);
        }
Ejemplo n.º 26
0
        public void SendEmail(IEmailMessage email)
        {
            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            if (CanSendEmail)
            {
                MFMailComposeViewController _mailController;
                _mailController = new MFMailComposeViewController();
                _mailController.SetSubject(email.Subject);
                _mailController.SetMessageBody(email.Message, ((EmailMessage)email).IsHtml);
                _mailController.SetToRecipients(email.Recipients.ToArray());

                if (email.RecipientsCc.Count > 0)
                {
                    _mailController.SetCcRecipients(email.RecipientsCc.ToArray());
                }

                if (email.RecipientsBcc.Count > 0)
                {
                    _mailController.SetBccRecipients(email.RecipientsBcc.ToArray());
                }

                foreach (var attachment in email.Attachments.Cast <EmailAttachment>())
                {
                    if (attachment.File == null)
                    {
                        _mailController.AddAttachmentData(NSData.FromFile(attachment.FilePath), attachment.ContentType, attachment.FileName);
                    }
                    else
                    {
                        _mailController.AddAttachmentData(NSData.FromUrl(attachment.File), attachment.ContentType, attachment.FileName);
                    }
                }

                Settings.EmailPresenter.PresentMailComposeViewController(_mailController);
            }
        }
Ejemplo n.º 27
0
        public virtual Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var mailer = new MFMailComposeViewController();

            mailer.SetToRecipients(emailMessage.To.ToArray());
            mailer.SetCcRecipients(emailMessage.Cc.ToArray());
            mailer.SetBccRecipients(emailMessage.Bcc.ToArray());

            mailer.SetSubject(emailMessage.Subject);
            mailer.SetMessageBody(emailMessage.Body, emailMessage.IsHTML);

            mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);

            return(Task.FromResult(true));
        }
 public override void ViewDidLoad ()
 {
     base.ViewDidLoad ();
     
     mailButton.TouchUpInside += (o, e) =>
     {
         if (MFMailComposeViewController.CanSendMail) {
             _mail = new MFMailComposeViewController ();
             _mail.SetToRecipients (new string[] { "*****@*****.**", "*****@*****.**" });
             _mail.SetCcRecipients (new string[] { "*****@*****.**" });
             _mail.SetBccRecipients (new string[] { "*****@*****.**" });
             _mail.SetMessageBody ("body of the email", false);
             _mail.SetSubject ("test email");
             _mail.Finished += HandleMailFinished;
             this.PresentModalViewController (_mail, true);
             
         } else {
             var alert = new UIAlertView ("Mail Alert", "Mail Not Sent", null, "Mail Demo", null);
             alert.Show ();
         }
     };
 }
Ejemplo n.º 29
0
        public virtual Task ComposeEmail(IEmailMessage emailMessage)
        {
            if (!CanComposeEmail)
            {
                throw new FeatureNotAvailableException();
            }

            var mailer = new MFMailComposeViewController();

            mailer.SetToRecipients(emailMessage.To.ToArray());
            mailer.SetCcRecipients(emailMessage.Cc.ToArray());
            mailer.SetBccRecipients(emailMessage.Bcc.ToArray());

            mailer.SetSubject(emailMessage.Subject);
            mailer.SetMessageBody(emailMessage.Body, emailMessage.IsHTML);

            mailer.Finished += (s, e) => ((MFMailComposeViewController) s).DismissViewController(true, () => { });

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);

            return Task.FromResult(true);
        }
Ejemplo n.º 30
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            mailButton.TouchUpInside += (o, e) =>
            {
                if (MFMailComposeViewController.CanSendMail)
                {
                    _mail = new MFMailComposeViewController();
                    _mail.SetToRecipients(new string[] { "*****@*****.**", "*****@*****.**" });
                    _mail.SetCcRecipients(new string[] { "*****@*****.**" });
                    _mail.SetBccRecipients(new string[] { "*****@*****.**" });
                    _mail.SetMessageBody("body of the email", false);
                    _mail.SetSubject("test email");
                    _mail.Finished += HandleMailFinished;
                    this.PresentModalViewController(_mail, true);
                }
                else
                {
                    var alert = new UIAlertView("Mail Alert", "Mail Not Sent", null, "Mail Demo", null);
                    alert.Show();
                }
            };
        }
Ejemplo n.º 31
0
        private void ShowMailComposer(object emailObject)
        {
            SystemLogger.Log(SystemLogger.Module.PLATFORM,"ShowMailComposer... ");
            EmailData emailData = (EmailData)emailObject;

            UIApplication.SharedApplication.InvokeOnMainThread (delegate {

                MFMailComposeViewController vcMail = new MFMailComposeViewController ();

                // To
                if (emailData.ToRecipientsAsString.Length > 0) {
                    vcMail.SetToRecipients (emailData.ToRecipientsAsString);
                }
                // Cc
                if (emailData.CcRecipientsAsString.Length > 0) {
                    vcMail.SetCcRecipients (emailData.CcRecipientsAsString);
                }
                // Bcc
                if (emailData.BccRecipientsAsString.Length > 0) {
                    vcMail.SetBccRecipients (emailData.BccRecipientsAsString);
                }
                // Subject
                if (emailData.Subject != null) {
                    vcMail.SetSubject (emailData.Subject);
                }
                // Body
                bool IsHtml = "text/html".Equals (emailData.MessageBodyMimeType);
                if (emailData.MessageBody != null) {
                    vcMail.SetMessageBody (emailData.MessageBody, IsHtml);
                }
                // Attachement
                if (emailData.Attachment != null) {
                    foreach (AttachmentData attachment in emailData.Attachment) {
                        try {

                            NSData data = null;
                            if(attachment.Data == null || attachment.Data.Length == 0) {

                                IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance ().GetService ("file");
                                string fullPath = Path.Combine(fileSystemService.GetDirectoryRoot().FullName, attachment.ReferenceUrl);
                                data = NSData.FromFile(fullPath);
                                if(attachment.FileName == null || attachment.FileName.Length == 0) {
                                    attachment.FileName = Path.GetFileName(attachment.ReferenceUrl);
                                }
                            } else {
                                data = NSData.FromArray (attachment.Data);
                            }
                            if(data != null) {
                                vcMail.AddAttachmentData (data, attachment.MimeType, attachment.FileName);
                            }
                        } catch (Exception e) {
                            SystemLogger.Log (SystemLogger.Module.PLATFORM, "Error adding attachment to Mail Composer.", e);
                        }
                    }
                }

                vcMail.Finished += HandleMailFinished;

                // method reviewed (15 April 2014).
                vcMail.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
                IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().PresentViewController(vcMail, true, null);

                // deprecated --> IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().PresentModalViewController (vcMail, true);

            });
        }
Ejemplo n.º 32
0
        public bool StartMailer(string title, string body, string[] to, string[] cc, string[] bcc, string filePath, ref string err)
        {
            //初期化
            err = String.Empty;
            string ret = String.Empty;

            if (!MFMailComposeViewController.CanSendMail)
            {                  //メール送信が可能かどうかの確認
                err = "この端末はメールが送信可能な状態にありません。";
                return(false); //メール送信不能
            }

            var mail = new MFMailComposeViewController();    //インスタンスの生成

            //項目セット
            if (to != null && to.Length > 0)
            {
                mail.SetToRecipients(to);
            }
            if (cc != null && cc.Length > 0)
            {
                mail.SetCcRecipients(cc);
            }
            if (bcc != null && bcc.Length > 0)
            {
                mail.SetBccRecipients(bcc);
            }
            mail.SetSubject(title);
            mail.SetMessageBody(body, false);

            /*
             * if (!String.IsNullOrEmpty(filePath))
             * {
             *  //ファイル添付あり
             *
             *  //拡張子
             *  string extention = System.IO.Path.GetExtension(filePath.ToLower()).Replace(".", "");
             *  if (String.IsNullOrEmpty(extention))
             *  {
             *      //拡張子が取得できない場合はテキストで開く
             *      extention = "txt";
             *  }
             *  //mime type
             *  string mimetype = MimeTypeUtility.GetMimeType(extention);
             *
             *  NSData data = NSData.FromFile(filePath);
             *  mail.AddAttachmentData(data, mimetype, System.IO.Path.GetFileName(filePath));
             * }
             */

            mail.Finished += (o, args) => {
                //送信処理終了時のイベント
                ret = args.Result.ToString();                      // srgs.Result:戻り値
                args.Controller.DismissViewController(true, null); //Eメール画面の消去
            };

            //メーラー起動
            var view = UIApplication.SharedApplication.KeyWindow.RootViewController;

            view.PresentViewController(mail, true, null);
            err = ret;
            return(true);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Launches the email application with a new message displayed.
        /// </summary>
        /// <param name="message">The email message that is displayed when the email application is launched.</param>
        /// <returns>An asynchronous action used to indicate when the operation has completed.</returns>
        public static Task ShowComposeNewEmailAsync(EmailMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException();
            }

            return(Task.Run(() =>
            {
#if __ANDROID__
                Intent emailIntent = new Intent(Intent.ActionSendto);
                //emailIntent.SetType("message/rfc822");
                emailIntent.SetData(Android.Net.Uri.Parse("mailto:"));
                emailIntent.PutExtra(Intent.ExtraEmail, RecipientsToStringArray(message.To));
                if (message.CC.Count > 0)
                {
                    emailIntent.PutExtra(Intent.ExtraCc, RecipientsToStringArray(message.CC));
                }

                if (message.Bcc.Count > 0)
                {
                    emailIntent.PutExtra(Intent.ExtraBcc, RecipientsToStringArray(message.Bcc));
                }
                emailIntent.PutExtra(Intent.ExtraSubject, message.Subject);
                emailIntent.PutExtra(Intent.ExtraText, message.Body);
                emailIntent.AddFlags(ActivityFlags.ClearWhenTaskReset);
                Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(emailIntent);
                //Platform.Android.ContextManager.Context.StartActivity(emailIntent);
#elif __IOS__
                try
                {
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        MFMailComposeViewController mcontroller = new MFMailComposeViewController();
                        mcontroller.Finished += mcontroller_Finished;

                        mcontroller.SetToRecipients(BuildRecipientArray(message.To));
                        mcontroller.SetCcRecipients(BuildRecipientArray(message.CC));
                        mcontroller.SetBccRecipients(BuildRecipientArray(message.Bcc));
                        mcontroller.SetSubject(message.Subject);
                        mcontroller.SetMessageBody(message.Body, false);
                        foreach (EmailAttachment a in message.Attachments)
                        {
                            NSData dataBuffer = NSData.FromFile(a.Data.Path);
                            mcontroller.AddAttachmentData(dataBuffer, a.MimeType, a.FileName);
                        }

                        UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        while (currentController.PresentedViewController != null)
                        {
                            currentController = currentController.PresentedViewController;
                        }

                        currentController.PresentViewController(mcontroller, true, null);
                    });
                }
                catch
                {
                    throw new PlatformNotSupportedException();
                }
#elif WINDOWS_UWP || WINDOWS_PHONE_APP
                Windows.ApplicationModel.Email.EmailMessage em = new Windows.ApplicationModel.Email.EmailMessage()
                {
                    Subject = message.Subject, Body = message.Body
                };
                foreach (EmailRecipient r in message.To)
                {
                    em.To.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach (EmailRecipient r in message.CC)
                {
                    em.CC.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach (EmailRecipient r in message.Bcc)
                {
                    em.Bcc.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach (EmailAttachment a in message.Attachments)
                {
                    em.Attachments.Add(new Windows.ApplicationModel.Email.EmailAttachment(a.FileName, (Windows.Storage.StorageFile)a.Data));
                }

                return Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(em).AsTask();
#elif WINDOWS_APP || __MAC__
                /*if (_type10 != null)
                 * {
                 *
                 * }
                 * else
                 * {*/
                // build URI

                // build a uri
                StringBuilder sb = new StringBuilder();
                bool firstParameter = true;

                if (message.To.Count == 0)
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    sb.Append("mailto:" + FormatRecipientCollection(message.To));
                }

                if (message.CC.Count > 0)
                {
                    if (firstParameter)
                    {
                        sb.Append("?");
                        firstParameter = false;
                    }
                    else
                    {
                        sb.Append("&");
                    }

                    sb.Append("cc=" + FormatRecipientCollection(message.CC));
                }

                if (message.Bcc.Count > 0)
                {
                    if (firstParameter)
                    {
                        sb.Append("?");
                        firstParameter = false;
                    }
                    else
                    {
                        sb.Append("&");
                    }

                    sb.Append("bbc=" + FormatRecipientCollection(message.Bcc));
                }

                if (!string.IsNullOrEmpty(message.Subject))
                {
                    if (firstParameter)
                    {
                        sb.Append("?");
                        firstParameter = false;
                    }
                    else
                    {
                        sb.Append("&");
                    }

                    sb.Append("subject=" + Uri.EscapeDataString(message.Subject));
                }

                if (!string.IsNullOrEmpty(message.Body))
                {
                    if (firstParameter)
                    {
                        sb.Append("?");
                        firstParameter = false;
                    }
                    else
                    {
                        sb.Append("&");
                    }

                    sb.Append("body=" + Uri.EscapeDataString(message.Body));
                }

                InTheHand.System.Launcher.LaunchUriAsync(new Uri(sb.ToString()));
                //}
#elif WINDOWS_PHONE
                // On Phone 8.0 use the email compose dialog
                EmailComposeTask task = new EmailComposeTask();

                if (!string.IsNullOrEmpty(message.Subject))
                {
                    task.Subject = message.Subject;
                }

                if (!string.IsNullOrEmpty(message.Body))
                {
                    task.Body = message.Body;
                }

                if (message.To.Count == 0)
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    task.To = FormatRecipientCollection(message.To);
                }

                if (message.CC.Count > 0)
                {
                    task.Cc = FormatRecipientCollection(message.CC);
                }

                if (message.Bcc.Count > 0)
                {
                    task.Bcc = FormatRecipientCollection(message.Bcc);
                }

                task.Show();
#elif WIN32
                ShowComposeNewEmailImpl(message);
#else
                throw new PlatformNotSupportedException();
#endif
            }));
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Launches the email application with a new message displayed.
        /// </summary>
        /// <param name="message">The email message that is displayed when the email application is launched.</param>
        /// <returns>An asynchronous action used to indicate when the operation has completed.</returns>
        public static Task ShowComposeNewEmailAsync(EmailMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException();
            }

            return Task.Run(() =>
            {
#if __ANDROID__
                Intent emailIntent = new Intent(Intent.ActionSendto);
                //emailIntent.SetType("message/rfc822");
                emailIntent.SetData(Android.Net.Uri.Parse("mailto:"));
                emailIntent.PutExtra(Intent.ExtraEmail, RecipientsToStringArray(message.To));
                if (message.CC.Count > 0)
                {
                    emailIntent.PutExtra(Intent.ExtraCc, RecipientsToStringArray(message.CC));
                }

                if (message.Bcc.Count > 0)
                {
                    emailIntent.PutExtra(Intent.ExtraBcc, RecipientsToStringArray(message.Bcc));
                }
                emailIntent.PutExtra(Intent.ExtraSubject, message.Subject);
                emailIntent.PutExtra(Intent.ExtraText, message.Body);
                emailIntent.AddFlags(ActivityFlags.ClearWhenTaskReset);
                Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(emailIntent);
                //Platform.Android.ContextManager.Context.StartActivity(emailIntent);           
#elif __IOS__
                try
                {
                    UIApplication.SharedApplication.InvokeOnMainThread(() =>
                    {
                        MFMailComposeViewController mcontroller = new MFMailComposeViewController();
                        mcontroller.Finished += mcontroller_Finished;

                        mcontroller.SetToRecipients(BuildRecipientArray(message.To));
                        mcontroller.SetCcRecipients(BuildRecipientArray(message.CC));
                        mcontroller.SetBccRecipients(BuildRecipientArray(message.Bcc));
                        mcontroller.SetSubject(message.Subject);
                        mcontroller.SetMessageBody(message.Body, false);
                        foreach (EmailAttachment a in message.Attachments)
                        {
                            NSData dataBuffer = NSData.FromFile(a.Data.Path);
                            mcontroller.AddAttachmentData(dataBuffer, a.MimeType, a.FileName);
                        }

                        UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        while (currentController.PresentedViewController != null)
                            currentController = currentController.PresentedViewController;

                        currentController.PresentViewController(mcontroller, true, null);
                    });
                }
                catch
                {
                    throw new PlatformNotSupportedException();
                }
#elif WINDOWS_UWP || WINDOWS_PHONE_APP
                Windows.ApplicationModel.Email.EmailMessage em = new Windows.ApplicationModel.Email.EmailMessage() { Subject = message.Subject, Body = message.Body };
                foreach(EmailRecipient r in message.To)
                {
                    em.To.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach(EmailRecipient r in message.CC)
                {
                    em.CC.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach (EmailRecipient r in message.Bcc)
                {
                    em.Bcc.Add(new Windows.ApplicationModel.Email.EmailRecipient(r.Address, r.Name));
                }
                foreach(EmailAttachment a in message.Attachments)
                {
                    em.Attachments.Add(new Windows.ApplicationModel.Email.EmailAttachment(a.FileName, (Windows.Storage.StorageFile)a.Data));
                }

                return Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(em).AsTask();
#elif WINDOWS_APP
                /*if (_type10 != null)
                {

                }
                else
                {*/
                    // build URI for Windows Store platform

                    // build a uri
                    StringBuilder sb = new StringBuilder();
                    bool firstParameter = true;

                    if (message.To.Count == 0)
                    {
                        throw new InvalidOperationException();
                    }
                    else
                    {
                        sb.Append("mailto:" + FormatRecipientCollection(message.To));
                    }

                    if (message.CC.Count > 0)
                    {
                        if (firstParameter)
                        {
                            sb.Append("?");
                            firstParameter = false;
                        }
                        else
                        {
                            sb.Append("&");
                        }

                        sb.Append("cc=" + FormatRecipientCollection(message.CC));
                    }

                    if (message.Bcc.Count > 0)
                    {
                        if (firstParameter)
                        {
                            sb.Append("?");
                            firstParameter = false;
                        }
                        else
                        {
                            sb.Append("&");
                        }

                        sb.Append("bbc=" + FormatRecipientCollection(message.Bcc));
                    }

                    if (!string.IsNullOrEmpty(message.Subject))
                    {
                        if (firstParameter)
                        {
                            sb.Append("?");
                            firstParameter = false;
                        }
                        else
                        {
                            sb.Append("&");
                        }

                        sb.Append("subject=" + Uri.EscapeDataString(message.Subject));
                    }

                    if (!string.IsNullOrEmpty(message.Body))
                    {
                        if (firstParameter)
                        {
                            sb.Append("?");
                            firstParameter = false;
                        }
                        else
                        {
                            sb.Append("&");
                        }

                        sb.Append("body=" + Uri.EscapeDataString(message.Body));
                    }

                    Windows.System.Launcher.LaunchUriAsync(new Uri(sb.ToString()));
                //}
#elif WINDOWS_PHONE
                // On Phone 8.0 use the email compose dialog
                EmailComposeTask task = new EmailComposeTask();

                if (!string.IsNullOrEmpty(message.Subject))
                {
                    task.Subject = message.Subject;
                }

                if (!string.IsNullOrEmpty(message.Body))
                {
                    task.Body = message.Body;
                }

                if (message.To.Count == 0)
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    task.To = FormatRecipientCollection(message.To);
                }

                if (message.CC.Count > 0)
                {
                    task.Cc = FormatRecipientCollection(message.CC);
                }

                if (message.Bcc.Count > 0)
                {
                    task.Bcc = FormatRecipientCollection(message.Bcc);
                }

                task.Show();
#else
                throw new PlatformNotSupportedException();
#endif
            });
        }
Ejemplo n.º 35
0
        private void ShowMailComposer(object emailObject)
        {
            SystemLogger.Log(SystemLogger.Module.PLATFORM, "ShowMailComposer... ");
            EmailData emailData = (EmailData)emailObject;


            UIApplication.SharedApplication.InvokeOnMainThread(delegate {
                MFMailComposeViewController vcMail = new MFMailComposeViewController();

                // To
                if (emailData.ToRecipientsAsString.Length > 0)
                {
                    vcMail.SetToRecipients(emailData.ToRecipientsAsString);
                }
                // Cc
                if (emailData.CcRecipientsAsString.Length > 0)
                {
                    vcMail.SetCcRecipients(emailData.CcRecipientsAsString);
                }
                // Bcc
                if (emailData.BccRecipientsAsString.Length > 0)
                {
                    vcMail.SetBccRecipients(emailData.BccRecipientsAsString);
                }
                // Subject
                if (emailData.Subject != null)
                {
                    vcMail.SetSubject(emailData.Subject);
                }
                // Body
                bool IsHtml = "text/html".Equals(emailData.MessageBodyMimeType);
                if (emailData.MessageBody != null)
                {
                    vcMail.SetMessageBody(emailData.MessageBody, IsHtml);
                }
                // Attachement
                if (emailData.Attachment != null)
                {
                    foreach (AttachmentData attachment in emailData.Attachment)
                    {
                        try {
                            NSData data = null;
                            if (attachment.Data == null || attachment.Data.Length == 0)
                            {
                                IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance().GetService("file");
                                string fullPath = Path.Combine(fileSystemService.GetDirectoryRoot().FullName, attachment.ReferenceUrl);
                                data            = NSData.FromFile(fullPath);
                                if (attachment.FileName == null || attachment.FileName.Length == 0)
                                {
                                    attachment.FileName = Path.GetFileName(attachment.ReferenceUrl);
                                }
                            }
                            else
                            {
                                data = NSData.FromArray(attachment.Data);
                            }
                            if (data != null)
                            {
                                vcMail.AddAttachmentData(data, attachment.MimeType, attachment.FileName);
                            }
                        } catch (Exception e) {
                            SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error adding attachment to Mail Composer.", e);
                        }
                    }
                }

                vcMail.Finished += HandleMailFinished;

                // method reviewed (15 April 2014).
                vcMail.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
                IPhoneServiceLocator.CurrentDelegate.MainUIViewController().PresentViewController(vcMail, true, null);

                // deprecated --> IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().PresentModalViewController (vcMail, true);
            });
        }