Wednesday, December 18, 2013

Read Mails From Exchange Server - Send Mail - Move Mail

Just finished struggling around with a console application that reads mail for a particular account with a particular subject from Exchange server and re sends it to some other id with the same content.

Not much blah is the whole code.. Let you guys be saved atleast...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
using Microsoft.Exchange.WebServices.Data;

namespace BTROutlookConsole
    class Program
        static void Main(string[] args)
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            MessageBody messageBody = new Microsoft.Exchange.WebServices.Data.MessageBody();
            service.Credentials = new System.Net.NetworkCredential("username", "pwd", "");
            object o = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
            FolderView view = new FolderView(100);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.Traversal = FolderTraversal.Deep;
            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Inbox, view);
            foreach (Item item in findResults.Items)
                if (item.Subject.ToString().ToLower() == "SUBJECT1".ToLower())
                    messageBody = item.Body.ToString();
                    Console.WriteLine("IsNew: " + item.IsNew);
                    Console.WriteLine("To: " + item.DisplayTo);
                    Console.WriteLine("Subject: " + item.Subject);
                    Console.WriteLine("Message Body: " + item.Body.ToString());
                    Console.WriteLine("Date & Time Received: " + item.DateTimeReceived);
                    Console.WriteLine("HasAttachments: " + item.HasAttachments);
                    string mailBody = item.Body.ToString();
                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                    message.Subject = "From YesFolder";
                    message.From = new System.Net.Mail.MailAddress("", "Test Subject");
                    message.Body = mailBody;
                    message.IsBodyHtml = true;
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("");

This program assumes the Microsoft.Exchange.WebServices is added as reference to the project.

Happy programming guys..So good to c you after so long...Hey n between nowadays I am trying my luck in AX 2012 too.. So may be next time I can give you something from that.. :)

No comments: