Search code examples
androidformsxamarindependenciesemail-attachments

Send an email +attachment using dependency services DROID Xamarin forms


I came across this error when Trying to send an email with attachment. any help ? Thank you

****Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?****

this is my code :

[assembly: Dependency(typeof(sendEmail))]
namespace myapp.Droid
{
    public class sendEmail : IEmailTask
    {
        public sendEmail()
        {

        }

        public void SendEmail () 
        {
            var sqlliteFilname = "test.3gpp";
            string documentsPath = System.Environment.GetFolderPath(
            Environment.SpecialFolder.Personal);
            var stringPath = Path.Combine(documentsPath, sqlliteFilname);

            var path = Android.Net.Uri.FromFile(new 
           Java.IO.File(stringPath));

            Intent emailIntent = new Intent(Intent.ActionSend);
            // set the type to 'email'
            emailIntent.SetData(Android.Net.Uri.Parse("mailto:"));

            String[] to = { "youremail@mail.com" };

            emailIntent.PutExtra(Intent.ExtraEmail, to);
            // the attachment
            emailIntent.PutExtra(Intent.ExtraStream, path);
            // the mail subject
            emailIntent.PutExtra(Intent.ExtraSubject, "Subject");

           Android.App.Application.Context.StartActivity(Intent.CreateChooser(emailIntent, "Send email..."));


        }
    }
}

code on the page is :

 void btnSendingHandle_Clicked(object sender, System.EventArgs e)
        {
            var getEmail = DependencyService.Get<IEmailTask>();

            getEmail.SendEmail();
        }

Solution

  • check if you have an attachment to send. *To be replace for the if block & change this

    Intent emailIntent = new Intent(Intent.ActionSend);
    //change it to 
    
    
    Intent emailIntent = new Intent(Intent.ActionSendto);
    

    Android.App.Application.Context.StartActivity(Intent.CreateChooser(emailIntent, "Send email..."));

    if (emailIntent.ResolveActivity(Android.App.Application.Context.PackageManager) != null)
                {
                    Android.App.Application.Context.StartActivity(emailIntent);
                }
                else
                {
    
                        string tag = "MY-EMAIL";
                        Log.Info(tag, "no attachment found");
                }
    

    my issue relies on the attachment itself.