Send email from Xamarin.Forms app using Dependency

2019-09-05 03:42发布

问题:

In my app, for debugging purposes and testing purposes I need to send an email.

How do I present the mail controller, when the class that sends it does not contain a definition for PresentViewController ? The class needs to fire off the email app after the user clicks "yes" from the alert which fires.

    public async Task<bool> SendEmail(Exception ex)
    {
        var result = await SendNotificationToRequestSendingEmail();

        if (result)
        {

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

                mailController.SetToRecipients(new string[] { "test@one.com", "test@two.com" });
                mailController.SetSubject("Details");
                mailController.SetMessageBody($"Message: {ex.Message}" +
                                              $"Exception: {ex.ToString()}"
                                              , false);

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

                this.PresentViewController(mailController, true, null); //this line causes the error
            }
        }

        return true;
    }

How can I fix this problem or get around it? This is called from a Xamarin Forms page.

回答1:

Please take a look at this answer:

Sending e-mail from Gmail in Xamarin.Forms app

besides that you can also do it with this NuGet package:

https://www.nuget.org/packages/Xam.Plugins.Messaging/