Работа с элементами календаря Outlook

Работа с MapiCalendar

Класс MapiCalendar библиотеки Aspose.Email предоставляет методы и атрибуты для установки различных свойств элемента календаря. В этой статье приведены примеры кода для:

Создание и сохранение элементов календаря

Следующий фрагмент кода показывает, как создать и сохранить элемент календаря в формате ICS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
// Create the appointment
MapiCalendar calendar = new MapiCalendar(
"LAKE ARGYLE WA 6743",
"Appointment",
"This is a very important meeting :)",
new DateTime(2012, 10, 2, 13, 0, 0),
new DateTime(2012, 10, 2, 14, 0, 0));
calendar.Save(dataDir + "CalendarItem_out.ics", AppointmentSaveFormat.Ics);

Сохранение элемента календаря в формате MSG

Следующий фрагмент кода показывает, как сохранить элемент календаря в формате MSG.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
calendar.Save(dataDir + "CalendarItemAsMSG_out.Msg", AppointmentSaveFormat.Msg);

Настройка идентификатора продукта при сохранении MapiCalendar в ICS

Свойство ProductIdentifier класса MapiCalendarIcsSaveOptions используется для сохранения элемента MAPI календаря в файле iCalendar (ICS), сохраняя оригинальную информацию о дате и времени, а также пользовательский идентификатор продукта. Свойство указывает идентификатор продукта, который создал объект iCalendar.

Следующий пример кода показывает, как работать с данными iCalendar (ICS) в объекте MAPI календаря:

var icsSaveOptions = new MapiCalendarIcsSaveOptions
{
    KeepOriginalDateTimeStamp = true,
    ProductIdentifier = "Foo Ltd"
};

mapiCalendar.Save("my.ics", icsSaveOptions);

Получение общего количества событий

Класс CalendarReader позволяет легко обрабатывать события календаря. Следующие свойства и метод позволяют работать с несколькими событиями:

  • CalendarReader.Count - Свойство Count класса CalendarReader позволяет получить количество компонентов Vevent (событий), присутствующих в календаре, что упрощает отслеживание общего числа событий.
  • CalendarReader.IsMultiEvents - Это свойство определяет, содержит ли календарь несколько событий. Оно возвращает булево значение, указывающее, содержит ли календарь более одного события, что помогает выявить календари с одиночными или множественными событиями.
  • CalendarReader.Method - Свойство Method получает тип метода iCalendar, связанный с объектом календаря. Оно возвращает тип метода, такой как “REQUEST,” “PUBLISH,” или “CANCEL,” предоставляя ценную информацию о назначении календаря.
  • CalendarReader.Version - Получает версию iCalendar.
  • CalendarReader.LoadAsMultiple() Этот метод позволяет загрузить список событий из календаря, содержащего несколько событий. Он возвращает список объектов Appointment, что позволяет легко получать доступ и обрабатывать каждое событие индивидуально.

Следующий пример кода демонстрирует, как вы можете реализовать эти возможности в вашем проекте:

var reader = new CalendarReader(fileName);
Console.WriteLine("Календарь содержит " + reader.Count + " событий");
Console.WriteLine("Версия календаря " + reader.Version);
Console.WriteLine("Метод календаря " + reader.Method);
Console.WriteLine("Содержит ли календарь несколько событий? - " + reader.IsMultiEvents);
List<Appointment> appointments = reader.LoadAsMultiple();

Добавление визуального напоминания в календарь

Следующий фрагмент кода показывает, как добавить визуальное напоминание в календарь.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
// Create Appointment
Appointment app = new Appointment("Home", DateTime.Now.AddHours(1), DateTime.Now.AddHours(1), "organizer@domain.com", "attendee@gmail.com");
MailMessage msg = new MailMessage();
msg.AddAlternateView(app.RequestApointment());
MapiMessage mapi = MapiMessage.FromMailMessage(msg);
MapiCalendar calendar = (MapiCalendar)mapi.ToMapiMessageItem();
// Set calendar Properties
calendar.ReminderSet= true;
calendar.ReminderDelta = 45;//45 min before start of event
string savedFile = (dataDir + "calendarWithDisplayReminder.ics");
calendar.Save(savedFile, AppointmentSaveFormat.Ics);

