Saturday, April 1, 2017

Use EWS (Exchange Web Services) to send emails

EWS (Exchange Web Services) is an API that you can use to interact with Exchange items such as mail, calendar, contacts etc.
You can also use Outlook Object model to send emails. 
To work with EWS, you have install EWS (it only works with 64 bit machine). The link to download is here

Here is the sample code to Send an email - 


' import namespace
Imports Microsoft.Exchange.WebServices.Data

Public Class TestMail

    Public Sub SendMailusingEWS()

        Dim service As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2010_SP1)

        'Connect to Exchange Web Services as testaccount at mydomain.com.
        service.Credentials = New WebCredentials("testaccount", "password", "mydomain")

        'OR try this if above doesn't work. This credential depend how AD is configured. 
        'service.Credentials = New WebCredentials("testaccount@mydomain.com", "password")

        ' This is to bypass server certificate. ONLY FOR DEBUGGING. May not required.
        System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True

        'Set the URL of the property of service.
        service.Url = New System.Uri("https://myexchange.mydomain.com/EWS/Exchange.asmx")

        'For exchange365
        'service.Url = New System.Uri("https://outlook.office365.com/EWS/Exchange.asmx")

        'OR you can also set the URL by calling autodiscoverURL. You might want to cash it and define as above.
        'service.AutodiscoverUrl("testaccount@mydomain.com")

        'Create msg object and set its connection by passing service object  
        Dim msg As EmailMessage = New EmailMessage(service)
        msg.Subject = "test from EWS service"
        msg.Body = "saqib is testing"
        msg.ToRecipients.Add("mymail@gmail.com")
        msg.SendAndSaveCopy()

    End Sub

End Class

No comments: