Thursday, September 11, 2014

How to Load an Existing Email Message & Modify its Contents in Java Apps



This technical tip shows how to java developers can load and modify an existingemail message inside their java application using Aspose.Email Java API.  Aspose.Email API allows developer to load any existing email message and modify its contents before saving back to the disk. One notable point is to specify the MessageFormat while loading the email message from the disk. In addition, it is important to specify the correct MailMessageSaveType while saving the message back to disk.

The following sequence of steps lets you modify an existing email message:

·         Create an instance of the MailMessage class.
·         Load an existing message using the MailMessage class' load(), specifying the email' MessageFormat.
·         Get the subject using the getSubject() method, modify it and set it using the MailMessage class' setSubject() method.
·         Get the body using the getHtmlBody() method, modify it and set it using the MailMessage class' setHtmlBody() method.
·         Create an instance of the MailAddressCollection class.
·         Get recipients from the TO field into the MailAddressCollection object using the MailMessage class' getTo() method.
·         Add or remove recipients using the MailAddressCollection collection's add() and remove() methods.
·         Get recipients from the CC field into the MailAddressCollection object using the MailMessage class' getCC() method.
·         Add or remove recipients using the MailAddressCollection collection's add() and remove() methods.
·         Call the MailMessage class' save() method to save the file to disk in MSG format by specifying the correct MailMessageSaveType.

//Adding Attachments to a New 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 MSG file by specifying the MessageFormat
    MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());

    //Initialize a String variable to get the Email Subject
    String subject = email.getSubject();
    //Append some more information to Subject
    subject = subject + " This text is added to the existing subject";
    //Set the Email Subject
    email.setSubject(subject);

    //Initialize a String variable to get the Email's HTML Body
    String body = email.getHtmlBody();
    //Apppend some more information to the Body variable
    body = body + "<br> This text is added to the existing body";
    //Set the Email Body
    email.setHtmlBody(body);

    //Initialize MailAddressCollection object
    MailAddressCollection contacts = new MailAddressCollection();

    //Retrieve Email's TO list
    contacts = email.getTo();
    //Check if TO list has some values
    if (contacts.size() > 0)
    {
        //Remove the first email address
        contacts.remove(0);
        //Add another email address to collection
        contacts.add("to1@domain.com");
    }
    //Set the collection as Email's TO list
    email.setTo(contacts);

    //Initialize MailAddressCollection
    contacts = new MailAddressCollection();

    //Retrieve Email's CC list
    contacts = email.getCC();
    //Add another email address to collection
    contacts.add("cc2@domain.com");
    //Set the collection as Email's CC list
    email.setCC(contacts);

    //Save the Email message to disk by specifying the MessageFormat
    email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}

//Loading a Message with Load Options

//To load a message with specific load options, Aspose.Email provides the MessageLoadOptions class that can be used as follow:

MesageLoadOptions options = new MesageLoadOptions();
options.PrefferedTextEncoding = Encoding.getEncoding(1252);
options.setMessageFormat(MessageFormat.getMsg());
MailMessage eml = MailMessage.Load("EMAIL_497563\\test3.msg", options);

Tuesday, June 3, 2014

How to Create & Send Email Message with Voting Options inside .NET Apps

This technical tip explains how to create & send an email message with voting options inside .NET Applications. Microsoft Outlook allows users to create a poll when composed a new message. This is done by including voting options such as Yes, No, Maybe, etc. The FollowUpOptions class offered by Aspose.Email, provides the VotingButtons property that can be used to set or get the value of the voting options. This article provides a detailed example of creating a MapiMessage with voting options for creating a poll and then sending the message using Exchange Web Service (EWS) client.
Creating and Sending a Message with Voting Options
The following code sample shows how to create a new message and then send it with voting options.
[C#]
string address = "firstname.lastname@aspose.com";
using (IEWSClient client = EWSClient.GetEWSClient("https://exchange.aspose.com/ews/Exchange.asmx", "username", "password", "aspose.com"))
{
    MailMessage message = CreateTestMessage(address);
    FollowUpOptions options = new FollowUpOptions();
    options.VotingButtons = "Yes;No;Maybe;Exactly!";
    client.Send(message, options);
}

 
[VB.NET]
Dim address As String = "firstname.lastname@aspose.com"
Using client As IEWSClient = EWSClient.GetEWSClient("https://exchange.aspose.com/ews/Exchange.asmx", "username", "password", "aspose.com")
      Dim message As MailMessage = CreateTestMessage(address)
      Dim options As New FollowUpOptions()
      options.VotingButtons = "Yes;No;Maybe;Exactly!"
      client.Send(message, options)
End Using
Sample Methods Used in Examples
[C#]
private static MailMessage CreateTestMessage(string address)
{
    MailMessage eml = new MailMessage(
        address,
        address,
        "Flagged message",
        "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");
    return eml;
}

 
[VB.NET]
private static MailMessage CreateTestMessage(string address)
{
    MailMessage eml = new MailMessage(
        address,
        address,
        "Flagged message",
        "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");
    return eml;
}
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.

Tuesday, May 13, 2014

How to Create Reply, Reply All & Forward Email Messages from MSG Using C# & VB.NET

This technical tip explains how .NET developers can create RE (Reply/Reply All) and FW (Forward) email messages from a source message inside their .NET applications using Aspose.Email for .NET. IEWSClient lets developers create RE (Reply/Reply All) and FW (Forward) messages from a source message. The source message is identified by selecting a particular ExchangeMessageInfo from ExchangeMessageInfoCollection obtained by IEWSClient.ListMessages(). The other argument is the actual MailMessage to be sent as RE or FW message. In the following example, a sample account is used to send a message and then the Reply and Forward message features are demonstrated against that sample message.
To perform this task:
  • Initialize the IEWSClient object by providing valid credentials.
  • Send a few sample messages.
  • Call the IEWSClient.Reply(), IEWSClient.ReplyAll() and IEWSClient.Forward() functions to send messages
The sample code below creates RE (Reply/Reply All) and FW (Forward) messages from a source message.
[C# Code Sample]
public static IEWSClient GetEWSClient()
{
    const string mailboxUri = "https://exchange.domain.com/ews/Exchange.asmx";
    const string domain = @"";
    const string username = @"username";
    const string password = @"password";
    NetworkCredential credential = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential);
    return client;
}
public static void TestMailReFw()
{
    using (IEWSClient client = GetAsposeEWSClient2())
    {
        try
        {
            MailMessage message = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
            client.Send(message);
            // Wait for a while
            ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);
            if(messageInfoCol.Count == 1)
                Console.WriteLine("1 message in Inbox");
            else
                Console.WriteLine("Error! No message in Inbox");
            MailMessage message1 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
            client.Send(message1);
            // Wait for a while
            messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);
            if(messageInfoCol.Count == 2)
                Console.WriteLine("2 messages in Inbox");
            else
                Console.WriteLine("Error! No new message in Inbox");

            MailMessage message2 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"));
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"));
            client.Reply(message2, messageInfoCol[0]);
            client.ReplyAll(message2, messageInfoCol[0]);
            client.Forward(message2, messageInfoCol[0]);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error in program");
        }
    }
}
[VB.NET Code Sample]
Public Shared Function GetEWSClient() As IEWSClient
            Const  mailboxUri As String = "https://exchange.domain.com/ews/Exchange.asmx"
            Const  domain As String = ""
            Const  username As String = "username"
            Const  password As String = "password"
            Dim credential As New NetworkCredential(username, password, domain)
            Dim client As IEWSClient = EWSClient.GetEWSClient(mailboxUri, credential)
            Return client
End Function
Public Shared Sub TestMailReFw()
            Using client As IEWSClient = GetAsposeEWSClient2()
                        Try
                                    Dim message As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")
                                    client.Send(message)
                                    ' Wait for a while
                                    Dim messageInfoCol As ExchangeMessageInfoCollection = client.ListMessages(client.MailboxInfo.InboxUri)
                                    If messageInfoCol.Count = 1 Then
                                                Console.WriteLine("1 message in Inbox")
                                    Else
                                                Console.WriteLine("Error! No message in Inbox")
                                    End If
                                    Dim message1 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")
                                    client.Send(message1)
                                    ' Wait for a while
                                    messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri)
                                    If messageInfoCol.Count = 2 Then
                                                Console.WriteLine("2 messages in Inbox")
                                    Else
                                                Console.WriteLine("Error! No new message in Inbox")
                                    End If

                                    Dim message2 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")
                                    message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"))
                                    message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"))
                                    client.Reply(message2, messageInfoCol(0))
                                    client.ReplyAll(message2, messageInfoCol(0))
                                    client.Forward(message2, messageInfoCol(0))
                        Catch ex As Exception
                                    Console.WriteLine("Error in program")
                        End Try
            End Using
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.

