Ejemplo n.º 1
0
        public void AddPictureAttachments(MFMailComposeViewController mailContr, bool items)
        {
            var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
            IList<LagerObject> storeting = AppDelegate.dao.LoadBigItems();
            foreach(LagerObject lobj in storeting){
                if (!string.IsNullOrEmpty (lobj.imageFileName)) {
                    string jpg = lobj.Name + ".jpg";
                    string filename = System.IO.Path.Combine (documentsDirectory, lobj.imageFileName);
                    UIImage image = UIImage.FromFile (filename);
                    NSData imagedata = image.AsJPEG ();
                    mailContr.AddAttachmentData (imagedata, "image/jpeg", jpg);
                }
            }

            if(items){
                IList<Item> itemsList = AppDelegate.dao.GetAllItems();
                foreach(Item it in itemsList){
                    if (!string.IsNullOrEmpty (it.ImageFileName)) {
                        string jpg = it.Name + ".jpg";
                        string filename = System.IO.Path.Combine (documentsDirectory, it.ImageFileName);
                        UIImage image = UIImage.FromFile (filename);
                        NSData imagedata = image.AsJPEG ();
                        mailContr.AddAttachmentData (imagedata, "image/jpeg", jpg);
                    }
                }
            }
        }
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;
            }));
        }
Ejemplo n.º 4
0
        public void SendEmail(string attachment)
        {
            MFMailComposeViewController mailController;

            if (MFMailComposeViewController.CanSendMail)
            {
                mailController = new MFMailComposeViewController();
                //mailController.SetToRecipients(new string[] { "*****@*****.**" });
                mailController.SetSubject("Mileage Report");
                mailController.SetMessageBody("Mileage report exported from MileageApp", false);

                var fileHelper = new FileHelper();
                var stream     = fileHelper.ReadFileContents(attachment);
                mailController.AddAttachmentData(NSData.FromStream(stream), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "expense report.xlsx");

                mailController.Finished += (object sender, MFComposeResultEventArgs e) =>
                {
                    // can set pass in an action to call when done
                    //if (completed != null)
                    //   completed(e.Result == MFMailComposeResult.Sent);
                    e.Controller.DismissViewController(true, null);

                    // is this the right place to close this? not sure if it copies the stream over before this
                    stream.Close();
                };

                // http://stackoverflow.com/questions/24136464/access-viewcontroller-in-dependencyservice-to-present-mfmailcomposeviewcontrolle
                //var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
                //var navcontroller = rootController as UINavigationController;
                //if (navcontroller != null)
                //   rootController = navcontroller.VisibleViewController;
                //rootController.PresentViewController(mailController, true, null);
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
            }
        }
Ejemplo n.º 5
0
        public Task OpenEmailManager(string[] emails, string subject, string text, string[] attachments)
        {
            var tcs = new TaskCompletionSource<bool>();
            if (MFMailComposeViewController.CanSendMail)
            {
                var c = new MFMailComposeViewController();
                c.SetToRecipients(emails);
                c.SetSubject(subject ?? "");
                c.SetMessageBody(text ?? "", false);
                foreach (string attachment in attachments)
                {
                    NSData data = NSData.FromFile(attachment);
                    if (data != null)
                        c.AddAttachmentData(data, GetMimeType(attachment), Path.GetFileName(attachment));
                }

                _application.RootController.PresentViewController(c, true, null);
                c.Finished += (sender, e) =>
                {
                    tcs.SetResult(e.Result == MFMailComposeResult.Sent);
                    _application.InvokeOnMainThread(() => e.Controller.DismissViewController(true, null));
                };
            }
            else
            {
                var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
                alert.Clicked += (sender, args) => tcs.SetResult(false);
                alert.Show();
            }
            return tcs.Task;
        }
Ejemplo n.º 6
0
 public Task<bool> SendReport(IReport report)
 {
     var tcs = new TaskCompletionSource<bool>();
     if (MFMailComposeViewController.CanSendMail)
     {
         var c = new MFMailComposeViewController();
         c.SetSubject(report.Title);
         c.SetToRecipients(new[] {_settings.DevelopersEmail});
         c.SetMessageBody(report.Body, false);
         NSData data = new NSString(report.Attachment).DataUsingEncoding(NSStringEncoding.UTF8);
         c.AddAttachmentData(data, "text/xml", "info.xml");
         _application.RootController.PresentViewController(c, true, null);
         c.Finished += (sender, e) =>
         {
             tcs.SetResult(e.Result == MFMailComposeResult.Sent);
             e.Controller.DismissViewController(true, null);
         };
     }
     else
     {
         var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
         alert.Clicked += (sender, args) => tcs.SetResult(false);
         alert.Show();
     }
     return tcs.Task;
 }
Ejemplo n.º 7
0
        private void EmailButtonTouchDown(object sender, EventArgs e)
        {
            if (File.Exists(Settings.Current.LogFile))
            {
                if (MFMailComposeViewController.CanSendMail)
                {
                    NSData data = NSData.FromFile(Settings.Current.LogFile);

                    MFMailComposeViewController mailController = new MFMailComposeViewController();
                    mailController.SetSubject("Really simple iPhone error report");
                    mailController.SetToRecipients(new string[] { "*****@*****.**" });
                    mailController.SetMessageBody("Really simple error report", false);
                    mailController.AddAttachmentData(data, "text/plain", "error.log");
                    mailController.Finished += HandleMailFinished;
                    this.PresentModalViewController(mailController, true);
                }
                else
                {
                    ModalDialog.Alert("No email account found", "Please configure an email account before sending an error report");
                }
            }
            else
            {
                ModalDialog.Alert("No log file was found", "The error log was empty. Please try sending this again after the error occurs.");
            }
        }