Добавление аудионапоминания в календарь

Следующий фрагмент кода показывает, как добавить аудионапоминание в календарь.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
Appointment app = new Appointment("Home", DateTime.Now.AddHours(1), DateTime.Now.AddHours(1), "organizer@domain.com", "attendee@gmail.com");
MailMessage msg = new MailMessage();
msg.AddAlternateView(app.RequestApointment());
MapiMessage mapi = MapiMessage.FromMailMessage(msg);
MapiCalendar calendar = (MapiCalendar)mapi.ToMapiMessageItem();
// Set calendar properties
calendar.ReminderSet = true;
calendar.ReminderDelta = 58;//58 min before start of event
calendar.ReminderFileParameter = dataDir + "Alarm01.wav";
string savedFile = (dataDir + "calendarWithAudioReminder_out.ics");
calendar.Save(savedFile, AppointmentSaveFormat.Ics);

Добавление/получение вложений из файлов календаря

Следующий фрагмент кода показывает, как добавить/получить вложения из файлов календаря.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string[] files = new string[3];
files[0] = dataDir + "attachment_1.doc";
files[1] = dataDir + "download.png";
files[2] = dataDir + "Desert.jpg";
Appointment app1 = new Appointment("Home", DateTime.Now.AddHours(1), DateTime.Now.AddHours(1), "organizer@domain.com", "attendee@gmail.com");
foreach (string file in files)
{
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(file)))
{
app1.Attachments.Add(new Attachment(ms, Path.GetFileName(file)));
}
}
app1.Save(dataDir + "appWithAttachments_out.ics", AppointmentSaveFormat.Ics);
Appointment app2 = Appointment.Load(dataDir + "appWithAttachments_out.ics");
Console.WriteLine(app2.Attachments.Count);
foreach (Attachment att in app2.Attachments)
Console.WriteLine(att.Name);

Статус получателей из запроса на встречу

Следующий фрагмент кода показывает, как отобразить статус получателей из запроса на встречу.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MapiMessage message = MapiMessage.FromFile(fileName);
foreach (MapiRecipient recipient in message.Recipients)
{
Console.WriteLine(recipient.RecipientTrackStatus);
}

Создание MapiCalendarTimeZone из стандартного часового пояса

Следующий фрагмент кода показывает, как создать MapiCalendarTimeZone из стандартного часового пояса.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MapiCalendarTimeZone timeZone = new MapiCalendarTimeZone(TimeZoneInfo.Local);

Настройка напоминания с созданным событием

Напоминание может быть добавлено при создании события. Эти будильники могут срабатывать по разным критериям, например за n минут до начала расписания, повторять n раз с интервалами в n. Различные теги могут использоваться для создания этих триггеров в скрипте, заключенном между BEGIN:VALARM и END:VALARM внутри события. Существует множество вариантов настройки напоминания на событие.

Настройка напоминания с помощью добавления тегов

