管理约会:创建、加载、转换 ICS 并处理重复规则

会议邀请、日历导出和调度数据都以 iCalendar(ICS)文件形式传递。在 Aspose.Email for C++ 中,一个 VEVENT 由 Appointment 类的 Aspose::Email::Calendar 命名空间;重复规则位于 Aspose::Email::Calendar::Recurrences中得到覆盖。本篇文章侧重于基于标准的日历功能。Outlook 特有的 MapiCalendar 项目在 使用 Outlook 日历项目,以及存储在 PST 中的日历项 在 PST 文件中使用日历项目.

以下示例使用以下头文件和命名空间:

#include <MailMessage.h>
#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <AlternateView.h>
#include <AlternateViewCollection.h>
#include <ParticipationStatus.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <Mime/ContentType.h>
#include <Mapi/MapiMessage.h>
#include <Calendar/Appointment.h>
#include <Calendar/AppointmentIcsSaveOptions.h>
#include <Calendar/AppointmentMsgSaveOptions.h>
#include <Calendar/AppointmentMethodType.h>
#include <Calendar/AppointmentAction.h>
#include <Calendar/CalendarReader.h>
#include <Calendar/CalendarWriter.h>
#include <Calendar/Recurrences/CalendarRecurrence.h>
#include <Calendar/Recurrences/RecurrenceRule.h>
#include <Calendar/Recurrences/RecurrenceRuleCollection.h>
#include <Calendar/Recurrences/ByNumberCollection.h>
#include <Calendar/Recurrences/DateCollection.h>
#include <Calendar/Recurrences/WeeklyRecurrencePattern.h>
#include <Calendar/Recurrences/CalendarDay.h>
#include <Calendar/Recurrences/Frequency.h>
#include <system/guid.h>
#include <system/collections/list.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::Mime;
using namespace Aspose::Email::Calendar;
using namespace Aspose::Email::Calendar::Recurrences;

创建约会并将其保存为 ICS 或 MSG

七参数 Appointment 构造函数接受位置、摘要、描述、开始和结束时间,以及组织者作为 MailAddress 以及与会者作为 MailAddressCollection. 保存 将结果写入由选项对象指定的格式: AppointmentIcsSaveOptions 用于任何日历应用导入的 ICS 文件,或 AppointmentMsgSaveOptions 用于 Outlook MSG 项目。

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(MakeObject<MailAddress>(u"attendee@domain.com"));

SharedPtr<Appointment> appointment = MakeObject<Appointment>(
    u"Meeting Room 3 at Office Headquarters",      // location
    u"Monthly Meeting",                             // summary
    u"Please confirm your availability.",           // description
    DateTime(2025, 2, 8, 13, 0, 0),                 // start date
    DateTime(2025, 2, 8, 14, 0, 0),                 // end date
    MakeObject<MailAddress>(u"organizer@domain.com"), // organizer
    attendees);                                     // attendees

// iCalendar (ICS) output
appointment->Save(u"MonthlyMeeting.ics", MakeObject<AppointmentIcsSaveOptions>());

// Outlook MSG output
appointment->Save(u"MonthlyMeeting.msg", MakeObject<AppointmentMsgSaveOptions>());

添加 HTML 描述

iCalendar 通过 X-ALT-DESC 属性。将标记分配给 HtmlDescription;能够理解该属性的客户端显示 HTML,其他客户端回退到纯文本。 DESCRIPTION。此处使用的五参数构造函数省略了摘要和描述。

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(MakeObject<MailAddress>(u"AinaMartensson@to.com", String(u"Aina Martensson")));

SharedPtr<Appointment> appointment = MakeObject<Appointment>(
    u"Bygget 83",
    DateTime::get_UtcNow(),                 // start date
    DateTime::get_UtcNow().AddHours(1),     // end date
    MakeObject<MailAddress>(u"TintinStrom@from.com", String(u"Tintin Strom")), // organizer
    attendees);