Ejemplo n.º 8
0
        public static void OpenSender(string path, Action success, Action <string> error)
        {
#if __IOS__
            string[] split = path.Split('/');
            string   name  = split[split.Length - 1];

            var stream = new MemoryStream(FileUtils.PathToByteData(path));

            NSData data = NSData.FromStream(stream);

            try
            {
                MFMailComposeViewController controller = new MFMailComposeViewController();

                controller.SetSubject("Style: " + name);
                controller.SetMessageBody("Date: " + DateTime.Now.ToString("F"), false);
                controller.AddAttachmentData(data, "application/zip", name);

                controller.Finished += (object sender, MFComposeResultEventArgs e) =>
                {
                    string message = "";

                    if (e.Result == MFMailComposeResult.Sent)
                    {
                        message = "Mail sent";
                        success();
                    }
                    else if (e.Result == MFMailComposeResult.Failed)
                    {
                        message = "Failed :" + e.Error;
                    }
                    else if (e.Result == MFMailComposeResult.Cancelled)
                    {
                        message = "Cancelled";
                    }
                    else if (e.Result == MFMailComposeResult.Saved)
                    {
                        message = "Saved";
                        success();
                    }

                    Toast.Show(message, new BaseView());
                    controller.DismissViewController(true, null);
                };

                Controller.PresentViewController(controller, true, null);
            }
            catch
            {
                //error("You don't seem to have any mail clients set up");
            }
#elif __ANDROID__
            Intent intent = new Intent(Intent.ActionSend);
            intent.SetType("application/zip");

            intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(path));

            Context.StartActivity(Intent.CreateChooser(intent, "Share zip"));
#endif
        }
Ejemplo n.º 9
0
        public static void Compose(string url)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                return;
            }

            MailTo mailTo = MailTo.ParseUrl(url);

            var mailComposer = new MFMailComposeViewController();

            mailComposer.MailComposeDelegate = new MailComposeDelegate();
            mailComposer.SetToRecipients(mailTo.EmailTo.ToArray());
            mailComposer.SetSubject(mailTo.EmailSubject);
            mailComposer.SetMessageBody(mailTo.EmailBody, true);

            foreach (var attachment in mailTo.EmailAttachments)
            {
                string path = attachment.Filename;
                if (!File.Exists(path))
                {
                    path = Path.Combine(TouchFactory.Instance.DataPath, attachment.Filename);
                }

                NSData data = NSData.FromFile(path);
                if (data != null)
                {
                    mailComposer.AddAttachmentData(data, attachment.MimeType, attachment.Filename);
                }
            }

            ModalManager.EnqueueModalTransition(TouchFactory.Instance.TopViewController, mailComposer, true);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            tv.BecomeFirstResponder();

            toolbar.Items[0].Clicked += (o, s) =>
            {
                string text    = tv.Text;
                NSData pdfData = CreatePDF(text, 500f, 700f);

                if (MFMailComposeViewController.CanSendMail)
                {
                    _mail = new MFMailComposeViewController();
                    _mail.SetMessageBody(tv.Text, false);
                    _mail.AddAttachmentData(pdfData, "text/x-pdf", "test.pdf");
                    _mail.Finished += HandleMailFinished;
                    this.PresentModalViewController(_mail, true);
                }
                else
                {
                    UIAlertView alert = new UIAlertView("App", "Could not send mail.", null, "OK", null);
                    alert.Show();
                }
            };

            toolbar.Items[1].Clicked += (o, s) =>
            {
                _pdf = new PDFViewController(tv.Text);
                this.PresentModalViewController(_pdf, true);
            };
        }
Ejemplo n.º 11
0
 void SendToEmail(string title, string text, string attachment, Action onSuccess, Action onFail)
 {
     if (MFMailComposeViewController.CanSendMail)
     {
         MFMailComposeViewController c = new MFMailComposeViewController();
         c.SetSubject(title);
         c.SetToRecipients(new string[] { _settings.DevelopersEmail });
         c.SetMessageBody(text, false);
         NSData data = new NSString(attachment).DataUsingEncoding(NSStringEncoding.UTF8);
         c.AddAttachmentData(data, "text/xml", "info.xml");
         _application.RootController.PresentViewController(c, true, null);
         c.Finished += (object sender, MFComposeResultEventArgs e) => {
             if (e.Result == MFMailComposeResult.Sent)
             {
                 onSuccess();
             }
             else
             {
                 onFail();
             }
             e.Controller.DismissViewController(true, null);
         };
     }
     else
     {
         UIAlertView alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
         alert.Show();
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Use this method to compose mail
        /// </summary>
        /// <param name="fileName">string type of parameter fileName</param>
        /// <param name="recipients">string type of parameter recipients</param>
        /// <param name="subject">string type of parameter subject</param>
        /// <param name="messagebody">string type of parameter message body</param>
        /// <param name="stream">MemoryStream type parameter stream</param>
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream stream)
        {
            if (MFMailComposeViewController.CanSendMail)
            {
                var mailer = new MFMailComposeViewController();
                mailer.SetMessageBody(messagebody ?? string.Empty, false);
                mailer.SetSubject(subject ?? subject);
                mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { });

                string exception = string.Empty;
                string path      = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                string filePath  = Path.Combine(path, fileName);
                try
                {
                    FileStream fileStream = File.Open(filePath, FileMode.Create);
                    stream.Position = 0;
                    stream.CopyTo(fileStream);
                    fileStream.Flush();
                    fileStream.Close();
                }
                catch (Exception e)
                {
                    exception = e.ToString();
                }

                mailer.AddAttachmentData(NSData.FromFile(filePath), this.GetMimeType(fileName), Path.GetFileName(fileName));
                UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }

                vc.PresentViewController(mailer, true, null);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Shows the native MFMailComposeViewController to send an email.
        /// Raises MailCompleted event when completed.</summary>
        ///
        /// <param name="recipients"> An array of strings representing the email addresses of the recipients.</param>
        /// <param name="subject"> The subject of the email.</param>
        /// <param name="body"> The body of the email.</param>
        /// <param name="bodyIsHTML"> True if the body is HTML; false otherwise.</param>
        /// <param name="image"> The image to attach to the email.</param>
        /// <param name="checkServiceAvailable"> Whether to check if the service is available first.</param>
        /// <returns> True if it is able to show the native view controller; false if it cannot send email.</returns>
        public static bool Mail(string[] recipients, string subject, string body, bool bodyIsHTML, UIImage image, bool checkServiceAvailable)
        {
            if (checkServiceAvailable && !MFMailComposeViewController.CanSendMail())
            {
                return(false);
            }

            var vc = new MFMailComposeViewController();

            if (vc.IsNil)
            {
                return(false);
            }

            vc.mailComposeDelegate = MailComposeViewControllerDelegate.instance;
            vc.SetToRecipients(recipients);
            vc.SetSubject(subject);
            vc.SetMessageBody(body, bodyIsHTML);

            if (image != null)
            {
                var nsdata = image.PNGRepresentation();
                vc.AddAttachmentData(nsdata, "image/png", "image.png");
            }

            UIApplication.deviceRootViewController.PresentViewController(vc, true, null);
            return(true);
        }
Ejemplo n.º 14
0
        public override Task ShareFileAsync(string path, string subject, string mimeType)
        {
            return SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async () =>
            {
                if (!MFMailComposeViewController.CanSendMail)
                {
                    await FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
                    return;
                }

                NSData data = NSData.FromUrl(NSUrl.FromFilename(path));

                if (data == null)
                {
                    await FlashNotificationAsync("No file to share.");
                    return;
                }

                MFMailComposeViewController mailer = new MFMailComposeViewController();
                mailer.SetSubject(subject);
                mailer.AddAttachmentData(data, mimeType, Path.GetFileName(path));
                mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
            });
        }
