Ejemplo n.º 1
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.º 2
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.º 3
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;
            }));
        }
        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.º 5
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.º 6
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();
            }
        }
        /// <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.º 8
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.º 9
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.º 10
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.º 11
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);
            }
        }
 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.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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
            }));
        }