Tuesday, December 16, 2014

Send an email via IMAP from C#! (compatible downwards to the 3.5 Framework, but assuming an Outlook server)

using System.Net;
using Microsoft.Exchange.WebServices.Data;
namespace AdministrableApplication.Email
{
   public class EmailFacilitator
   {
      public void Send()
      {
         ExchangeService service = new ExchangeService();
         service.Credentials = new NetworkCredential("me@example.com", "abc123",
               "outlook.whatever.com");
         service.TraceEnabled = true;
         service.AutodiscoverUrl("me@example.com", RedirectionCallback);
         EmailMessage message = new EmailMessage(service);
         message.Subject = "Can you see this?";
         message.Body = "Please write me back if you got this!";
         message.ToRecipients.Add("tomjaeschke@tomjaeschke.com");
         message.SendAndSaveCopy();
      }
      
      static bool RedirectionCallback(string url)
      {
         return url.ToLower().StartsWith("https://");
      }
   }
}

 
 

The following links helped me figure this out:

 
 

I originally got the project from here for the Microsoft.Exchange.WebServices.Data namespace which I then bolting into an existing solution in Visual Studio, but then I also ended up getting it anew from here when I got this error:

Could not find any resources appropriate for the specified culture or the neutral culture. Make sure \"Microsoft.Exchange.WebServices.Strings.resources\" was correctly embedded or linked into assembly \"Microsoft.Exchange.WebServices.Data\" at compile time, or that all the satellite assemblies required are loadable and fully signed.

 
 

Again, I got the error using the first of the two here links above and I got around the error by using the later. Yet, another error I then hit looked like this:

Autodiscover blocked a potentially insecure redirection to https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.

 
 

The line which looks like...

service.AutodiscoverUrl("me@example.com", RedirectionCallback);

 
 

...in my above code had to be rewritten to its current shape as it originally looked like so...

service.AutodiscoverUrl("me@example.com");

 
 

...bringing in the static method which also had to be added in. This fix got me around this second pitfall.

No comments:

Post a Comment