Ejemplo n.º 15
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.º 16
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.º 17
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.º 18
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.º 19
0
    // Use this for initialization
    void Start()
    {
        // create some arbitary binary data. or load from existing location
        FileStream someFile = new FileStream(Application.temporaryCachePath + "/someFile.bin", FileMode.Create);

        someFile.WriteByte(0x42);
        someFile.Close();

        _mailController = new MFMailComposeViewController();

        _mailControllerDelegate             = new MyMFMailComposeViewControllerDelegate();
        _mailController.mailComposeDelegate = _mailControllerDelegate;

        _mailController.SetToRecipients(new string[] { "*****@*****.**" });
        _mailController.SetSubject("well hello");
        _mailController.SetMessageBody("just testing attachments", false);

        _mailController.AddAttachmentData(
            new NSData(Application.temporaryCachePath + "/someFile.bin"),
            "application/octet-stream",
            "someFile.bin"
            );

        UIApplication.deviceRootViewController.PresentViewController(_mailController, true, null);
    }
Ejemplo n.º 20
0
        public Task <bool> SendReport(IReport report)
        {
            var tcs = new TaskCompletionSource <bool>();

            if (MFMailComposeViewController.CanSendMail)
            {
                var c = new MFMailComposeViewController();
                c.SetSubject(report.Title);
                c.SetToRecipients(new[] { _settings.DevelopersEmail });
                c.SetMessageBody(report.Body, false);
                NSData data = new NSString(report.Attachment).DataUsingEncoding(NSStringEncoding.UTF8);
                c.AddAttachmentData(data, "text/xml", "info.xml");
                _application.RootController.PresentViewController(c, true, null);
                c.Finished += (sender, e) =>
                {
                    tcs.SetResult(e.Result == MFMailComposeResult.Sent);
                    e.Controller.DismissViewController(true, null);
                };
            }
            else
            {
                var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
                alert.Clicked += (sender, args) => tcs.SetResult(false);
                alert.Show();
            }
            return(tcs.Task);
        }
Ejemplo n.º 21
0
        public void SendEmail(string[] toRecipients, string subject, string text = null, FileUri[] attachments = null)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                throw new InvalidOperationException("System can not send email.");
            }

            MFMailComposeViewController mailController = new MFMailComposeViewController();

            mailController.SetToRecipients(toRecipients);
            mailController.SetSubject(subject);
            mailController.SetMessageBody(text, false);
            mailController.Finished += (sender, e) => ((UIViewController)sender).DismissViewController(true, null);

            if (attachments != null &&
                attachments.Length > 0)
            {
                attachments
                .ToList()
                .ForEach(a =>
                {
                    mailController.AddAttachmentData(
                        NSData.FromUrl(a.ToNSUrl()),
                        "application/octet-stream",
                        Path.GetFileName(a.AbsolutePath));
                });
            }

            UIApplication.SharedApplication
            .Windows[0]
            .RootViewController
            .PresentViewController(mailController, true, null);
        }
Ejemplo n.º 22
0
        public Task OpenEmailManager(string[] emails, string subject, string text, string[] attachments)
        {
            var tcs = new TaskCompletionSource <bool>();

            if (MFMailComposeViewController.CanSendMail)
            {
                var c = new MFMailComposeViewController();
                c.SetToRecipients(emails);
                c.SetSubject(subject ?? "");
                c.SetMessageBody(text ?? "", false);
                foreach (string attachment in attachments)
                {
                    NSData data = NSData.FromFile(attachment);
                    if (data != null)
                    {
                        c.AddAttachmentData(data, GetMimeType(attachment), Path.GetFileName(attachment));
                    }
                }

                _application.RootController.PresentViewController(c, true, null);
                c.Finished += (sender, e) =>
                {
                    tcs.SetResult(e.Result == MFMailComposeResult.Sent);
                    _application.InvokeOnMainThread(() => e.Controller.DismissViewController(true, null));
                };
            }
            else
            {
                var alert = new UIAlertView("Cannot send report", "E-mail messages not allowed", null, "OK");
                alert.Clicked += (sender, args) => tcs.SetResult(false);
                alert.Show();
            }
            return(tcs.Task);
        }
Ejemplo n.º 23
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);
    }