Tuesday, May 6, 2014

Create & Save an Appointment in Draft Mode inside Java Applications

This technical tip shows how Java developers can create and save an appointment in draft mode inside their own applications using Aspose.Email for Java. It can be useful to create an appointment request in draft mode, so that the basic information is added and then the same draft appointment can be forwarded to other users who might make changes. Aspose.Email for Java provides the flexibility to create and save an appointment in draft mode for later use. In order to save an appointment in draft mode, the Method property of the Appointment class should be set to Publish. The following code sample demonstrates the use of this property as an example.
Create a Draft Appointment Request
[Java]
String sender = "test@gmail.com";
String recipient = "test@email.com";

MailMessage message = new MailMessage(sender, recipient, "", "");
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2012, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2012, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();

MailAddressCollection attendees = new MailAddressCollection();
attendees.add(new MailAddress("attendee_address@aspose.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);

Appointment app = new Appointment("Appointment Location", "Appointment Summary", "Appointment Description",
        startDate, endDate,
        new MailAddress("organizer_address@aspose.com", "Organizer"), attendees, expected);

//Set the Appointment as Draft
app.setMethod(AppointmentMethodType.Publish);//.Method = AppointmentMethodType.Publish;
message.addAlternateView(app.requestApointment());
MapiMessage msg = MapiMessage.fromMailMessage(message);

// Save the appointment as draft.
msg.save("Draft.msg");

Draft Appointment Creation from Text
[Java]
String ical = "BEGIN:VCALENDAR\r\nMETHOD:PUBLISH\r\nPRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nATTENDEE;CN=test@gmail.com:mailto:test@gmail.com\r\nDTSTART:20130220T171439\r\nDTEND:20130220T174439\r\nDTSTAMP:20130220T161439Z\r\nEND:VEVENT\r\nEND:VCALENDAR";
String sender = "test@gmail.com";
String recipient = "test@email.com";

MailMessage message = new MailMessage(sender, recipient, "", "");
AlternateView av = AlternateView.createAlternateViewFromString(ical, new ContentType("text/calendar"));
message.getAlternateViews().add(av);
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as draft.
msg.save("DraftAppointment.msg");

Overview: Aspose.Email for Java

Aspose.Email for Java is a Non-Graphical Java component that enables Java applications to read and write MS Outlook MSG files from within a Java application without using MS Outlook. It enables developers to create new MSG file from scratch, update an existing MSG file, read Outlook MSG file & get its properties like subject, body, recipients in to, cc and bcc, adding or removing attachment, sender information & MAPI properties.  Aspose.Email can be used with Web as well as Desktop Application.

Sunday, April 27, 2014

Set Reminder information to MapiTask & Adding Files to PST in Java Apps

What’s new in this release?

We are pleased to announce the new release of Aspose.Email for Java 4.0.0. This release not only fix the issues that our customers reported for the previous version, but also include a number of enhancements as well. Aspose.Email for Java already supported creating, saving and updating an Outlook Task. Microsoft Outlook allows adding reminder information to the created task which then triggers at the specified time and reminds the user for the activity. This month’s release of Aspose.Email for Java further enhances the MapiTask properties by providing support for adding reminder information to the created task. This includes setting reminder time for the task, specifying the audible file name that is played as reminder and reading reminder information from a MapiTask.  Aspose.Email provides vast variety of operations when it comes to work with Personal Storage (PST) files. Talking about the list of items that can be added to a PST file, it already supports adding messages, tasks, journal and notes to the PST file. This month’s release introduces a new feature of adding files to a PST folder in addition to the above mentioned Outlook items. Similar to Outlook, our API now allows to adding files to a PST and that too without installing Microsoft Outlook. In addition to the enhancements, this month’s release also includes a number of bug fixes related to message encoding, message attachments, message conversions to other formats and PST. The main improved features & bug fixes added in this release are listed below
  • Add any files (not only messages) to PST same like Microsoft Outlook.
  • Implement search of messages or folders in the PST file on certain criteria
  • Possibility to produce MHT files that use the 7-bit encoding format
  • Adding Reminder information to MapiTask
  • On Behalf of now displayed in conversion to mhtml
  • EML to XPS, Time displayed in GMT
  • PR_BODY garbled when EML converted to MSG
  • PR_BODY lost is fixed when MSG converted from EML is dragged to Outlook
  • Embedded Attachment Name is now retrieved using ImapClient
  • Issue is resolved with TNEF format
  • Incorrect conversion is fixed from EML to MSG.
  • Attachment Name now read by latest version of Aspose.Email API
  • EML to MSG: Saved MSG can now be opened in Outlook
  • HTML body lost is fixed during EML to MSG conversion
  • EML to MHTML: Attachment name absent is resolved in output
  • Setting Html body in Outlook mapi message now working with latest version
  • EML to PST: Messages are now visible in Outlook
  • Adding files to PST
Other most recent bug fixes are also included in this release.

Overview:Aspose.Email for Java 

Aspose.Email for Java is a Non-Graphical Java component that enables Java applications to read and write Microsoft Outlook documents without utilizing Microsoft Outlook. It enables developers to create new MSG file from scratch, update an existing MSG file, read Outlook MSG file & get it's properties like subject, body, recipients in to, cc and bcc, Adding or removing attachment, sender information and MAPI properties.  Aspose.Email for Java can be used with Web as well asDesktop Application.

Tuesday, April 15, 2014

Change Color Space of PDF Document & Export PDF Bookmarks to XML File

Aspose.Email lets developers manage attachments with email messages using the MailMessage and MapiMessage class. Microsoft Outlook allows you to add as well as retrieve attachments from calendar items, that is ICS. This article shows how the same can be achieved using Aspose.Email for Java for ICS files. Aspose.Email provides an attachments collection that can be used to add and retrieve attachments associated with calendar items. This article shows how to:
  • Create and add attachments to an Appointment class object.
  • Retrieve attachments information an appointment.
  • Extract attachments from an appointment.
Sample Code for Adding and Retrieving Attachments from Calendar Items
[Java]
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2012, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2012, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();

MailAddressCollection attendees = new MailAddressCollection();
attendees.add(new MailAddress("attendee_address@domain.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);

Appointment app = new Appointment("Appointment Location", "Appointment Summary", "Appointment Description",
                                                                                                            startDate, endDate,
                                                                                                            new MailAddress("organizer_address@domain.com", "Organizer"), attendees, expected);

//Attach a file from disc to this appointment
File file = new File("OutputXLS.xls");
FileInputStream fis = new FileInputStream(file);

Attachment att = new Attachment(fis, file.getName());
app.getAttachments().add(att);
fis.close();
String savedFile = "appWithAttachments.ics";
app.save(savedFile, AppointmentSaveFormat.Ics);

Appointment app2 = Appointment.load(savedFile);
System.out.println("Total Attachments: "  + app2.getAttachments().size());
for (int i=0; i< app2.getAttachments().size();i++)
{
            att = app2.getAttachments().get(i);
            System.out.println(att.getName());

        //Save the attachment to disc
        att.save(att.getName());
}

Overview: Aspose.Email for Java

Aspose.Email for Java is a Non-Graphical Java component that enables Java applications to read and write MS Outlook MSG files from within a Java application without using MS Outlook. It enables developers to create new MSG file from scratch, update an existing MSG file, read Outlook MSG file & get its properties like subject, body, recipients in to, cc and bcc, adding or removing attachment, sender information & MAPI properties.  Aspose.Email can be used with Web as well as Desktop Application.

Tuesday, April 8, 2014

How to Send Email Messages using Exchange Server & Exchange Web Services

This technical tip explains how to send email messages using exchange server & exchange web services inside .NET applications. You can send email messages using Exchange Server with the help of the tools in the Aspose.Email.Exchange. The ExchangeClient.Send() method accepts a MailMessage instance as a parameter and sends the email. Please follow the following steps to send emails using Exchange Server:
  • Create an instance of the ExchangeClient class.
  • Specify server name, username, password and domain.
  • Create an instance of the MailMessage class.
  • Specify the from, to, subject and other MailMessage properties.
  • Call the ExchangeClient.Send() method to send the email.
The sample code below sends email messages using Exchange Server.
[C# Code Sample]
// Create instance of ExchangeClient class by giving credentials
ExchangeClient client = new ExchangeClient("http://MachineName/exchange/username",
    "username", "password", "domain");
// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";
// Send the message
client.Send(msg);


[VB.NET]
‘Create instance of ExchangeClient class by giving credentials
Dim client As ExchangeClient = New ExchangeClient("http://MachineName/exchange/username", "username", "password", "domain")
' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"
' Send the message
client.Send(msg)
Send Email using Exchange Web Services
Aspose.Email provides the ExchangeWebServiceClient class to connect to Microsoft Exchange Server using Exchange Web Services. The code snippets that follow use EWS to send emails using Microsoft Exchange Server.
[C# Code Sample]
// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
// Create instance of type MailMessage
MailMessage msg = new MailMessage();
msg.From = "sender@domain.com";
msg.To = "recipient@ domain.com ";
msg.Subject = "Sending message from exchange server";
msg.HtmlBody = "<h3>sending message from exchange server</h3>";
// Send the message
client.Send(msg);


[VB.NET Code Sample]
' Create instance of EWSClient class by giving credentials
Dim client As IEWSClient = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain")
' Create instance of type MailMessage
Dim msg As MailMessage = New MailMessage()
msg.From = "sender@domain.com"
msg.To = "recipient@ domain.com "
msg.Subject = "Sending message from exchange server"
msg.HtmlBody = "<h3>sending message from exchange server</h3>"
' Send the message
client.Send(msg)
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.

Tuesday, March 18, 2014

How to Connect to Exchange Server & List Messages from Inbox Folder using IMAP

This technical tip explains how developers can connect and list messages from Inbox folder of Microsoft Exchange Server using IMAP protocol. Microsoft Exchange Server supports the IMAP protocol for accessing items in a mailbox. Use Aspose.Email's ImapClient class to connect to the Exchange Server using IMAP protocol. This article shows how. To connect to an Exchange Server using IMAP, please first, make sure that IMAP services are enabled for your Exchange Server:
  • Open the Control Panel.
  • Go to Administrator Tools, then Services.
  • Check the status of the Microsoft Exchange IMAP4 service.
  • If it is not already running, enable/start it.
Below is the sample source code to connect and list messages from Inbox folder of Microsoft Exchange Server using IMAP protocol.
[C#]
// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("ex07sp1", "Administrator", "Evaluation1");
imapClient.Connect(true);
// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    Console.WriteLine(msgInfo.Subject);
}
// Disconnect from the server
imapClient.Disconnect();

 
[VB.NET]
' Connect to Exchange Server using ImapClient class
Dim imapClient As ImapClient = New ImapClient("ex07sp1", "Administrator", "Evaluation1")
imapClient.Connect(True)
' Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox)
' Get the list of messages
Dim msgCollection As ImapMessageInfoCollection = imapClient.ListMessages()
For Each msgInfo As ImapMessageInfo In msgCollection
    Console.WriteLine(msgInfo.Subject)
Next msgInfo
' Disconnect from the server
imapClient.Disconnect()
Programming Samples for SSL
If the Exchange Server uses SSL, modify the above code as follows:
[C#]
private void ConnectUsingSSL()
{
// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", new RemoteCertificateValidationCallback(RemoteCertificateValidationHandler));
imapClient.EnableSsl = true;
imapClient.SecurityMode = ImapSslSecurityMode.Implicit;
imapClient.Connect(true);
lstLog.Items.Add("Connected to Exchange server");
// Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    Console.WriteLine(msgInfo.Subject);
}
// Disconnect from the server
imapClient.Disconnect();
}
// Certificate verification handler
private bool RemoteCertificateValidationHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true; //ignore the checks and go ahead
}
[VB.NET]
' Connect to Exchange Server using ImapClient class
Dim imapClient As ImapClient = New ImapClient("ex07sp1", 993, "Administrator", "Evaluation1", New RemoteCertificateValidationCallback(AddressOf RemoteCertificateValidationHandler))
imapClient.EnableSsl = True
imapClient.SecurityMode = ImapSslSecurityMode.Implicit
imapClient.Connect(True)
Console.WriteLine("Connected to Exchange server")
' Select the Inbox folder
imapClient.SelectFolder(ImapFolderInfo.InBox)
' Get the list of messages
Dim msgCollection As ImapMessageInfoCollection = imapClient.ListMessages()
For Each msgInfo As ImapMessageInfo In msgCollection
    Console.WriteLine(msgInfo.Subject)
Next msgInfo
' Disconnect from the server
imapClient.Disconnect()
' Certificate verification handler
Private Function RemoteCertificateValidationHandler(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean
    Return True 'ignore the checks and go ahead
End Function


Programming Sample - Saving One Message Only
After connecting to an Exchange server using IMAP and getting the IMapMessageInfoCollection, you can use the MessageInfo object's sequence number to save a specific message as follow:
[C#]
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.ListMessages();
foreach (ImapMessageInfo msgInfo in msgCollection)
{
    //Fetch the message from inbox using its SequenceNumber from msgInfo
    MailMessage msg = imapClient.FetchMessage(msgInfo.SequenceNumber);
    //Save the message to disc now
    msg.Save(msgInfo.SequenceNumber + ".msg", MailMessageSaveType.OutlookMessageFormat);
}

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.

Tuesday, March 4, 2014

Add, Delete, Update or Move Appointments in Google Calendars using .NET

This technical tip explains how developers can use Gmail Calendars to add, retrieve delete, move or update Appointments in their own .NET applications using Aspose.Email.   Aspose.Email provides features for working with Appointments in Google calendars. Following is the list of tasks that can be performed on appointments in Google calendar:
  1. Add Appointments
  2. Retrieve list off appointments
  3. Retrieve particular appointment
  4. Update an appointment
  5. Move appointment from one calendar to another
  6. Delete appointment
IGmailClient provides functions like CreateAppointment, FetchAppointment, UpdateAppointment, ListAppointments, MoveAppointment and DeleteAppointment.

Adding an appointment

Following code sample demonstrates the feature of adding an appointment in a calendar.
[C#]
//get access token
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret");
string accessToken = GoogleOAuthHelper.GetAccessToken(User2);
//Get IGmailclient
using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(accessToken))
{
    //Create local calendar
    Calendar calendar1 = new Calendar(
        "summary - " + Guid.NewGuid().ToString(),
        null,
        null,
        "Europe/Kiev");
    //Insert calendar and get id of inserted calendar
    string id = client.CreateCalendar(calendar1);

    //Get back calendar using an id
    Calendar cal1 = client.FetchCalendar(id);
    string calendarId1 = cal1.Id;
    try
    {
        //Retrieve list of appointments from the first calendar
        Appointment[] appointments = client.ListAppointments(calendarId1);

        //It shall be zero
        if (appointments.Length > 0)
        {
            Console.WriteLine("Wrong number of appointments");
            return;
        }

        //Get current time and Calculate time after an hour from now
        DateTime startDate = DateTime.Now;
        DateTime endDate = startDate.AddHours(1);

        //Initialize a mail address collection and set attendees mail address
        MailAddressCollection attendees = new MailAddressCollection();
        attendees.Add("User1.EMail@domain.com");
        attendees.Add("User3.EMail@domain.com");

        //create an appointment with above attendees
        Appointment app1 = new Appointment(
            "Location - " + Guid.NewGuid().ToString(),
            startDate,
            endDate,
            User2.EMail,
            attendees);

        //Set appointment summary, description, start/end time zone
        app1.Summary = "Summary - " + Guid.NewGuid().ToString();
        app1.Description = "Description - " + Guid.NewGuid().ToString();
        app1.StartTimeZone = "Europe/Kiev";
        app1.EndTimeZone = "Europe/Kiev";

        //Insert appointment in the first calendar inserted above and get back inserted appointment
        Appointment app2 = client.CreateAppointment(calendarId1, app1);

        //Retrieve appointment using unique id
        Appointment app3 = client.FetchAppointment(calendarId1, app2.UniqueId);

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}


Retrieve and update appointment

Here retrieving and updating of calendar is demonstrated as follows:
[C#]
static void UpdateAppointment(string calendarId, string AppointmentUniqueId)
{
    //get access token
    GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret");
    string accessToken = GoogleOAuthHelper.GetAccessToken(User2);
    //Get IGmailclient
    using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(accessToken))
    {
        //Retrieve Appointment
        Appointment app3 = client.FetchAppointment(calendarId, AppointmentUniqueId);
        //Change the appointment information
        app3.Summary = "New Summary - " + Guid.NewGuid().ToString();
        app3.Description = "New Description - " + Guid.NewGuid().ToString();
        app3.Location = "New Location - " + Guid.NewGuid().ToString();
        app3.Flags = AppointmentFlags.AllDayEvent;
        app3.StartDate = DateTime.Now.AddHours(2);
        app3.EndDate = app3.StartDate.AddHours(1);
        app3.StartTimeZone = "Europe/Kiev";
        app3.EndTimeZone = "Europe/Kiev";

        //Update the appointment and get back updated appointment
        Appointment app4 = client.UpdateAppointment(calendarId, app3);
    }
}

Move and Delete appointment

Appointment can be moved by providing the source calendar, destination calendar and unique id of appointment in the source calendar.
[C#]
static void MoveDeleteAppointment(string SourceCalendarId, string DestinationCalendarId, string TargetAppUniqueId)
{
    //get access token
    GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret");
    string accessToken = GoogleOAuthHelper.GetAccessToken(User2);
    //Get IGmailclient
    using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(accessToken))
    {
        //Retrieve the list of appointments in the destination calendar before moving the appointment
        Appointment[] appointments = client.ListAppointments(DestinationCalendarId);
        Console.WriteLine("Before moving count = " + appointments.Length);

        Appointment Movedapp = client.MoveAppointment(SourceCalendarId, DestinationCalendarId, TargetAppUniqueId);
        //Retrieve the list of appointments in the destination calendar after moving the appointment
        appointments = client.ListAppointments(DestinationCalendarId);
        Console.WriteLine("After moving count = " + appointments.Length);

        //Delete particular appointment from a calendar using unique id
        client.DeleteAppointment(DestinationCalendarId, Movedapp.UniqueId);

        //Retrieve the list of appointments. It should be one less than the earlier appointments in the destination calendar
        appointments = client.ListAppointments(DestinationCalendarId);
        Console.WriteLine("After deleting count = " + appointments.Length);

    }
}


Import appointment and retrieve instances

Appointment can be imported by providing the source calendar and appointment.
[C#]
//get access token
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret");
string accessToken = GoogleOAuthHelper.GetAccessToken(User2);
//Get IGmailClient
using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(accessToken))
{
    //Initialize calendar object
    Calendar calendar1 = new Calendar("summary - " + Guid.NewGuid().ToString(),null,null,"Europe/Kiev");

    //Insert calendar and get back id of inserted calendar
    string id = client.CreateCalendar(calendar1);

    //Fetch same calendar using id
    Calendar cal1 = client.FetchCalendar(id);

    string calendarId1 = cal1.Id;
    try
    {
        //Get list of appointments from the calendar. it should be zero.
        Appointment[] appointments = client.ListAppointments(calendarId1);
        if (appointments.Length != 0)
        {
            Console.WriteLine("Wrong number of appointments.");
        }

        //Get current time as appointment start time and add an hour to calculate appointment fisnih time
        DateTime startDate = DateTime.Now;
        DateTime endDate = startDate.AddHours(1);

        //Initialize attendees list
        MailAddressCollection attendees = new MailAddressCollection();
        attendees.Add("user1@domain.com");
        attendees.Add("user2@domain.com");

        //Create an appointment
        Appointment app1 = new Appointment("Location - " + Guid.NewGuid().ToString(),startDate,endDate,server.User2.EMail,attendees);
        app1.Summary = "Summary - " + Guid.NewGuid().ToString();
        app1.Description = "Description - " + Guid.NewGuid().ToString();
        app1.StartTimeZone = "Europe/Kiev";
        app1.EndTimeZone = "Europe/Kiev";

        //Insert appointment in the calendar and get back same appointment incase of successful insertion
        Appointment app2 = client.CreateAppointment(calendarId1, app1);

        //import the appointment from calendar 1
        Appointment app3 = client.ImportAppointment(calendarId1, app2);

        //Get list of appointment instances in calendar using appointment unique id
        Appointment[] instances = client.ListAppointmentInstances(calendarId1, app2.UniqueId);

        //get list of appointments. It should be one
        appointments = client.ListAppointments(calendarId1);
        if (appointments.Length != 1)
        {
            Console.WriteLine("Wrong number of appointments");
            return;
        }

        //Delete appointment from calendar
        client.DeleteAppointment(calendarId1, app2.UniqueId);

        //Get list of appointments from the calendar. It should be zero now.
        appointments = client.ListAppointments(calendarId1);
        if (appointments.Length != 0)
        {
            Console.WriteLine("Wrong number of appointments");
            return;
        }
    }
    finally
    {
        //Delete calendar
        client.DeleteCalendar(cal1.Id);
    }
}


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.