Sending Email Using Office 365 Exchange Webservices Api

Sending email using C# is really easy,  you can use the build in SMTP client

// Setup mail message section  
MailMessage mailMessage = new MailMessage(); 
mailMessage.From = new MailAddress("from@cupofdev.co.za");
mailMessage.To.Add(new MailAddress("to@cupofdev.com"); 
mailMessage.Subject = "Test Message Subject"; 
mailMessage.Body = "HTML Body; 
mailMessage.IsBodyHtml = true; 

// Setup SMTP Client 
SmtpClient client = new SmtpClient(); 
client.Credentials = new NetworkCredential("", ""); 
client.Port = 587; 
client.Host = "pod51016.outlook.com"; 
client.EnableSsl = true;  
client.send(mailmessage); 

but using this method will send email using the SMTP setting for Exchange Online / Office 365. My only problem with this approach is there is no send messages in the outbox and in some situations you need to keep track of messages that was send, you can also not really control any aspects of your mailbox or the mails.

Exchange Webservices API 2.0

Using the Exchange Webservices API (http://msdn.microsoft.com/en-us/library/dd633709(v=exchg.80).aspx) you can control every aspect of your exchange mailbox using webservices. Using Nuget you can add references to Microsoft.Exchange.Webservices.

// Create a new Exchange service object  
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);  

// Set user login credentials  
service.Credentials = new WebCredentials("email@domain.com", "email password");
 try {  
    //Set Office 365 Exchange Webserivce Url  
    string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx";
    service.Url = new Uri(serviceUrl);
    EmailMessage emailMessage = new EmailMessage(service);
    emailMessage.Subject = "Subject";  
    emailMessage.Body = new MessageBody("Cupofdev Exchange Web Service API");
    emailMessage.ToRecipients.Add("email@domain.com");  
    emailMessage.SendAndSaveCopy(); 
    }
catch (AutodiscoverRemoteException exception) {
     // handle exception  
     throw exception; 
     }

Using the SendAndSaveCopy method will send an email and also save it in your send items.

Built with Hugo
Theme Stack designed by Jimmy