Ejemplo n.º 24
0
        public void SendFeedbackErrorLog(string supportEmail, string subject)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                var av = new UIAlertView(Localize.GetValue("PanelMenuViewReportProblemText"), Localize.GetValue("ServiceError_EmailClientAbsent"), null, Localize.GetValue("OkButtonText"), null);
                av.Show();
                return;
            }

            var mailComposer = new MFMailComposeViewController();
            var logFile      = _logger.GetLogFileName();

            if (logFile != null)
            {
                mailComposer.AddAttachmentData(NSData.FromFile(logFile), "text", Path.GetFileName(logFile));
            }

            mailComposer.SetToRecipients(new [] { supportEmail });
            mailComposer.SetMessageBody("", false);
            mailComposer.SetSubject(subject);
            mailComposer.Finished += (sender, args) =>
            {
                var uiViewController = sender as UIViewController;
                if (uiViewController == null)
                {
                    throw new ArgumentException("sender");
                }

                uiViewController.DismissViewController(true, () => { });
                _modalHost.NativeModalViewControllerDisappearedOnItsOwn();
            };
            _modalHost.PresentModalViewController(mailComposer, true);
        }
        private void SendByMail()
        {
            UIGraphics.BeginImageContext(chart.Frame.Size);
            var ctx = UIGraphics.GetCurrentContext();

            if (ctx != null)
            {
                chart.Layer.RenderInContext(ctx);
                UIImage img = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                if (MFMailComposeViewController.CanSendMail)
                {
                    _mail = new MFMailComposeViewController();

                    _mail.AddAttachmentData(img.AsPNG(), "image/png", "image.png");
                    _mail.SetSubject("Chart from TeeChart Builder for iPhone");

                    _mail.SetMessageBody("This is the Chart sent through TeeChart app.", false);
                    _mail.Finished += HandleMailFinished;

                    this.PresentModalViewController(_mail, true);
                }
                else
                {
                    // handle not being able to send mail
                }
            }
        }
        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);
        }
        // This function builds email confirmation with attachment
        private void SendEmail(string[] recipients, string messageBody, UIImage attachment)
        {
            try
            {
                var d = new MFMessageComposeViewController();

                var mailController = new MFMailComposeViewController();

                mailController.SetToRecipients(recipients);
                mailController.SetSubject("Email Confirmation By Just Delivered");
                mailController.SetMessageBody(messageBody, false);
                mailController.AddAttachmentData(attachment.AsJPEG(), "image/png", "photo.png");

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

                this.PresentViewController(d, true, null);
            }
            catch (FeatureNotSupportedException ex)
            {
                myPage.DisplayException(ex.Message);
            }
            catch (Exception ex)
            {
                myPage.DisplayException(ex.Message);
            }
        }
        private void SendButton_TouchUpInside(object sender, EventArgs e)
        {
            if (MFMailComposeViewController.CanSendMail)
            {
                // an array of strings that represents recipients
                var to = new string[] { "*****@*****.**" };

                // MFMailComposeViewController calls the UI to send an email
                if (MFMailComposeViewController.CanSendMail)
                {
                    mailController = new MFMailComposeViewController();
                    mailController.SetToRecipients(to);
                    mailController.SetSubject("A picture");
                    mailController.SetMessageBody("Hi, I'm sending a picture from iOS", false);

                    mailController.AddAttachmentData(ImageView.Image.AsJPEG(), "image/jpeg", "image.jpg");

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

                this.PresentViewController(mailController, true, null);
            }
        }
 public override void ViewDidLoad ()
 {
     base.ViewDidLoad ();
     
     tv.BecomeFirstResponder ();
     
     toolbar.Items[0].Clicked += (o, s) =>
     {
         string text = tv.Text;
         NSData pdfData = CreatePDF (text, 500f, 700f);
         
         if (MFMailComposeViewController.CanSendMail) {
             _mail = new MFMailComposeViewController ();
             _mail.SetMessageBody (tv.Text, false);
             _mail.AddAttachmentData (pdfData, "text/x-pdf", "test.pdf");
             _mail.Finished += HandleMailFinished;
             this.PresentModalViewController (_mail, true);
         } else {
             UIAlertView alert = new UIAlertView ("App", "Could not send mail.", null, "OK", null);
             alert.Show ();
         }
     };
     
     toolbar.Items[1].Clicked += (o, s) =>
     {
         _pdf = new PDFViewController (tv.Text);
         this.PresentModalViewController (_pdf, true);
     };
 }
Ejemplo n.º 30
0
        private void Email(string exportType)
        {
            if (!MFMailComposeViewController.CanSendMail)
            {
                return;
            }

            var    title          = exampleInfo.Title + "." + exportType;
            NSData nsData         = null;
            string attachmentType = "text/plain";
            var    rect           = new CGRect(0, 0, 800, 600);

            switch (exportType)
            {
            case "png":
                nsData         = View.ToPng(rect);
                attachmentType = "image/png";
                break;

            case "pdf":
                nsData         = View.ToPdf(rect);
                attachmentType = "text/x-pdf";
                break;
            }

            var mail = new MFMailComposeViewController();

            mail.SetSubject("OxyPlot - " + title);
            mail.SetMessageBody("Please find attached " + title, false);
            mail.Finished += HandleMailFinished;
            mail.AddAttachmentData(nsData, attachmentType, title);

            this.PresentViewController(mail, true, null);
        }
Ejemplo n.º 31
0
        public void SendMail(MemoryStream stream)
        {
            SaveExcel(stream);

            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string filePath = Path.Combine(path, "reports.xlsx");

            NSData data = NSData.FromFile (filePath);

            if (MFMailComposeViewController.CanSendMail)
            {
                var mail = new MFMailComposeViewController ();
                mail.SetSubject ("Exports");
                mail.SetMessageBody ("Hi, Please find the report here.", false);
                mail.AddAttachmentData (data, "application/vnd.ms-excel", "reports.xlsx");

                var window= UIApplication.SharedApplication.KeyWindow;
                var vc = window.RootViewController;
                vc.PresentViewController (mail, false, null);

                mail.Finished += ( object s, MFComposeResultEventArgs args) => {

                        args.Controller.DismissViewController (true, null);

                };
            }
        }
Ejemplo n.º 32
0
        public async Task ComposeEmail(string[] recipients, string mailSubject, string mailBody, string attachmentFilePath, string attachmentType, Action onSuccesfulSend, Action onFailedSend, Action onSendCancel)
        {
            if (MFMailComposeViewController.CanSendMail)
            {
                MFMailComposeViewController mailController = new MFMailComposeViewController();

                if (recipients != null && recipients.Length > 0)
                {
                    mailController.SetToRecipients(recipients);
                }
                if (!string.IsNullOrEmpty(mailSubject))
                {
                    mailController.SetSubject(mailSubject);
                }
                if (!string.IsNullOrEmpty(mailBody))
                {
                    mailController.SetMessageBody(mailBody, false);
                }

                if (!string.IsNullOrEmpty(attachmentFilePath))
                {
                    IFile attachmentFile = await FileSystem.Current.GetFileFromPathAsync(attachmentFilePath);

                    if (attachmentFile != null)
                    {
                        NSData attachmentData = NSData.FromFile(attachmentFilePath);
                        string mimeType       = attachmentType;
                        mailController.AddAttachmentData(attachmentData, mimeType, attachmentFile.Name);
                    }
                }

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

                    if (args.Result == MFMailComposeResult.Sent)
                    {
                        onSuccesfulSend?.Invoke();
                    }
                    else if (args.Result == MFMailComposeResult.Failed)
                    {
                        onFailedSend?.Invoke();
                    }
                    else
                    {
                        onSendCancel?.Invoke();
                    }
                };
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
            }
            else
            {
                onFailedSend?.Invoke();
                throw new Exception("Error sending mail: No mail client has been configured on this device.");
            }
        }
