Forum Xamarin.Forms

How to attach an ImageSource object to an email?

I'm working on an Android dependency service to open the default email client and add an image attachment.
I'm passing an ImageSource object to the Android dependency service, but now I'm trying to add the ImageSource object being passed as an attachment in an email message. I've been researching this but all of the solutions I've found are reading from an actual file in the disk (see here)

This is what I have so far...

public void OpenEmailClient(ImageSource image)
    Intent email = new Intent(Android.Content.Intent.ActionSend);
    email.PutExtra(Android.Content.Intent.ExtraSubject, "Catalog page image");
    // I'm trying to get the uri from the ImageSource object here...
    var uri = image.GetValue(UriImageSource.UriProperty);
    // The line below is giving an error - the uri variable is invalid
    email.PutExtra(Intent.ExtraStream, uri);

    Forms.Context.StartActivity(Intent.CreateChooser(email, "Send mail..."));       

Am I going to have to save the image in disk in order to be able to attach it to an email message?
Any ideas?


  • rarenivarrarenivar USMember ✭✭

    For anyone out there trying to do this, I ended up creating an image file, then using this file
    to attach to the email intent.

    This is how I implemented this functionality...

    // Function is part of the Android Dependency Service being called in the Xamarin.Forms application public async void OpenEmailClient(ImageSource image) { // Need to first convert the ImageSource object to a Bitmap Bitmap bitmap = await GetImageFromImageSource(image, Forms.Context); var picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); var filePath = System.IO.Path.Combine(picturesDirectory.Path, "tempImage.png"); // Write Bitmap object to a file var stream = new FileStream(filePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); stream.Close(); var file = new Java.IO.File(filePath); file.SetReadable(true, false); var uri = Android.Net.Uri.FromFile(file); var email = new Intent(Intent.ActionSend); email.PutExtra(Intent.ExtraSubject, "Subject of email here"); email.PutExtra(Intent.ExtraStream, uri); email.SetType("message/rfc822"); Forms.Context.StartActivity(Intent.CreateChooser(email, "Email")); }

Sign In or Register to comment.