Sending an Email with an Attachment on Windows Phone (Sort of)

From it’s initial release Windows Phone has had a method to programmatically send an email from code. In keeping with the mantra that the user is in control it has always been a method to populate the email but allow the user to decide to modify, send or cancel. Despite much demand the ability to attach files has not been made available. As a user you can attach a picture to an outgoing email but the phone can receive a wider variety of types. There is, albeit not as obvious, a method to send a picture attachment via email but there are caveats.

The ShareMediaTask only allows you to specify the image to use and not the transport to send via or an accompanying message. In fact it basically is just running the “share…” menu found in the built in Pictures app. The other caveat is that the picture must be in a location that the system can read from so a path to your isolated storage won’t work. You can however copy an image to the user’s pictures library. Another annoyance is that once you’ve copied a picture to the library you can’t delete it – only the user has the ability to do this.

Microsoft.Xna.Framework.Media.MediaLibrary ml = new Microsoft.Xna.Framework.Media.MediaLibrary();
Microsoft.Xna.Framework.Media.Picture pic = ml.SavePicture(“mypic.png”, stream);
path = Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions.GetPath(pic);

The above code takes an image stream and placed it in the library and gets a true file path. The code to initiate the share operation is equally simple:-

Microsoft.Phone.Tasks.ShareMediaTask shareMediaTask = new Microsoft.Phone.Tasks.ShareMediaTask();
shareMediaTask.FilePath = path;

That’s all there is to it – you don’t get any feedback on what option was chosen (or whether the operation was cancelled).

I’ll be discussing some more around sharing various types of data at my talk on this coming Tuesday for WPUG Manchester which is titled “Bluetooth and NFC for Windows Phone and Beyond” where I’ll be unveiling some ways to make “Charming” apps for Windows Phone.