Sending files via the default e-mail client
I recently released a "Send To Email" plugin for Cropper, which makes it easy to grab a portion of your screen and send it as an e-mail attachment. It's easy enough to directly send an e-mail in .NET using System.Net.Mail, but there's no provision for sending a mail using the default client.
Spoiler - if you just want the code without the background, skip to the "Take Three" section below.
Take One - MailTo link
You can launch the default mail client by shelling out to a mailto link, and some e-mail clients support an "attach" parameter:
public static void Main() { SendMailWithMailTo( "dvader@deathstar.mil", "Rebel Base Detected", "Hoth, baybee!!", "\"C:\\Users\\Fett\\RebelBase[1].png\""); } public static void SendMailWithMailTo( string address, string subject, string body, string attach) { //Don't use this - just an example string mailto = string.Format( "mailto:{0}?Subject={1}&Body={2}&Attach={3}", address,subject,body,attach); System.Diagnostics.Process.Start(mailto); }
That's not really a good plan, though. The main reason is that the "attach" is an unofficial extension to the mailto protocol. It's not supported in a lot of e-mail clients, and those that implement it all work a little differently (for instance, some use "attachment" instead of "attach". I'd expect that fewer mail clients will be support attachments in the mailto protocol due to the obvious security issues (a mailto link on a website with an attachment reference to files in common locations, for instance). There was a security advisory for mailto attachments in Outlook 2003, for instance.
Take Two - Call MapiSendMail via PInvoke
MapiSendMail invokes the default e-mail client and supports attachments. There's a CodeProject article with C++ code, and the author supplied C# code to call MapiSendMail in the comments. It's reasonably straightforward, and it's easy to use. I'm going to skip over it, though, because it has one major problem - the call to MapiSendMail is modal. What that means is that your program hangs until the user edits and sends the e-mail. That's not at all what you'd expect as an end user - I'd want to be able to save the message as a draft and go on using the program.
Take Three - Call MapiSendMail Asynchronously
Andrew Baker's MAPI wrapper class does a great job of sending mail using the default e-mail client, and it does it asynchronously. The function you'll call, ShowDialog, just calls internal utility functions on a new thread and returns. It's very easy to use:
MapiMailMessage message = new MapiMailMessage(subject, body); message.Files.Add(file); message.ShowDialog();