Ejemplo n.º 33
0
 public void AddQRPictureAttachment(MFMailComposeViewController mailContr, LagerObject input)
 {
     if (this.IncludeQr()) {
         if (input != null) {
             UIImage image = AppDelegate.key.MakeQr (input);
             NSData imagedata = image.AsPNG ();
             mailContr.AddAttachmentData (imagedata, "image/png", "QR.png");
         }
     }
 }
Ejemplo n.º 34
0
        private void sendMail(object sender, EventArgs e)
        {
            mailCtrl.SetMessageBody("ICOM Archivo PDF", false);
            NSData nsdf = NSData.FromFile(urlDocumento);

            mailCtrl.AddAttachmentData(nsdf, "pdf", tituloDocumento);


            this.PresentViewController(mailCtrl, true, null);
        }
Ejemplo n.º 35
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.º 36
0
 public override void ShareFileAsync(string path, string subject)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         MFMailComposeViewController mailer = new MFMailComposeViewController();
         mailer.SetSubject(subject);
         mailer.AddAttachmentData(NSData.FromUrl(NSUrl.FromFilename(path)), "application/json", Path.GetFileName(path));
         mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
         UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
     });
 }
Ejemplo n.º 37
0
 public void AddPictureAttachment(MFMailComposeViewController mailContr, Item input)
 {
     var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
     if (!string.IsNullOrEmpty (input.ImageFileName)) {
         string jpg = input.Name + ".jpg";
         string filename = System.IO.Path.Combine (documentsDirectory, input.ImageFileName);
         UIImage image = UIImage.FromFile (filename);
         NSData imagedata = image.AsJPEG ();
         mailContr.AddAttachmentData (imagedata, "image/jpeg", jpg);
     }
 }
Ejemplo n.º 38
0
        void HandleSend(object sender, System.EventArgs eventArgs)
        {
            var mail = new MFMailComposeViewController();
            var body = string.Format("QR Code: {0}\r\nImages", ViewModel.BarcodeResult);

            mail.SetMessageBody(body, false);
            mail.SetSubject("Results");
            mail.SetToRecipients(new[] { "*****@*****.**" });
            int i = 0;

            foreach (var im in ViewModel.Images)
            {
                mail.AddAttachmentData(NSData.FromArray(im), "image/jpg", string.Format("im{0}.jpg", ++i));
            }
            if (ViewModel.Bytes != null)
            {
                mail.AddAttachmentData(NSData.FromArray(ViewModel.Bytes), "image/jpg", "combined.jpg");
            }
            mail.Finished += (s, e) => (s as UIViewController).DismissViewController(true, () => { });
            PresentViewController(mail, true, null);
        }
Ejemplo n.º 39
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.º 40
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.º 41
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.º 42
0
    // Use this for initialization
    void Start()
    {
        // create some arbitary binary data. or load from existing location
        FileStream someFile = new FileStream(Application.temporaryCachePath+"/someFile.bin", FileMode.Create);
        someFile.WriteByte(0x42);
        someFile.Close();

        _mailController = new MFMailComposeViewController();

        _mailControllerDelegate = new MyMFMailComposeViewControllerDelegate();
        _mailController.mailComposeDelegate = _mailControllerDelegate;

        _mailController.SetToRecipients(new string[]{"*****@*****.**"});
        _mailController.SetSubject("well hello");
        _mailController.SetMessageBody("just testing attachments", false);

        _mailController.AddAttachmentData(
            new NSData(Application.temporaryCachePath+"/someFile.bin"),
            "application/octet-stream",
            "someFile.bin"
        );

        UIApplication.deviceRootViewController.PresentViewController(_mailController, true, null);
    }
        void HandleShareButtonClicked(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty (_currentSpeechItem.Text)) {
                if (_savedItemsController != null)
                    _savedItemsController.SelectedSpeechItem = null;

                if (MFMailComposeViewController.CanSendMail) {
                    MFMailComposeViewController mail = new MFMailComposeViewController ();
                    mail.SetSubject ("message from TalkBot");
                    mail.SetMessageBody (_currentSpeechItem.Text, false);
                    mail.AddAttachmentData (_currentSpeechItem.ToData (), "audio/x-wav", "audio.wav");
                    mail.Finished += HandleMailFinished;

                    this.PresentModalViewController (mail, true);

                } else {
                    UIAlertView alert = new UIAlertView ("Talk Bot", "Could not send mail.", null, "OK", null);
                    alert.Show ();
                }
            } else {
                UIAlertView promptNoText = new UIAlertView ("Talk Bot", "Please enter something \r\nfor me to share", null, "OK");
                promptNoText.Show ();
            }
        }
