Sunday, June 12, 2011

How to talk to Exchange Server using .net code.

Recently, I took a task to develop a tool , which will be required to access a mailbox, and pull email from there automatically and periodically. the situation is , one of our customer, which is using our financial service, when consumer go to their website or store, and want to buy their product using finance , they will ask consumer to fill in a form, and then send the information to us by email.

In the mean time, a team had been setup in house to specifically to handle those email, as you know, this is not a good solution, thus, we would develop a series of web service and try to avoid sending email, but as a matter of fact, there is a lot problem with the security setting, firewall stuff, which apparently block the web service.  In order to test the web service, they decide to send us the xml request through email as well.

Thus my tool will be required to pull those email  from a mailbox, which email body is the xml request, and then send route the xml to our web service, in this way, we can test our web service before the infrastructure issue is resolved.

Originally I was thinking, it is quite easy, I can use POP3 to access my mailbox, but it is quite frustrating , cause we are using Exchange server 2010, and POP3 had been turned off.  but after some investigation , I found out , that in Exchange Server 2010, it provide web service, as well as some SDK, thus application can use these SDK to access the mailbox.

If you also need to interactive with your Exchange mailbox, you can think about to use this as well, it is pretty easy.

The SDK is available at the following location.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c3342fb3-fbcc-4127-becf-872c746840e1

I just want to show you how easy to access your email box using C# code.
Connect to the mail server:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("johnny.luo", "password", "domain");
service.AutodiscoverUrl("johnny.luo@*******.com.au");
go through emails

ItemView iv = new ItemView(200);
FindItemsResults<Item> result = service.FindItems(fi, iv);

send email:

EmailMessage msg = new EmailMessage(service);
                            msg.Subject = string.Format("Content {0}", ex.Message);
                         
                            msg.ToRecipients.Add("johnny.luo@******.com.au");
               
                            var att = msg.Attachments.AddItemAttachment<Item>();
                            att.Name = "XML email";
                            att.Item.MimeContent = xmlItem.EmailItem.MimeContent;
                            var att1 = msg.Attachments.AddItemAttachment<Item>();
                            att1.Name = "Plain Text email";
                            att1.Item.MimeContent = query.EmailItem.MimeContent;
                            msg.SendAndSaveCopy();