Great Article – How to send signed email

“A question that keeps popping up is how to send signed or encrypted email using EWS. A colleague (thank-you Vladimir!) has recently put together some sample code showing how to do exactly that using the EWS Managed API.”

EWS: How to send signed email

By David Barrett (Dark Bytes Ltd.)

Advertisements

EWS API 2.1 Released

Download:

http://www.microsoft.com/en-us/download/details.aspx?id=42022

The EWS Managed API 2.1 package contains the EWS Managed API, a managed interface for developing client applications that use EWS. The EWS Managed API simplifies the implementation of applications that communicate with versions of Exchange starting with Exchange Server 2007 Service Pack 1 (SP1). Built on the EWS SOAP protocol and Autodiscover, the EWS Managed API provides a .NET interface to EWS that is easy to learn, use, and maintain.

For your convenience, the package also includes the Exchange Server 2013 token validation library. You can use the EWS Managed API and the library to build mail apps for Outlook that can be authenticated by the identity tokens issued by Exchange 2013. 

What is the Service Binding in the Exchange Web Services Managed API

The Microsoft Exchange Web Services Managed API have 2 main classes, the FOLDER Class and the ITEM Class. All these 2 need a ServiceObject in order to communicate with a Exchange Web service.

Service Binding use the Autodiscover Object in order to get a Exchange Web Service endpoint URL, something like this https://SERVER.outlook.com/EWS/Exchange.asmx.

The Folder Class

image

The Item Class

image

You can see at the TOP of the hierarchy SERVICEOBJECT that is a type of ExchangeService() Object

So what next? let’s see in more detail, what Outlook do if you add a Microsoft Exchange Account?

image

In this case Outlook will try to resolve thru Autodiscover the domain in the E-mail Address field, and get the Endpoint for the Exchange Web Service, if the credentials are OK, all user configurations and Mail will be attached to Outlook

Service Binding do the same thing, the only difference is that you will assign properties values to a ExchangeService(), and assign user information’s like the Endpoint URL in order to you can use All Objects in the FOLDER and ITEM Class

Let’s see the Method here

Enjoy EWS!

Getting the User Settings from Exchange On-Line

Here it is a sample in order to get some Keys and Values relative to the Exchange Server User Settings

public void GetBindingAndKeys()
{
try
{
	//Create Service
	ExchangeService service = new
		ExchangeService(ExchangeVersion.Exchange2010_SP1)
	{ /*Assign Credentials*/
		Credentials = new
			WebCredentials("Your-Mail", "Your-Password")
	};
	// Create an instance of the AutodiscoverService.
	AutodiscoverService ads = new AutodiscoverService
	{ /* Enable tracing.*/
		TraceEnabled = true,
		/* Set the credentials.*/
		Credentials = service.Credentials,
		/* Prevent the AutodiscoverService from */
		/*looking in the local Active Directory */
		/* for the Exchange Web Services Services SCP.*/
		EnableScpLookup = false,
		/* Specify a redirection URL validation */
		/*callback that returns true for valid URLs.*/
		RedirectionUrlValidationCallback =
			RedirectionUrlValidationCallback
	};
	// Get the Exchange Web Services URL for the user's mailbox.
	GetUserSettingsResponse userresponse = ads.GetUserSettings(
		 mUser,
		 UserSettingName.UserDN,
		 UserSettingName.UserDeploymentId,
		 UserSettingName.InternalMailboxServer,
		 UserSettingName.MailboxDN,
		 UserSettingName.PublicFolderServer,
		 UserSettingName.ActiveDirectoryServer,
		 UserSettingName.ExternalMailboxServer,
		 UserSettingName.EcpDeliveryReportUrlFragment,
		 UserSettingName.EcpPublishingUrlFragment,
		 UserSettingName.EcpTextMessagingUrlFragment,
		 UserSettingName.ExternalEwsUrl,
		 UserSettingName.CasVersion,
		 UserSettingName.EwsSupportedSchemas);
	foreach (KeyValuePair<UserSettingName, Object> 
		usersetting in userresponse.Settings)
	{                    
		Console.WriteLine("User Setting Key: " + "usersetting.Key + 
			" - " + "User Setting Value: " + 
				usersetting.Value);
	}
}
catch (AutodiscoverRemoteException ex)
{
	Console.WriteLine("Exception thrown: " + ex.Error.Message);
}
}

public bool RedirectionUrlValidationCallback(String redirectionUrl)
{
	// The default for the validation callback is to reject the URL.
	bool result;

	Uri redirectionUri = new Uri(redirectionUrl);

	// Validate the contents of the redirection URL. 
	//In this simple validation
	// callback, the redirection URL is considered 
	//valid if it is using HTTPS
	// to encrypt the authentication credentials. 
	if (redirectionUri.Scheme == "https")
		result = true;
	else
		result = false;
	return result;
}

How to reply a message with Outlook Live

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

 /// <summary>
/// Replies the message.
/// </summary>
/// <param name="messId">The mess id.</param>
/// <param name="body">The body.</param>
/// <param name="replyAll">if set to <c>true</c> [reply all].</param>
/// <returns></returns>
public static bool ReplyMessage(string messId, string body, bool replyAll)
{
	Item mess = Item.Bind(GetBinding(), messId);
	EmailMessage message = mess as EmailMessage;
	if (message != null)
	{
		MessageBody messageBody = new MessageBody(BodyType.HTML, body);
		message.Reply(messageBody, replyAll);
		return true;
	}
	return false;
}

Get the Message Date Received

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

/// <summary>
/// Gets the message date received.
/// </summary>
/// <param name="messId">The mess id.</param>
/// <returns></returns>
public static string GetMessageDateReceived(string messId)
{
    Item mess = Item.Bind(GetBinding(), messId);
    return mess.DateTimeReceived.ToShortDateString();
}

Get Attachments from a Message

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

GET ATTACHMENT’S COLLECTION

// Bind to an existing MyMessage item, requesting its 
//Id property plus its attachments collection.
EmailMessage myMessage = EmailMessage.Bind(GetBinding(),
    new ItemId(“Your message unique id”),
        new PropertySet(BasePropertySet.IdOnly,
            ItemSchema.Attachments));

ITERATE THROUGH ATTACHMENT’S COLLECTION

// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in myMessage.Attachments)
{
}

GET THE FILE OR ITEM ATTACHMENT INTO MEMORY

if (attachment is FileAttachment)
{
    //If it's file attachment
    FileAttachment fileAttachment = attachment as FileAttachment;
    //Load the file attachment into memory
    fileAttachment.Load();
}
else // Attachment is an item attachment.
{
    //If it's item attachment 
    ItemAttachment itemAttachment = attachment as ItemAttachment;
    //Load the item attachment into memory
    itemAttachment.Load();
}

Count Read Messages in a Folder using the WellKnownFolderName

In order to use this code you will need to get the GetBinding() method

CODE

/// <summary>
/// Obters the mensages lidas pasta.
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns></returns>
public static int ObterMensagesLidasPasta(WellKnownFolderName folder, int pageSize)
{
    ItemView view = new ItemView(pageSize, 0);
    SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);

    FindItemsResults<Item> findResults = GetBinding().FindItems(folder, sf, view);
    return findResults.Items.Count;
}

Send a Message with Recipients and Attachments

You can use in the bellow code the GetBinding() Method in order to pass as ExchangeService

Attachments are the Full Path to file in HDD

Body is HTML or Plain Text

Recipients are valid E-Mails

CODE – Return true if sent

/// <summary>
/// Envia Mensagem.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="mailTo">The mail to.</param>
/// <param name="mailCc"></param>
/// <param name="mailBcc"></param>
/// <param name="attachments"></param>
public static bool SendNewMessage(ExchangeService service, 
                  string subject, string body, 
                  List<string> mailTo, 
                  List<string> mailCc, 
                  List<string> mailBcc, 
                  List<string> attachments)
{
    // Create an e-mail message and identify the Exchange service.
    EmailMessage message = new EmailMessage(service)
    {
        /* Subject*/
        Subject = subject, /* Body*/
        Body = new MessageBody(body)
    };

    // Recipients
    foreach (string recipientes in mailTo)
    {
        message.ToRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string recipientes in mailCc)
    {
        message.CcRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string recipientes in mailBcc)
    {
        message.BccRecipients.Add(recipientes);
    }

    // Recipients
    foreach (string att in attachments)
    {
        message.Attachments.AddFileAttachment(att);
    }
    // Send the mail. This makes a trip to the EWS server.
    message.SendAndSaveCopy();
    return true;
}

Delete a Message and Move it to Deleted Items

In order to use this code you will need to get the GetBinding() method and understand how to get a message item UniqueId

CODE – Return True if deleted

/// <summary>
/// Deletes the message.
/// </summary>
/// <param name="messId">The mess id.</param>
public static bool DeleteMessage(string messId)
{
    Item mess = Item.Bind(GetBinding(), messId);
    EmailMessage message = mess as EmailMessage;
    if (message == null) return false;
    message.Delete(DeleteMode.MoveToDeletedItems);
    return true;
}