Monday, December 16, 2013

How to Read Email Messages from Microsoft SharePoint Document library

This technical tip explains how to read email messages from a Microsoft SharePoint document library. To access files in a SharePoint document library, the SharePoint SDK must be installed on the system. The SDK provides the API necessary to log in and access files from the document library. The programming samples below assume that a Microsoft Outlook Message file (.msg) is already stored in the SharedDocument folder of the SharePoint Document Library. The SharePoint SDK is used to get the message file into a stream and then pass this stream to an instance of Aspose.Email's MailMessage class. The MailMessage class loads the stream and parses the Outlook message file. After that, access the MailMessage class' properties, for example, subject, text body, HTML body etc. to use the information in a Visual Studio project.
Reading Email Messages from SharePoint
[C#]
// Private members
private SPSite site = null;
private SPWeb web = null;
/// <summary>
/// This method is called through the delegate elevatedGetSite which is definend in button2_Click
/// </summary>
private void EstablishSharepoint()
{
    site = new SPSite("http://localhost/Site1");
    web = site.OpenWeb();
}
/// <summary>
/// Click the event of a Windows form button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
    SPSecurity.CodeToRunElevated elevatedGetSite = new SPSecurity.CodeToRunElevated(EstablishSharepoint);
    SPSecurity.RunWithElevatedPrivileges(elevatedGetSite);
    // Path to the MSG file stored in Shared Documents folder
    SPFile msgFile = web.GetFile("Shared Documents/Test.msg");
    // Read the file into a memory stream.
    MemoryStream fileStream = new MemoryStream();
    byte[] currentFileContent = msgFile.OpenBinary();
    fileStream.Write(currentFileContent, 0, currentFileContent.Length);
    fileStream.Position = 0;
    // Create an instance of the MailMessage class
    // and pass the memory stream of the MSG file to it
    MailMessage msg = MailMessage.Load(fileStream, MessageFormat.Msg);
    fileStream.Close();
    fileStream.Dispose();
    // Access the MailMessage class' public properties
    Console.WriteLine("Subject: " + msg.Subject);
    Console.WriteLine("From: " + msg.From.ToString());
    Console.WriteLine("Text Body: " + msg.TextBody);
}

 
[VB.NET]
' Private members
Private site As SPSite = Nothing
Private web As SPWeb = Nothing
''' <summary>
''' This method is called through the delegate elevatedGetSite which is definend in button2_Click
''' </summary>
Private Sub EstablishSharepoint()
    site = New SPSite("http://localhost/Site1")
    web = site.OpenWeb()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim elevatedGetSite As New SPSecurity.CodeToRunElevated(AddressOf EstablishSharepoint)
    SPSecurity.RunWithElevatedPrivileges(elevatedGetSite)
    ' The path to the MSG file stored in the Shared Documents folder
    Dim msgFile As SPFile = web.GetFile("Shared Documents/Test.msg")
    ' Read the file into a memory stream.
    Dim fileStream As New MemoryStream()
    Dim currentFileContent As Byte() = msgFile.OpenBinary()
    fileStream.Write(currentFileContent, 0, currentFileContent.Length)
    fileStream.Position = 0
    ' Create an instance of the MailMessage class
    ' and pass the memory stream of the MSG file to it
    Dim msg As MailMessage = MailMessage.Load(fileStream, MessageFormat.Msg)
    fileStream.Close()
    fileStream.Dispose()
    ' Access the MailMessage class' public properties
    Console.WriteLine("Subject: " & msg.Subject)
    Console.WriteLine("From: " & msg.From.ToString())
    Console.WriteLine("Text Body: " & msg.TextBody)
End Sub
Overview: Aspose.Email for .NET
Aspose.Email for .NET is a set of components allowing developers to easily implement email functionality within their ASP.NET web applications, web services & Windows applications. It Supports Outlook PST, EML, MSG & MHT formats. It allows developers to work with SMTP, POP3, FTP & MS Exchange servers. It supports mail merge, iCalendar, customized header & body, header information, embedded files, Twitter & many more. It makes it easy to work with HTML or plain text emails & their attachments.

Read more about Aspose.Email for .NET

    Tuesday, November 12, 2013

    C# & VB.NET Code Samples for Downloading Email Messages from Exchange Server

    This technical tip explains how developers can download messages from the Public Folders of Exchange Server using Aspose.Email for .NET. Microsoft Exchange Server lets users create public folders and post messages in them. To do this through your application, use Aspose.Email's ExchangeWebServiceClient class to connect to the Exchange Server and read and download messages and posts from public folders.  The sample source code below reads all public folders, and subfolders, and lists and downloads any messages found in these folders. This example only works with Microsoft Exchange Server 2007 or above since only these support EWS.
    Sample Code for Downloading Messages from the Public Folders of Exchange Server
    [C#]
    class Program
    {
        static string mailboxURI = "https://exchange/ews/exchange.asmx"; // EWS
        static string username = "administrator";
        static string password = "pwd";
        static string domain = "ex2013.local";

        static void Main(string[] args)
        {
            try
            {
                ReadPublicFolders();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static void ReadPublicFolders()
        {
            NetworkCredential credential = new NetworkCredential(username, password, domain);
            IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);
            ExchangeFolderInfoCollection folders = client.ListPublicFolders();
            foreach (ExchangeFolderInfo publicFolder in folders)
            {
                Console.WriteLine("Name: " + publicFolder.DisplayName);
                Console.WriteLine("Subfolders count: " + publicFolder.ChildFolderCount);
                ListMessagesFromSubFolder(publicFolder, client);
            }
        }
        private static void ListMessagesFromSubFolder(ExchangeFolderInfo publicFolder, ExchangeWebServiceClient client)
        {
            Console.WriteLine("Folder Name: " + publicFolder.DisplayName);
            ExchangeMessageInfoCollection msgInfoCollection = client.ListMessagesFromPublicFolder(publicFolder);
            foreach (ExchangeMessageInfo messageInfo in msgInfoCollection)
            {
                MailMessage msg = client.FetchMessage(messageInfo.UniqueUri);
                Console.WriteLine(msg.Subject);
                msg.Save(msg.Subject + ".msg", MailMessageSaveType.OutlookMessageFormat);
            }
            // Call this method recursively for any subfolders
            if (publicFolder.ChildFolderCount > 0)
            {
                ExchangeFolderInfoCollection subfolders = client.ListSubFolders(publicFolder);
                foreach (ExchangeFolderInfo subfolder in subfolders)
                {
                    ListMessagesFromSubFolder(subfolder, client);
                }
            }
        }
    }

     
    [VB.NET]
    Class Program
                Private Shared mailboxURI As String = "https://ex2010/ews/exchange.asmx" ' EWS
                Private Shared username As String = "administrator"
                Private Shared password As String = "pwd"
                Private Shared domain As String = "ex2010.local"

                Shared Sub Main(ByVal args As String())
                            Try
                                        ReadPublicFolders()
                            Catch ex As Exception
                                        Console.WriteLine(ex.Message)
                            End Try
                End Sub
                Private Shared Sub ReadPublicFolders()
                            Dim credential As NetworkCredential = New NetworkCredential(username, password, domain)
                            Dim client As ExchangeWebServiceClient = New ExchangeWebServiceClient(mailboxURI, credential)
                            Dim folders As ExchangeFolderInfoCollection = client.ListPublicFolders()
                            For Each publicFolder As ExchangeFolderInfo In folders
                                        Console.WriteLine("Name: " & publicFolder.DisplayName)
                                        Console.WriteLine("Subfolders count: " & publicFolder.ChildFolderCount)
                                        ListMessagesFromSubFolder(publicFolder, client)
                            Next publicFolder
                End Sub
                Private Shared Sub ListMessagesFromSubFolder(ByVal publicFolder As ExchangeFolderInfo, ByVal client As ExchangeWebServiceClient)
                            Console.WriteLine("Folder Name: " & publicFolder.DisplayName)
                            Dim msgInfoCollection As ExchangeMessageInfoCollection = client.ListMessagesFromPublicFolder(publicFolder)
                            For Each messageInfo As ExchangeMessageInfo In msgInfoCollection
                                        Dim msg As MailMessage = client.FetchMessage(messageInfo.UniqueUri)
                                        Console.WriteLine(msg.Subject)
                                        msg.Save(msg.Subject & ".msg", MailMessageSaveType.OutlookMessageFormat)
                            Next messageInfo
                            ' Call this method recursively for any subfolders
                            If publicFolder.ChildFolderCount > 0 Then
                                        Dim subfolders As ExchangeFolderInfoCollection = client.ListSubFolders(publicFolder)
                                        For Each subfolder As ExchangeFolderInfo In subfolders
                                                    ListMessagesFromSubFolder(subfolder, client)
                                        Next subfolder
                            End If
                End Sub
    End Class
    Overview: Aspose.Email for .NET
    Aspose.Email for .NET is a set of components allowing developers to easily implement email functionality within their ASP.NET web applications, web services & Windows applications. It Supports Outlook PST, EML, MSG & MHT formats. It allows developers to work with SMTP, POP3, FTP & MS Exchange servers. It supports mail merge, iCalendar, customized header & body, header information, embedded files, Twitter & many more. It makes it easy to work with HTML or plain text emails & their attachments.
    More about Aspose.Email for .NET

    Wednesday, July 17, 2013

    Read Outlook Email Template (.OFT) File & Save Message as MSG Format

    This technical tip explains how to read outlook email template File (.OFT). Outlook templates are very useful when you want to send a similar email message again and again. Instead of preparing the message from scratch each time, first prepare the message in Outlook and save it as an Outlook template (OFT). After that, whenever you need to send the message, you can create it from the template, saving time writing the same text in the body or the subject line, setting formatting and so on.
    Aspose.Email’s MailMessage class can be used to load and read an Outlook template (OFT) file. Once the Outlook template is loaded in an instance of the MailMessage class, you can update the sender, recipient, body, subject and other properties. After updating the properties:
    • Send the email using the SmtpClient class or
    • Save the message as MSG and do further updates/validation using Microsoft Outlook.
    Sample Code for loading outlook email template (.OFT) File, updating the message and saving it in MSG format
    [C#]
    // Load the Outlook template (OFT) file in MailMessage's instance
    MailMessage message = MailMessage.Load("invitation to meeting.oft", MessageFormat.Msg);

    // Set the sender and recipients information
    string senderDisplayName = "John";
    string senderEmailAddress = "john@abc.com";
    string recipientDisplayName = "William";
    string recipientEmailAddress = "william@xzy.com";

    message.Sender = new MailAddress(senderEmailAddress, senderDisplayName);
    message.To.Add(new MailAddress(recipientEmailAddress, recipientDisplayName));
    message.HtmlBody = message.HtmlBody.Replace("DisplayName", "<b>" + recipientDisplayName + "</b>");

    // Set the name, location and time in email body
    string meetingLocation = "<u>" + "Hall 1, Convention Center, New York, USA" + "</u>";
    string meetingTime = "<u>" + "Monday, June 28, 2010" + "</u>";
    message.HtmlBody = message.HtmlBody.Replace("MeetingPlace", meetingLocation);
    message.HtmlBody = message.HtmlBody.Replace("MeetingTime", meetingTime);

    // Send the email or save as MSG and open in Outlook for further editing
    SmtpClient client = new SmtpClient("host", 25, "username", "password");
    client.Send(message);

    // Save the message in MSG format and open in Office Outlook
    MapiMessage msg = MapiMessage.FromMailMessage(message);
    msg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT);
    msg.Save("Invitation.msg");
    Process.Start("Invitation.msg");


    [VB.NET]
    ' Load the Outlook template (OFT) file in MailMessage's instance
    Dim message As MailMessage = MailMessage.Load("invitation to meeting.oft", MessageFormat.Msg)

    ' Set the sender and recipients information
    Dim senderDisplayName As String = "John"
    Dim senderEmailAddress As String = "john@abc.com"
    Dim recipientDisplayName As String = "William"
    Dim recipientEmailAddress As String = "william@xzy.com"

    message.Sender = New MailAddress(senderEmailAddress, senderDisplayName)
    message.To.Add(New MailAddress(recipientEmailAddress, recipientDisplayName))
    message.HtmlBody = message.HtmlBody.Replace("DisplayName", "<b>" & recipientDisplayName & "</b>")

    ' Set the name, location and time in email body
    Dim meetingLocation As String = "<u>" & "Hall 1, Convention Center, New York, USA" & "</u>"
    Dim meetingTime As String = "<u>" & "Monday, June 28, 2010" & "</u>"
    message.HtmlBody = message.HtmlBody.Replace("MeetingPlace", meetingLocation)
    message.HtmlBody = message.HtmlBody.Replace("MeetingTime", meetingTime)

    ' Send the email or save as MSG and open in Outlook for further editing
    Dim client As SmtpClient = New SmtpClient("host", 25, "username", "password")
    client.Send(message)

    ' Save the message in MSG format and open in Office Outlook
    Dim msg As MapiMessage = MapiMessage.FromMailMessage(message)
    msg.SetMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT)
    msg.Save("Invitation.msg")
    Process.Start("Invitation.msg")

    Wednesday, July 10, 2013

    Manage Attachments in Existing & New Email Messages inside Java Apps

    This technical tip shows how to manage attachments in email message. There can be certain circumstances when the developers want to access and manipulate the Attachments of an Email Message. Aspose.Email Java API provides the handful of collections and methods to perform a task like Extraction of Attachments. Furthermore, using this API one can Add or Remove Attachments at run time. To demonstrate these features, we will load existing Email Messages from disk and access their Attachment Collection.
    Steps to Extract Attachments from an existing Email Message
    Please perform the following sequence of steps to save the Attachments from existing Messages:* Create an instance of MailMessage class.* Load the existing Email Message using the load() method exposed by MailMessage class and by specifying the correct MessageFormat.* Create an instance of AttachmentCollection class and fill it with Attachments from the instance of MailMessage using getAttachments() method.* Iterate over the AttachmentCollection.# Create an instance of Attachment class and fill it with indexed value from AttachmentCollection using get() method.# Save the attachment to disk using the save() method exposed by Attachment class.
    Adding Attachments to a New Email Message using Aspose.Email for Java 
    [Java]
    //Create an instance of MailMessage class
    MailMessage message = new MailMessage();

    //From
    message.setFrom(new MailAddress("sender@sender.com"));

    //to whom
    message.getTo().add(new MailAddress("receiver@gmail.com"));

    //Adding 1st attachment
    //Create an instance of Attachment class
    Attachment attachment;

    //Load an attachment
    attachment = new Attachment("1.txt");

    //Add attachment in instance of MailMessage class
    message.getAttachments().add(attachment);

    //Add 2nd Attachment
    message.getAttachments().add(new Attachment("1.jpg"));

    //Add 3rd Attachment
    message.getAttachments().add(new Attachment("1.doc"));

    //Add 4th Attachment
    message.getAttachments().add(new Attachment("1.rar"));

    //Add 5th Attachment
    message.getAttachments().add(new Attachment("1.pdf"));

    //Save message to disc
    message.save("output.msg",MessageFormat.getMsg());
    Extract Attachments from an existing Email Message
    public static void main(String[] args)
    {
        // Base folder for reading and writing files
        String strBaseFolder = "D:\\Data\\Aspose\\resources\\";

        //Initialize and Load an existing EML file by specifying the MessageFormat
        MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());

        //Initialize AttachmentCollection object with MailMessage Attachments
        AttachmentCollection attachments =  msg.getAttachments();

        //Iterate over the AttachmentCollection
        for(int index = 0; index < attachments.size(); index++)
        {
            //Initialize Attachment object and Get the indexed Attachment reference
            Attachment attachment = (Attachment) attachments.get(index);
            //Display Attachment Name
            System.out.println(attachment.getName());
            //Save Attachment to disk
            attachment.save(strBaseFolder + "attachment_"+ attachment.getName());
        }
    }

    Add or Remove Attachments from an existing Email Message
    public static void main(String[] args)
    {
        // Base folder for reading and writing files
        String strBaseFolder = "D:\\Data\\Aspose\\resources\\";

        //Initialize and Load an existing EML file by specifying the MessageFormat
        MailMessage message = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());

        //Initialize AttachmentCollection object with MailMessage Attachments
        AttachmentCollection attachments =  message.getAttachments();
        System.out.println("Attachment Count: " + attachments.size());

        //Check if AttachmentCollection size is greater than 0
        if(attachments.size() > 0)
        {
            //Remove Attachment from index location 0
            attachments.remove(0);
            System.out.println("Attachment Count: " + attachments.size());
        }

        //Add a PDF file as Attachment to the message
        message.addAttachment(new Attachment(strBaseFolder + "Blank.PDF"));
        System.out.println("Attachment Count: " + attachments.size());

        //Save the Email message to disk by specifying the EML MailMessageSaveType
        message.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());

    }