Ejemplo n.º 44
0
		void SendToEmail (string title, string text, string attachment, Action onSuccess, Action onFail)
		{
			if (MFMailComposeViewController.CanSendMail) {
				MFMailComposeViewController c = new MFMailComposeViewController ();
				c.SetSubject (title);
				c.SetToRecipients (new string[]{ _settings.DevelopersEmail });
				c.SetMessageBody (text, false);
				NSData data = new NSString (attachment).DataUsingEncoding (NSStringEncoding.UTF8);
				c.AddAttachmentData (data, "text/xml", "info.xml");
				_application.RootController.PresentViewController (c, true, null);
				c.Finished += (object sender, MFComposeResultEventArgs e) => {
					if (e.Result == MFMailComposeResult.Sent)
						onSuccess ();
					else
						onFail ();
					e.Controller.DismissViewController (true, null);
				};

			} else {
				UIAlertView alert = new UIAlertView ("Cannot send report", "E-mail messages not allowed", null, "OK");
				alert.Show ();
			}
		}
        void SendMail()
        {
            if (MFMailComposeViewController.CanSendMail) {
                var mail = new MFMailComposeViewController ();
                mail.SetSubject ("Location data spreadsheet");
                mail.SetMessageBody ("Spreadsheet with location data attached.", false);
                mail.AddAttachmentData (NSData.FromFile (path), "application/vnd.ms-excel ", "locations.xlsx");
                mail.Finished += (object sender, MFComposeResultEventArgs e) => {
                    e.Controller.DismissViewController (true, null);
                };

                PresentViewController (mail, true, null);
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Shows the native MFMailComposeViewController to send an email.
        /// Raises MailCompleted event when completed.</summary>
        /// 
        /// <param name="recipients"> An array of strings representing the email addresses of the recipients.</param>
        /// <param name="subject"> The subject of the email.</param>
        /// <param name="body"> The body of the email.</param>
        /// <param name="bodyIsHTML"> True if the body is HTML; false otherwise.</param>
        /// <param name="image"> The image to attach to the email.</param>
        /// <param name="checkServiceAvailable"> Whether to check if the service is available first.</param>
        /// <returns> True if it is able to show the native view controller; false if it cannot send email.</returns>
        public static bool Mail(string[] recipients, string subject, string body, bool bodyIsHTML, UIImage image, bool checkServiceAvailable)
        {
            if (checkServiceAvailable && !MFMailComposeViewController.CanSendMail())
                return false;

            var vc = new MFMailComposeViewController();
            if (vc.IsNil)
                return false;

            vc.mailComposeDelegate = MailComposeViewControllerDelegate.instance;
            vc.SetToRecipients(recipients);
            vc.SetSubject(subject);
            vc.SetMessageBody(body, bodyIsHTML);

            if (image != null) {
                var nsdata = image.PNGRepresentation();
                vc.AddAttachmentData(nsdata, "image/png", "image.png");
            }

            UIApplication.deviceRootViewController.PresentViewController(vc, true, null);
            return true;
        }
Ejemplo n.º 47
0
 public override void ShareFileAsync(string path, string subject)
 {
     Device.BeginInvokeOnMainThread(() =>
         {
             MFMailComposeViewController mailer = new MFMailComposeViewController();
             mailer.SetSubject(subject);
             mailer.AddAttachmentData(NSData.FromUrl(NSUrl.FromFilename(path)), "application/json", Path.GetFileName(path));
             mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
             UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
         });
 }
Ejemplo n.º 48
0
 void HandleSend(object sender, System.EventArgs eventArgs)
 {
     var mail = new MFMailComposeViewController();
     var body = string.Format("QR Code: {0}\r\nImages", ViewModel.BarcodeResult);
     mail.SetMessageBody(body, false);
     mail.SetSubject("Results");
     mail.SetToRecipients(new[] {"*****@*****.**"});
     int i = 0;
     foreach(var im in ViewModel.Images)
         mail.AddAttachmentData(NSData.FromArray(im), "image/jpg", string.Format("im{0}.jpg", ++i));
     if(ViewModel.Bytes != null)
         mail.AddAttachmentData(NSData.FromArray(ViewModel.Bytes), "image/jpg", "combined.jpg");
     mail.Finished += (s, e) => (s as UIViewController).DismissViewController(true, () => { });
     PresentViewController(mail, true, null);
 }
Ejemplo n.º 49
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.º 50
0
 public override void ShareFileAsync(string path, string subject, string mimeType)
 {
     Device.BeginInvokeOnMainThread(() =>
         {
             if (MFMailComposeViewController.CanSendMail)
             {
                 MFMailComposeViewController mailer = new MFMailComposeViewController();
                 mailer.SetSubject(subject);
                 mailer.AddAttachmentData(NSData.FromUrl(NSUrl.FromFilename(path)), mimeType, Path.GetFileName(path));
                 mailer.Finished += (sender, e) => mailer.DismissViewControllerAsync(true);
                 UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailer, true, null);
             }
             else
                 SensusServiceHelper.Get().FlashNotificationAsync("You do not have any mail accounts configured. Please configure one before attempting to send emails from Sensus.");
         });
 }
Ejemplo n.º 51
0
		private void Email(string exportType)
        {
            if(!MFMailComposeViewController.CanSendMail)
                return;

            var title = exampleInfo.Title + "." + exportType;
            NSData nsData = null;
            string attachmentType = "text/plain";
            var rect = new CGRect(0,0,800,600);
            switch(exportType)
            {
            case "png":
                nsData =  View.ToPng(rect);
                attachmentType = "image/png";
                break;
            case "pdf":
                nsData = View.ToPdf(rect);
                attachmentType = "text/x-pdf";
                break;
            }

            var mail = new MFMailComposeViewController ();
            mail.SetSubject("OxyPlot - " + title);
            mail.SetMessageBody ("Please find attached " + title, false);
            mail.Finished += HandleMailFinished;
            mail.AddAttachmentData(nsData, attachmentType, title);

            this.PresentViewController (mail, true, null);
        }
Ejemplo n.º 52
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear (animated);
            var elements = HistoryManager.SharedInstance.GetResultList();

            Root.Remove(Section);
            Section = new Section ();

            for (int i=1; i<=elements.Count;i++)
            {
                var temp = i;
                Section.Add (new StringElement("Result "+temp,()=>{
                    Console.Out.WriteLine(temp);
                    var ActionSheet = new UIActionSheet ("Options");

                    ActionSheet.AddButton("Detail");
                    ActionSheet.AddButton("Send by Email");
                    ActionSheet.AddButton("Delete");
                    ActionSheet.AddButton("Cancel");

                    ActionSheet.DestructiveButtonIndex = 2;
                    ActionSheet.CancelButtonIndex = 3;

                    ActionSheet.Clicked += (object sender, UIButtonEventArgs e) => {
                        if(e.ButtonIndex == 0)
                        {
                            // Detail
                            Console.Out.WriteLine("Detail");
                            var t = new CalculationResult ();
                            t = HistoryManager.SharedInstance.GetResultList()[temp-1];
                            this.NavigationController.PushViewController(new TankMix_History_Result(t),true);
                        }else if (e.ButtonIndex == 1){
                            // Share
                            Console.Out.WriteLine("Send by Email");
                            var Email = new MFMailComposeViewController();
                            if(MFMailComposeViewController.CanSendMail)
                            {
                                var filePath = CreateExcelFile(HistoryManager.SharedInstance.GetResultList()[temp-1]);
                                //NSData iData = NSData.FromUrl(new NSUrl(imageList[i],false) );
                                NSData attachement = NSData.FromUrl(new NSUrl(filePath,false));
                                Email.AddAttachmentData(attachement,"text/csv","Reports");
                            }
                            Email.Finished += (object s, MFComposeResultEventArgs ea) => {
                                ea.Controller.DismissViewController(true,null);
                            };
                            var msg = "";
                            Email.SetMessageBody(msg,false);
                            this.NavigationController.PresentViewController(Email,true,null);

                            this.NavigationController.PopToRootViewController(true);
                        }else if (e.ButtonIndex == 2){
                            //Delete
                            Console.Out.WriteLine("Delete");
                            HistoryManager.SharedInstance.GetResultList().RemoveAt(i-2);
                            ViewWillAppear(true);
                        }else{
                            // Cancel
                            Console.Out.WriteLine("Cancel");
                            CreateExcelFile(HistoryManager.SharedInstance.GetResultList()[temp-1]);
                        }

                    };
                    ActionSheet.ShowInView(View);

                }));
            }
            Root.Add (Section);
        }