// alternative representation of the description, written as X-ALT-DESC
appointment->set_HtmlDescription(
    u"<html>"
    u"<style type=\"text/css\">.text { font-family:'Comic Sans MS'; font-size:16px; }</style>"
    u"<body><p class=\"text\">Hi, I'm happy to invite you to our party.</p></body>"
    u"</html>");

appointment->Save(u"PartyInvitation.ics", MakeObject<AppointmentIcsSaveOptions>());

创建草稿会议请求

会议请求是嵌入邮件消息中的约会,形式为 text/calendar 生成的备用视图。若想将其保留为稍后可以完成的草稿——例如在 Outlook 中——请设置 MethodType 到 AppointmentMethodType::Publish,附加由 RequestApointment 到一个 MailMessage,将消息转换为 MAPI 并保存为 MSG。

String sender = u"test@gmail.com";
String recipient = u"test@email.com";

SharedPtr<MailMessage> message = MakeObject<MailMessage>(sender, recipient, String::Empty, String::Empty);

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(MakeObject<MailAddress>(recipient));

SharedPtr<Appointment> appointment = MakeObject<Appointment>(String::Empty, DateTime::get_Now(), DateTime::get_Now(),
    MakeObject<MailAddress>(sender), attendees);

// PUBLISH marks the request as a draft that can be completed later
appointment->set_MethodType(AppointmentMethodType::Publish);

message->AddAlternateView(appointment->RequestApointment());

SharedPtr<MapiMessage> msg = MapiMessage::FromMailMessage(message);
msg->Save(u"DraftAppointment.msg");

从 iCalendar 文本创建草稿

如果邀请已经以 iCalendar 文本形式存在——来自其他系统或模板生成——它可以封装为一个 AlternateView 与 CreateAlternateViewFromString 以及一个 text/calendar ContentType,然后以相同方式存储。

String ical =
    u"BEGIN:VCALENDAR\r\n"
    u"METHOD:PUBLISH\r\n"
    u"PRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN\r\n"
    u"VERSION:2.0\r\n"
    u"BEGIN:VEVENT\r\n"
    u"ATTENDEE;CN=test@gmail.com:mailto:test@gmail.com\r\n"
    u"DTSTART:20130220T171439\r\n"
    u"DTEND:20130220T174439\r\n"
    u"DTSTAMP:20130220T161439Z\r\n"
    u"END:VEVENT\r\n"
    u"END:VCALENDAR";

SharedPtr<MailMessage> message = MakeObject<MailMessage>(u"test@gmail.com", u"test@email.com", String::Empty, String::Empty);

// the iCalendar text becomes a text/calendar alternate view of the message
SharedPtr<AlternateView> view = AlternateView::CreateAlternateViewFromString(ical, MakeObject<ContentType>(u"text/calendar"));
message->get_AlternateViews()->Add(view);

SharedPtr<MapiMessage> msg = MapiMessage::FromMailMessage(message);
msg->Save(u"DraftFromText.msg");

自定义约会

设置与会者的参与状态

当约会作为回复写回时,每个与会者都可以携带一个 PARTSTAT 的参数出现。分配一个 ParticipationStatus 到 MailAddress 对象在添加到与会者集合之前;该值作为相应 ATTENDEE 行中。

DateTime startDate(2025, 12, 10, 10, 12, 11);
DateTime endDate(2025, 12, 13, 13, 11, 12);
SharedPtr<MailAddress> organizer = MakeObject<MailAddress>(u"aaa@amail.com", String(u"Organizer"));

SharedPtr<MailAddress> attendee1 = MakeObject<MailAddress>(u"bbb@bmail.com", String(u"First attendee"));
SharedPtr<MailAddress> attendee2 = MakeObject<MailAddress>(u"ccc@cmail.com", String(u"Second attendee"));

