[Xamarin] Sending an email with attachment in your Xamarin.Android application

April 9th, 2015 | Posted by Tom in .NET | Article | Xamarin | Read: 5,583

Recently, I’ve been asked by one of my customer how it could be possible, in a Xamarin.Android application, to send an email with an attachment.

After searching over Internet, I’ve managed to produce the following method:

var downloadsFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadsFolder.Path, "Demo.txt");

var createdFile = File.CreateText(filePath);
await createdFile.WriteAsync("Hello World!");
await createdFile.FlushAsync();

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.ExtraEmail, new[] { "tom@email.com" });
email.PutExtra(Intent.ExtraSubject, "Sample email with attachment");
email.PutExtra(Intent.ExtraStream, uri);

email.SetType("message/rfc822");

this.StartActivity(Intent.CreateChooser(email, "Email"));

The most important part here is the beginning of the method. Indeed, to be able to add the attachment, it needs to be accessible to the app that will send the email. So we need to create a copy of our file in a location that can be accessible by any app so, in our case, we choose the Downloads folder.

Another interesting point is the use of the SetReadable method to indicate that the file need to be readable but to anyone and not only the file’s creator!

Finally, depending of where you create the copy, you might set the right permissions to your app:

image

Also, once your application is back to forward, don’t forget to delete the copy to clean up the Downloads folder!

 

Happy coding! :)

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply