Working with Appointments

Load and Save an Appointment in ICS Format

The Appointment class in Aspose.Email for Java can be used to load an appointment in ICS format as well as to create a new appointment and save it to a disk in ICS format. In this article, we first create an appointment and save it to a disk in ICS format and then we load it.

Load an Appointment in ICS Format

To load an appointment in ICS format, the following steps are required:

  1. Create an instance of the Appointment class.
  2. Call the Load() method by providing the path of the ICS file.
  3. Read any property to get any information from the appointment (ICS file).

The following code snippets show how to load an appointment in ICS format.

Create an Appointment and Save to Disk in ICS Format

The following steps are required to create an appointment and save it in ICS format.

  1. Create an instance of the Appointment class and initialize it with this constructor.
  2. Pass the following arguments in the above constructor
    1. Attendees
    2. Description
    3. End Date
    4. Location
    5. Organizer
    6. Start Date
    7. Summary
    8. Created Date
    9. Last Modified Date 
  3. Call the Save() method and specify the file name and format in the arguments.

The appointment can be opened in Microsoft Outlook or any program that can load an ICS file. If the file is opened in Microsoft Outlook it automatically adds the appointment in the Outlook calendar.

The following code snippets show how to create and save an appointment to a disk in ICS format.

Saving Appointments to MSG Format

Aspose.Email makes it possible to save appointments directly to .msg files. The following public classes are available for customizing the saving process of apppointments:

The code sample below shows how to load an appointment from a file, and then save it in two different formats: .ics and .msg.

Appointment appointment = Appointment.load("fileName");
appointment.save("fileName.ics", new AppointmentIcsSaveOptions());
appointment.save("fileName.msg", new AppointmentMsgSaveOptions());

Create an Appointment with HTML Content

It’s a common practice to use the X-ALT-DESC header in iCalendar (RFC 5545) format. It is an extended property that provides an alternative human-readable description of a calendar item or event. This header is often used to include a plain text or HTML representation of the event description, which can be useful for compatibility with older calendar software or for providing a simplified version of the description. In cases, when the primary description is not supported or displayed correctly by the recipient’s calendar application, X-ALT-DESC header is used to provide an alternative description of the event. It allows the sender to include different representations of the event description to ensure better compatibility and accessibility across different calendar software and platforms. To create an appointment with HTML content, set the HtmlDescription property to ‘true’. Try the following code sample that demonstrates how to create and define an appointment object with specific details and settings, including the date, time, location, organizer, attendees, and a formatted description:

Date startDate = new Date();
Appointment appointment = new Appointment("Bygget 83",
        startDate, // start date
        addHours(startDate, 1), // end date
        new MailAddress("TintinStrom@from.com", "Tintin Strom"), // organizer
        MailAddressCollection.to_MailAddressCollection(
                new MailAddress("AinaMartensson@to.com", "Aina Martensson"))); // attendee
appointment.setHtmlDescription("<html>\n"
        + "     <style type=\"\"text/css\"\">\n"
        + "      .text {\n"
        + "             font-family:'Comic Sans MS';\n"
        + "             font-size:16px;\n"
        + "            }\n"
        + "     </style>\n"
        + "    <body>\n"
        + "     <p class=\"\"text\"\">Hi, I'm happy to invite you to our party.</p>\n"
        + "    </body>\n"
        + "    </html>");

Create a Draft Appointment Request