// the status ends up in the PARTSTAT parameter of each ATTENDEE line
attendee1->set_ParticipationStatus(ParticipationStatus::Accepted);
attendee2->set_ParticipationStatus(ParticipationStatus::Declined);

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(attendee1);
attendees->Add(attendee2);

SharedPtr<Appointment> appointment = MakeObject<Appointment>(u"Room 12", startDate, endDate, organizer, attendees);
appointment->Save(u"WithParticipationStatus.ics", MakeObject<AppointmentIcsSaveOptions>());

设置产品标识符

每个 iCalendar 文件都会在其 PRODID 属性。若要发布您自己的标识符,请设置 ProductId 在保存选项上 - 静态 默认 实例是一个方便的起点。

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(MakeObject<MailAddress>(u"second@test.com"));

SharedPtr<Appointment> appointment = MakeObject<Appointment>(u"location", u"test appointment", u"Test Description",
    DateTime::get_Today(), DateTime::get_Today().AddDays(1), MakeObject<MailAddress>(u"first@test.com"), attendees);

// the value is written to the PRODID property of the calendar
SharedPtr<AppointmentIcsSaveOptions> saveOptions = AppointmentIcsSaveOptions::get_Default();
saveOptions->set_ProductId(u"Test Corporation");

appointment->Save(u"CustomProdId.ics", saveOptions);

加载约会

静态 Load 方法解析一个 ICS 文件(也有流重载),并返回一个 Appointment 其属性反映 VEVENT。

SharedPtr<Appointment> loaded = Appointment::Load(u"MonthlyMeeting.ics");

Console::WriteLine(u"Summary: " + loaded->get_Summary());
Console::WriteLine(u"Location: " + loaded->get_Location());
Console::WriteLine(u"Description: " + loaded->get_Description());
Console::WriteLine(u"Start date: " + loaded->get_StartDate().ToString());
Console::WriteLine(u"End date: " + loaded->get_EndDate().ToString());
Console::WriteLine(u"Organizer: " + loaded->get_Organizer()->ToString());
Console::WriteLine(u"Attendees: " + loaded->get_Attendees()->ToString());

将 ICS 转换为 EML 或 MSG

ToMailMessage 将约会封装为带有日历备用视图的 MIME 消息,并且 ToMapiMessage 生成 Outlook 项目。任一结果都可以使用常规方法保存。

SharedPtr<Appointment> appointment = Appointment::Load(u"MonthlyMeeting.ics");

// MIME message carrying the invitation
SharedPtr<MailMessage> eml = appointment->ToMailMessage();
eml->Save(u"MonthlyMeeting.eml", SaveOptions::get_DefaultEml());

// Outlook MAPI message
SharedPtr<MapiMessage> msg = appointment->ToMapiMessage();
msg->Save(u"MonthlyMeetingFromIcs.msg");

检查 iCalendar 版本

Version 返回 VERSION 已加载文件的属性 - "2.0" 用于 iCalendar(RFC 5545), "1.0" 用于旧的 vCalendar 格式——因此应用程序可以根据收到的方言进行分支。

SharedPtr<Appointment> appointment = Appointment::Load(u"MonthlyMeeting.ics");

// Version holds the ICS/VCS version string, e.g. "2.0" for iCalendar
if (appointment->get_Version() == u"2.0")
{
    Console::WriteLine(u"iCalendar 2.0 file");
}

从 ICS 文件读取多个事件

日历导出通常将多个事件打包在同一文件中。 CalendarReader 遍历它们: NextEvent 前进到下一个 VEVENT 并返回 false 在末尾,而 当前 将事件公开为 Appointment.

auto appointments = MakeObject<Collections::Generic::List<SharedPtr<Appointment>>>();

SharedPtr<CalendarReader> reader = MakeObject<CalendarReader>(u"US-Holidays.ics");

// each call moves to the next VEVENT; Current exposes it as an Appointment
while (reader->NextEvent())
{
    appointments->Add(reader->get_Current());
}