Ejemplo n.º 53
0
        private void sendReportByEmail(string path, CLLocationCoordinate2D location)
        {
            var mailController = new MFMailComposeViewController ();
            var msg = string.Format("Location Coordinates : http://maps.google.com/maps?z=12&t=m&q=loc:{0}+{1}",location.Latitude,location.Longitude);
            mailController.SetMessageBody(msg,false);

            var recordings = Directory.EnumerateFiles (path+"/recordings");
            var photos = Directory.EnumerateFiles (path+"/photos");

            foreach (var r in recordings){

                NSData aData = NSData.FromUrl(new NSUrl(r,false));
                mailController.AddAttachmentData(aData,"audio/aac","Audio_");
            }

            foreach (var p in photos) {
                NSData iData = NSData.FromUrl(new NSUrl(p,false) );
                mailController.AddAttachmentData(iData,"image/jpg","Image_");
            }

            mailController.Finished += (object s, MFComposeResultEventArgs ea) => {
                ea.Controller.DismissViewController(true,null);
            };
            this.NavigationController.PresentViewController(mailController,true,null);
        }
        // ReSharper disable once UnusedMember.Local
        // ReSharper disable once UnusedParameter.Local
        async partial void SendToMail(NSObject sender)
        {
            try
            {
                BTProgressHUD.Show();
                var mailController = new MFMailComposeViewController();

                mailController.SetToRecipients(new[]
                {
                    string.Empty
                });
                mailController.SetSubject(CurrentMessage.Subject);
                mailController.SetMessageBody(CurrentMessage.Body, true);

                byte[] data = await PlattformService.Service.GetAttachment(CurrentMessage.Links.Attachment[0].Href);
                NSData attachment = NSData.FromArray(data);

                if (attachment != null && CurrentMessage.Links.Attachment[0].Mimetype != null)
                {
                    mailController.AddAttachmentData(attachment, CurrentMessage.Links.Attachment[0].Mimetype,
                        CurrentMessage.Links.Attachment[0].Name);
                }

                mailController.Finished += (s, args) =>
                {
                    Logger.Logg(args.Result.ToString());
                    args.Controller.DismissViewController(true, null);
                };
                BTProgressHUD.Dismiss();
                PresentViewController(mailController, true, null);
            }
            catch (Exception ex)
            {
                Logger.Logg("failed to create mail: " + ex);
            }
        }
Ejemplo n.º 55
0
		partial void SendButtonClick(MonoTouch.Foundation.NSObject sender) 
		{
			if (MFMailComposeViewController.CanSendMail) 
			{
				var mail = new MFMailComposeViewController ();
				mail.SetSubject( "Zetetic Message Database");
				mail.SetToRecipients(new string[]{});
				mail.SetMessageBody ("Please find a database attached", false);
				mail.AddAttachmentData(NSData.FromFile(_messageDb.FilePath), MessageDb.MIME_TYPE, Path.GetFileName(_messageDb.FilePath));
				mail.Finished += (s, e) => {
					mail.DismissViewController(true, null);
				};
				PresentViewController(mail, true, null);			
			}
		}