Следующий фрагмент кода показывает, как установить напоминание, добавив теги.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
string location = "Meeting Location: Room 5";
DateTime startDate = new DateTime(1997, 3, 18, 18, 30, 00),
endDate = new DateTime(1997, 3, 18, 19, 30, 00);
MailAddress organizer = new MailAddress("aaa@amail.com", "Organizer");
MailAddressCollection attendees = new MailAddressCollection();
attendees.Add(new MailAddress("bbb@bmail.com", "First attendee"));
Appointment target = new Appointment(location, startDate, endDate, organizer, attendees);
// Audio alarm that will sound at a precise time and
// Repeat 4 more times at 15 minute intervals:
AppointmentReminder audioReminder = new AppointmentReminder();
audioReminder.Trigger = new ReminderTrigger(new DateTime(1997, 3, 17, 13, 30, 0, DateTimeKind.Utc));
audioReminder.Repeat = 4;
audioReminder.Duration = new ReminderDuration(new TimeSpan(0, 15, 0));
audioReminder.Action = ReminderAction.Audio;
ReminderAttachment attach = new ReminderAttachment(new Uri("ftp://Host.com/pub/sounds/bell-01.aud"));
audioReminder.Attachments.Add(attach);
target.Reminders.Add(audioReminder);
// Display alarm that will trigger 30 minutes before the
// Scheduled start of the event it is
// Associated with and will repeat 2 more times at 15 minute intervals:
AppointmentReminder displayReminder = new AppointmentReminder();
ReminderDuration dur = new ReminderDuration(new TimeSpan(0, -30, 0));
displayReminder.Trigger = new ReminderTrigger(dur, ReminderRelated.Start);
displayReminder.Repeat = 2;
displayReminder.Duration = new ReminderDuration(new TimeSpan(0, 15, 0));
displayReminder.Action = ReminderAction.Display;
displayReminder.Description = "Breakfast meeting with executive team at 8:30 AM EST";
target.Reminders.Add(displayReminder);
// Email alarm that will trigger 2 days before the
// Scheduled due date/time. It does not
// Repeat. The email has a subject, body and attachment link.
AppointmentReminder emailReminder = new AppointmentReminder();
ReminderDuration dur1 = new ReminderDuration(new TimeSpan(-2, 0, 0, 0));
emailReminder.Trigger = new ReminderTrigger(dur1, ReminderRelated.Start);
ReminderAttendee attendee = new ReminderAttendee("john_doe@host.com");
emailReminder.Attendees.Add(attendee);
emailReminder.Action = ReminderAction.Email;
emailReminder.Summary = "REMINDER: SEND AGENDA FOR WEEKLY STAFF MEETING";
emailReminder.Description = @"A draft agenda needs to be sent out to the attendees to the weekly managers meeting (MGR-LIST). Attached is a pointer the document template for the agenda file.";
ReminderAttachment attach1 = new ReminderAttachment(new Uri("http://Host.com/templates/agenda.doc"));
emailReminder.Attachments.Add(attach1);
target.Reminders.Add(emailReminder);
// Procedural alarm that will trigger at a precise date/time
// And will repeat 23 more times at one hour intervals. The alarm will
// Invoke a procedure file.
AppointmentReminder procReminder = new AppointmentReminder();
procReminder.Trigger = new ReminderTrigger(new DateTime(1998, 1, 1, 5, 0, 0, DateTimeKind.Utc));
procReminder.Repeat = 23;
procReminder.Duration = new ReminderDuration(new TimeSpan(1, 0, 0));
procReminder.Action = ReminderAction.Procedure;
ReminderAttachment attach2 = new ReminderAttachment(new Uri("ftp://Host.com/novo-procs/felizano.exe"));
procReminder.Attachments.Add(attach2);
target.Reminders.Add(procReminder);
target.Save(dataDir + "savedFile_out.ics");

Преобразование EML события в MSG с HTML телом

Начиная с версии 19.3, Aspose.Email предоставляет возможность преобразовать EML события в MSG, сохраняя HTML тело события. Aspose.Email предоставляет свойство MapiConversionOptions.ForcedRtfBodyForAppointment, которое имеет значение по умолчанию true. Когда значение MapiConversionOptions.ForcedRtfBodyForAppointment установлено в true, тело события преобразуется в формат RTF. Чтобы сохранить формат тела события в формате HTML, установите значение MapiConversionOptions.ForcedRtfBodyForAppointment в false.

Следующий пример демонстрирует использование MapiConversionOptions.ForcedRtfBodyForAppointment для сохранения формата тела события в формате HTML.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Outlook directory
string dataDir = RunExamples.GetDataDir_Outlook();
MailMessage mailMessage = MailMessage.Load(dataDir + "TestAppointment.eml");
MapiConversionOptions conversionOptions = new MapiConversionOptions();
conversionOptions.Format = OutlookMessageFormat.Unicode;
// default value for ForcedRtfBodyForAppointment is true
conversionOptions.ForcedRtfBodyForAppointment = false;
MapiMessage mapiMessage = MapiMessage.FromMailMessage(mailMessage, conversionOptions);
Console.WriteLine("Body Type: " + mapiMessage.BodyType);
mapiMessage.Save(dataDir + "TestAppointment_out.msg");