Console::WriteLine(u"Events loaded: " + Convert::ToString(appointments->get_Count()));
for (SharedPtr<Appointment> appointment : appointments)
{
    Console::WriteLine(appointment->get_StartDate().ToString(u"yyyy-MM-dd") + u"  " + appointment->get_Summary());
}

将多个事件写入 ICS 文件

CalendarWriter 是输出的对应操作:每个 写入 调用会向同一 VCALENDAR 添加一个 VEVENT。该 操作 保存选项决定了 METHOD 已写入文件。释放 writer 以正确关闭日历。

SharedPtr<AppointmentIcsSaveOptions> saveOptions = MakeObject<AppointmentIcsSaveOptions>();
saveOptions->set_Action(AppointmentAction::Create);

SharedPtr<CalendarWriter> writer = MakeObject<CalendarWriter>(u"MultipleEvents.ics", saveOptions);

for (int32_t i = 0; i < 10; i++)
{
    SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
    attendees->Add(MakeObject<MailAddress>(u"receiver@domain.com"));

    SharedPtr<Appointment> appointment = MakeObject<Appointment>(String::Empty,
        DateTime::get_Now().AddDays(i), DateTime::get_Now().AddDays(i).AddHours(1),
        MakeObject<MailAddress>(u"sender@domain.com"), attendees);
    appointment->set_Description(u"Test body " + Convert::ToString(i));
    appointment->set_Summary(u"Test summary:" + Convert::ToString(i));

    // every call appends one VEVENT to the same VCALENDAR
    writer->Write(appointment);
}

writer->Dispose();

创建重复约会

一系列会议是一个带有重复模式的单一约会,附加在其 重复 属性。模式类 - DailyRecurrencePattern, WeeklyRecurrencePattern, MonthlyRecurrencePattern, YearlyRecurrencePattern - 可以通过出现次数或结束日期来构造。分配一个 UniqueId 是一种好做法:随后需要使用相同的标识符来更新或取消整个系列。示例创建了每周一、二、四的 14 场会议,并将该系列保存为 ICS。

SharedPtr<MailAddressCollection> attendees = MakeObject<MailAddressCollection>();
attendees->Add(MakeObject<MailAddress>(u"to@domain.com"));

DateTime startDate(2025, 12, 1, 17, 0, 0);
DateTime endDate(2025, 12, 1, 17, 30, 0);
SharedPtr<Appointment> appointment = MakeObject<Appointment>(u"same place", startDate, endDate,
    MakeObject<MailAddress>(u"from@domain.com"), attendees);

// keep the identifier so the series can be updated or cancelled later
appointment->set_UniqueId(Guid::NewGuid().ToString());
appointment->set_Description(u"Weekly sync");

// 14 occurrences on Monday, Tuesday and Thursday of every week
SharedPtr<WeeklyRecurrencePattern> pattern = MakeObject<WeeklyRecurrencePattern>(14);
pattern->set_StartDays(MakeArray<CalendarDay>({ CalendarDay::Monday, CalendarDay::Tuesday, CalendarDay::Thursday }));
pattern->set_Interval(1);

appointment->set_Recurrence(pattern);

appointment->Save(u"RecurringMeeting.ics", MakeObject<AppointmentIcsSaveOptions>());

生成的文件包含 RRULE:FREQ=WEEKLY;WKST=MO;INTERVAL=1;COUNT=14;BYDAY=MO,TU,TH。返回的备用视图由 UpdateAppointment 和 CancelAppointment 的构建方式与 RequestApointment 并且可以附加到随后由邮件客户端发送的消息上。

使用 iCalendar 重复模式

在 iCalendar 术语中,重复模式是对日程的紧凑描述,可据此计算各个日期——事件。RFC 5545 使用少数属性来表达它: DTSTART (模式的第一次出现和锚点), RRULE (重复规则), RDATE (要包含的额外日期), EXRULE (描述要排除日期的规则)和 EXDATE (要排除的单个日期)。仅 DTSTART 是必需的。

