Trabalhando com Itens do Calendário do Outlook

Trabalhando com MapiCalendar

A classe MapiCalendar do Aspose.Email fornece métodos e atributos para definir várias propriedades de um item de calendário. Este artigo fornece amostras de código para:

Criando e Salvando Itens de Calendário

O seguinte trecho de código mostra como criar e salvar um item de calendário no formato 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);

Salvando o Item do Calendário como MSG

O seguinte trecho de código mostra como salvar o item do calendário como 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);

Definindo um Produto ID ao Salvar MapiCalendar para ICS

A propriedade ProductIdentifier da classe MapiCalendarIcsSaveOptions é usada para salvar um item de calendário MAPI em um arquivo iCalendar (ICS) preservando as informações originais de data e hora, bem como um identificador de produto personalizado. A propriedade especifica o identificador para o produto que criou o objeto iCalendar.

O seguinte exemplo de código mostra como trabalhar com dados iCalendar (ICS) dentro de um objeto de calendário MAPI:

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

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

Obtendo o número total de eventos

A classe CalendarReader permite lidar com eventos de calendário sem esforço. As seguintes propriedades e um método permitem que você trabalhe com múltiplos eventos:

  • CalendarReader.Count - A propriedade Count da classe CalendarReader permite recuperar o número de componentes Vevent (eventos) presentes no calendário, facilitando o rastreamento do número total de eventos.
  • CalendarReader.IsMultiEvents - Esta propriedade determina se o calendário contém múltiplos eventos. Ela fornece um valor booleano indicando se o calendário contém mais de um evento, ajudando a identificar calendários com eventos únicos ou múltiplos.
  • CalendarReader.Method - A propriedade Method obtém o tipo de método iCalendar associado ao objeto de calendário. Ela retorna o tipo de método, como “REQUEST,” “PUBLISH,” ou “CANCEL,” fornecendo informações valiosas sobre o propósito do calendário.
  • CalendarReader.Version - Obtém a versão do iCalendar.
  • CalendarReader.LoadAsMultiple() Este método permite carregar uma lista de eventos de um calendário contendo múltiplos eventos. Ele retorna uma lista de objetos Appointment, permitindo fácil acesso e processamento de cada evento individualmente.

O seguinte exemplo de código demonstra como você pode implementar essas capacidades em seu projeto:

var reader = new CalendarReader(fileName);
Console.WriteLine("O calendário contém " + reader.Count + " eventos");
Console.WriteLine("A versão do calendário é " + reader.Version);
Console.WriteLine("O método do calendário é " + reader.Method);
Console.WriteLine("O calendário contém múltiplos eventos? - " + reader.IsMultiEvents);
List<Appointment> appointments = reader.LoadAsMultiple();

Adicionando lembrete de exibição a um Calendário

O seguinte trecho de código mostra como adicionar um lembrete de exibição a um calendário.

// 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);

Adicionando lembrete de áudio a um Calendário

O seguinte trecho de código mostra como adicionar um lembrete de áudio a um calendário.

// 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);

Adicionar/Recuperar anexos de arquivos do Calendário

O seguinte trecho de código mostra como adicionar/recuperar anexos de arquivos do calendário.

// 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);

Status dos Recipientes de um Pedido de Reunião

O seguinte trecho de código mostra como exibir o status dos recipientes de um pedido de reunião.

// 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);
}

Criar MapiCalendarTimeZone a partir do Fuso Horário Padrão

O seguinte trecho de código mostra como criar MapiCalendarTimeZone a partir do fuso horário padrão.

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

Definindo Lembrete com o Compromisso Criado

Um lembrete pode ser adicionado quando um compromisso é criado. Esses alarmes podem ser acionados com base em diferentes critérios, como n minutos antes do agendamento começar, repetir n vezes em n intervalos. Diferentes tags podem ser usadas para criar esses gatilhos no script delimitado por BEGIN:VALARM e END:VALARM dentro de um compromisso. Existem várias variantes nas quais o lembrete pode ser definido em um compromisso.

Definindo um Lembrete Adicionando Tags

O seguinte trecho de código mostra como definir um lembrete adicionando tags.

// 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");

Converter Compromisso EML para MSG com Corpo HTML

Desde a versão 19.3, o Aspose.Email fornece a capacidade de converter Compromisso EML para MSG enquanto retém o corpo HTML do compromisso. O Aspose.Email fornece uma propriedade MapiConversionOptions.ForcedRtfBodyForAppointment que tem um valor padrão de true. Quando o valor de MapiConversionOptions.ForcedRtfBodyForAppointment é definido como true, o corpo do compromisso é convertido para o formato RTF. Para manter o formato do corpo do compromisso em HTML, defina o valor de MapiConversionOptions.ForcedRtfBodyForAppointment como false.

O seguinte exemplo demonstra o uso da propriedade MapiConversionOptions.ForcedRtfBodyForAppointment para manter o formato do corpo do compromisso em 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");