Ejemplo n.º 56
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.º 57
0
        /// <summary>
        /// Shows the native MFMailComposeViewController to send an email.
        /// Raises MailCompleted event when completed.</summary>
        /// 
        /// <param name="recipients"> An array of strings representing the email addresses of the recipients.</param>
        /// <param name="subject"> The subject of the email.</param>
        /// <param name="body"> The body of the email.</param>
        /// <param name="bodyIsHTML"> True if the body is HTML; false otherwise.</param>
        /// <param name="image"> The image to attach to the email.</param>
        /// <param name="checkServiceAvailable"> Whether to check if the service is available first.</param>
        /// <returns> True if it is able to show the native view controller; false if it cannot send email.</returns>
        public static bool Mail(string[] recipients, string subject, string body, bool bodyIsHTML, Texture2D image = null, bool checkServiceAvailable = true)
        {
            if (checkServiceAvailable && !MFMailComposeViewController.CanSendMail())
                return false;

            var vc = new MFMailComposeViewController();
            if (vc.IsNil)
                return false;

            vc.mailComposeDelegate = MailComposeViewControllerDelegate.instance;
            vc.SetToRecipients(recipients);
            vc.SetSubject(subject);
            vc.SetMessageBody(body, bodyIsHTML);

            if (image != null) {
                var nsdata = NSData.FromByteArray(image.EncodeToPNG());
                vc.AddAttachmentData(nsdata, "image/png", "image.png");
            }

            UIApplication.SharedApplication().keyWindow.rootViewController.PresentViewController(vc, true, null);
            return true;
        }
Ejemplo n.º 58
0
        public FT_MessageViewController(UIImage mapImage,CLLocationCoordinate2D location)
            : base(UITableViewStyle.Grouped, null)
        {
            imageList = new List<string> ();
            audioList = new List<NSUrl> ();

            _mapScreenShot = mapImage;
            this.Pushing = true;

            var _shareBtn = new UIBarButtonItem (){
                Title = "Send"
            };
            _shareBtn.Clicked += (object sender, EventArgs e) => {

                if (MFMailComposeViewController.CanSendMail){
                    var mailController = new MFMailComposeViewController ();
                    saveMessage(location);
                    var msg = string.Format("Location Coordinates : http://maps.google.com/maps?z=12&t=m&q=loc:{0}+{1}",location.Latitude,location.Longitude);
                    mailController.SetMessageBody(msg,false);

                    for(int i=0 ; i<audioList.Count; i++){

                        var path = audioList[i].AbsoluteString;
                        NSFileManager.SetSkipBackupAttribute(path,true);
                        NSData aData = NSData.FromUrl(audioList[i]);
                        mailController.AddAttachmentData(aData,"audio/aac","Audio_"+i);
                    }

                    for(int i=0; i<imageList.Count; i++){
                        NSFileManager.SetSkipBackupAttribute(imageList[i],true);
                        NSData iData = NSData.FromUrl(new NSUrl(imageList[i],false) );
                        mailController.AddAttachmentData(iData,"image/jpg","Image_"+i);
                    }

                    mailController.Finished += (object s, MFComposeResultEventArgs ea) => {
                        ea.Controller.DismissViewController(true,null);
                    };
                    this.NavigationController.PresentViewController(mailController,true,null);

                    this.NavigationController.PopToRootViewController(true);
                }else{
                    new UIAlertView ("Error","No Email Account on the Device.",null,"OK",null).Show();
                }

            };
            this.NavigationItem.RightBarButtonItem = _shareBtn;

            Root = new RootElement ("Add");
            var mapS = new Section (){
                HeaderView = new UIImageView (CropImage (_mapScreenShot, 0, 150, 320, 240)),
            };
            var locationS = new Section ("Location Information"){
                new StringElement ("Latitude", location.Latitude.ToString ()),
                new StringElement ("Longitude",location.Longitude.ToString()),
            };

            var pictureS = new Section ("Picture");
            createTakePhotoBtn(pictureS);

            var recordingS = new Section ("Recording");
            createTakeRecordingBtn (recordingS);

            Root.Add (mapS);
            Root.Add (locationS);
            Root.Add (pictureS);
            Root.Add (recordingS);

            observer = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, delegate (NSNotification n) {
                //player.Dispose();
                player = null;
            });

            createDocumentFolder ();

            this.NavigationItem.HidesBackButton = true;
            var cancelBtn = new UIBarButtonItem ();
            cancelBtn.Title = "Cancel";
            cancelBtn.TintColor = UIColor.Red;
            this.NavigationItem.LeftBarButtonItem = cancelBtn;
            cancelBtn.Clicked += (object sender, EventArgs e) => {
                deleteDocumentFolder();
                this.NavigationController.PopToRootViewController(true);

            };
        }
        private void EmailButtonTouchDown(object sender, EventArgs e)
        {
            if (File.Exists(Settings.Current.LogFile))
            {
                if (MFMailComposeViewController.CanSendMail)
                {
                    NSData data = NSData.FromFile(Settings.Current.LogFile);

                    MFMailComposeViewController mailController = new MFMailComposeViewController();
                    mailController.SetSubject("Really simple iPhone error report");
                    mailController.SetToRecipients(new string[] { "*****@*****.**" });
                    mailController.SetMessageBody("Really simple error report", false);
                    mailController.AddAttachmentData(data, "text/plain", "error.log");
                    mailController.Finished += HandleMailFinished;
                    this.PresentModalViewController(mailController, true);
                }
                else
                {
                    ModalDialog.Alert("No email account found", "Please configure an email account before sending an error report");
                }
            }
            else
            {
                ModalDialog.Alert("No log file was found", "The error log was empty. Please try sending this again after the error occurs.");
            }
        }