该 Aspose::Email::Calendar::Recurrences 命名空间直接建模如下:

解析模式并生成其出现次数

该 CalendarRecurrence(String) 构造函数接受 iCalendar 文本; GenerateOccurrences 将其展开为一个 DateCollection. 十次团队会议,每周一 10:00:

// Ten team meetings, every Monday at 10am
SharedPtr<CalendarRecurrence> pattern = MakeObject<CalendarRecurrence>(
    u"DTSTART:20040301T100000\nRRULE:FREQ=WEEKLY;COUNT=10;BYDAY=MO");

SharedPtr<DateCollection> dates = pattern->GenerateOccurrences();

for (DateTime date : dates)
{
    Console::WriteLine(date.ToString());
}

在代码中构建模式

相同的结果也可以不使用文本实现:设置起始日期,向其中添加规则 RRules 并填写其属性。该 GenerateOccurrences(int32_t) overload 限制生成的日期数量,这是请求“接下来 N 次”出现的方式。

SharedPtr<CalendarRecurrence> recurrencePattern = MakeObject<CalendarRecurrence>();
recurrencePattern->set_StartDate(DateTime(1997, 9, 10, 9, 0, 0));

// build the RRULE part programmatically
SharedPtr<RecurrenceRule> rule = recurrencePattern->get_RRules()->Add();
rule->set_Frequency(Frequency::Monthly);
rule->set_Count(20);
rule->set_Interval(18);
rule->get_ByMonthDay()->Add(MakeArray<int32_t>({ 10, 11, 12, 13, 14, 15 }));

SharedPtr<DateCollection> expectedDates = recurrencePattern->GenerateOccurrences(20);
Console::WriteLine(u"expectedDates.Count = " + Convert::ToString(expectedDates->get_Count()));

for (DateTime date : expectedDates)
{
    Console::WriteLine(u"DateTime = " + date.ToString());
}

用通俗语言描述规则

FriendlyText 将规则转换为适合用户界面的句子。下面的规则生成 “每月在本月第 1 天和倒数第 1 天重复,最多出现 2 次。”

SharedPtr<RecurrenceRule> rule = MakeObject<RecurrenceRule>();
rule->set_Frequency(Frequency::Monthly);
rule->set_Count(2);
rule->get_ByMonthDay()->Add(1);
rule->get_ByMonthDay()->Add(-1);

Console::WriteLine(rule->get_FriendlyText());

规则手册

| 计划 | RRULE | | — | — | | 每个月的最后一天(-2 会是前一天; 31 跳过较短的月份) | FREQ=MONTHLY;BYMONTHDAY=-1 | | 每个月的最后一个工作日(BYSETPOS (从列出的工作日中选择最后一个) | FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1 | | 年的最后一个星期一 | FREQ=YEARLY;BYDAY=-1MO | | 年的第一个 ISO 8601 周的星期五 | FREQ=YEARLY;BYWEEKNO=1;BYDAY=FR | | 年的第一个星期五 | FREQ=YEARLY;BYDAY=1FR |

模式中的日期和时间值

  • 一个 DATE 值的形式为 yyyyMMdd (19970714).
  • 本地 DATE-TIME (DTSTART:19980118T230000) 被称为“漂浮”,表示在当前时区的相同墙钟时间。
  • UTC DATE-TIME 带有尾部 Z (DTSTART:19980119T070000Z)。Aspose.Email 会忽略 Z 并将其视为本地时间;在 UNTIL,其中 RFC 5545 要求使用 UTC,接受上述任何形式。
  • 一个 DATE-TIME 使用以下方式限定 TZID (DTSTART;TZID=US-Eastern:19980119T020000) 也被视为本地时间; TZID 参数当前被忽略。
  • BYWEEKNO 遵循 ISO 8601:第 1 周是新年中至少有四天的第一周。仅在 FREQ=YEARLY,其取值范围为 1 到 53 以及 -1 到 -53。

另见