In order to save an appointment in a 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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-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(2016, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2016, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee_address@aspose.com", "Attendee"));
//WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);
Appointment app = new Appointment("", startDate, endDate, new MailAddress("organizer_address@aspose.com", "Organizer"), attendees);
/*
* 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);
message.addAlternateView(app.requestApointment());
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as draft.
msg.save(dataDir + "appointment-draft.msg");

Draft Appointment Creation from Text

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-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().addItem(av);
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as draft.
msg.save(dataDir + "DraftAppointment.msg");

Adding and Removing Attachments from Calendar Items

Aspose.Email provides an attachments collection that can be used to add and retrieve attachments associated with calendar items. This article shows how to:

  1. Create and add attachments to an Appointment class object.
  2. Retrieve attachments information from an appointment.
  3. Extract attachments from an appointment.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(AddAndRetrieveAttachmentFromCalendarItems.class) + "email/";
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2016, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2016, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(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(dataDir + "sample.xlsx");
FileInputStream fis = new FileInputStream(file);
Attachment att = new Attachment(fis, file.getName());
app.getAttachments().addItem(att);
fis.close();
String savedFile = "appWithAttachments.ics";
app.save(dataDir + savedFile, AppointmentSaveFormat.Ics);
Appointment app2 = Appointment.load(dataDir + savedFile);
System.out.println("Total Attachments: " + app2.getAttachments().size());
for (int i = 0; i < app2.getAttachments().size(); i++) {
att = app2.getAttachments().get_Item(i);
System.out.println(att.getName());
//Save the attachment to disc
att.save(dataDir + att.getName());
}

Formatting Appointments

The programming samples below demonstrate how to use the AppointmentFormattingOptions class to format text and HTML.

Programming Sample - Text Formatting

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Appointment appointment = Appointment.load(dataDir + "test.ics");
AppointmentFormattingOptions formattingOptions = new AppointmentFormattingOptions();
formattingOptions.setLocationFormat("Where: {0}");
formattingOptions.setTitleFormat("Subject: {0}");
formattingOptions.setDescriptionFormat("\r\n*~*~*~*~*~*~*~*~*~*\r\n{0}");
System.out.println(appointment.getAppointmentText(formattingOptions));

Programming Sample - HTML Formatting

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Appointment appointment = Appointment.load(dataDir + "test.ics");
AppointmentFormattingOptions formattingOptions = AppointmentFormattingOptions.createAsHtml();
formattingOptions.setLocationFormat("<FONT SIZE=2 FACE=\"Arial\"><b>Where: {0}</b></FONT><BR>");
formattingOptions.setTitleFormat("<FONT SIZE=2 FACE=\"Arial\"><b>Subject: {0}</b></FONT><BR>");
formattingOptions.setDescriptionFormat("<P><FONT SIZE=2 FACE=\"Arial\">-----------<br><i>{0}</i></FONT></P>");
System.out.println(appointment.getAppointmentText(formattingOptions));

Read Multiple Events from ICS File

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
List<Appointment> appointments = new ArrayList<Appointment>();
CalendarReader reader = new CalendarReader(dataDir + "US-Holidays.ics");
while (reader.nextEvent())
{
appointments.add(reader.getCurrent());
}
System.out.println("Number of events read: " + appointments.size());
//Process appointments loaded from events
//Reading events from a specific index
appointments = new ArrayList<Appointment>();
AppointmentLoadOptions options = new AppointmentLoadOptions();
options.setEventIndex(4);
reader = new CalendarReader(dataDir + "US-Holidays.ics", options);
//start reading from 4th appointment...
while (reader.nextEvent())
{
appointments.add(reader.getCurrent());
}

Write Multiple Events from ICS File

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IcsSaveOptions saveOptions = new IcsSaveOptions();
saveOptions.setAction(AppointmentAction.Create);
CalendarWriter writer = new CalendarWriter("WirteMultipleEventsToICS_out.ics", saveOptions);
//Set the start and end date of meeting
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2018, Calendar.JUNE, 19, 19, 0, 0); //19 Jan, 2015 - 1900
Date startDate = calendar.getTime();
calendar.set(2018, Calendar.JUNE, 19, 20, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addItem(new MailAddress("recepientEmail@gmail.com"));
try {
for (int i = 0; i < 10; i++) {
//create Appointment instance
Appointment app = new Appointment("Room 112", //location
startDate, //start time
endDate, //end time
new MailAddress("organizer@domain.com"), //organizer
attendees //attendee
);
app.setDescription("Test body " + i);
app.setSummary("Test summary:" + i);
writer.write(app);
}
} finally {
writer.dispose();
}

Set Participants Status of Appointment Attendees

Aspose.Email for .NET API lets you set status of appointment attendees while formulating a reply message. This adds the PARTSTAT property to the ICS file.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String location = "Room 5";
java.util.Calendar c = java.util.Calendar.getInstance();
c.set(2011, 11, 10, 10, 12, 11);
Date startDate = c.getTime();
c.set(2012, 10, 13, 13, 11, 12);
Date endDate = c.getTime();
MailAddress organizer = new MailAddress("aaa@amail.com", "Organizer");
MailAddressCollection attendees = new MailAddressCollection();
MailAddress attendee1 = new MailAddress("bbb@bmail.com", "First attendee");
MailAddress attendee2 = new MailAddress("ccc@cmail.com", "Second attendee");
attendee1.setParticipationStatus(ParticipationStatus.Accepted);
attendee2.setParticipationStatus(ParticipationStatus.Declined);
attendees.addMailAddress(attendee1);
attendees.addMailAddress(attendee2);
Appointment target = new Appointment(location, startDate, endDate, organizer, attendees);

Customize Product Identifier for ICalendar

Aspose.Email for Java API allows to get or set the product identifier that created iCalendar object.

How to get around Address Validation when trying to Load Appointments

Aspose.Email for Java API allows to get around the email validation error by setting the IgnoreSmtpAddressCheck option on the AppointmentLoadOptions object and passing it in to the load call.

AppointmentLoadOptions lo = new AppointmentLoadOptions();
lo.setIgnoreSmtpAddressCheck(true);
Appointment appointment = Appointment.load("app.ics", lo);