약속 관리: 생성, 로드, 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 to 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 파일에 기록됩니다. 작성자를 폐기하여 캘린더를 올바르게 닫으세요.

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

반복 약속 만들기

시리즈 회의는 반복 패턴이 첨부된 단일 약속입니다 Recurrence 속성. 패턴 클래스 - 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개의 팀 회의, 매주 월요일 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 속성을 채웁니다. The GenerateOccurrences(int32_t) 오버로드는 생성되는 날짜 수를 제한하며, 이는 무제한 규칙의 "다음 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 |

패턴의 날짜 및 시간 값

  • A DATE 값 형태는 yyyyMMdd (19970714).
  • 로컬 DATE-TIME (DTSTART:19980118T230000) 은 "부동"으로, 현재 시간대에 관계없이 동일한 시계 시간을 나타냅니다.
  • UTC DATE-TIME 뒤에 trailing Z (DTSTART:19980119T070000Z). Aspose.Email은 이를 무시합니다. Z 값을 로컬 시간으로 처리합니다; UNTIL, RFC 5545가 UTC를 요구하는 경우, 모든 형식이 허용됩니다.
  • A DATE-TIME 다음과 같이 지정됩니다 TZID (DTSTART;TZID=US-Eastern:19980119T020000) 은 로컬 시간으로 간주됩니다; TZID 매개변수가 현재 무시됩니다.
  • BYWEEKNO ISO 8601을 따릅니다: 1주차는 새해에 최소 4일이 포함된 첫 주입니다. 이는 다음과 함께 사용할 때만 유효합니다 FREQ=YEARLY, 값 범위는 1에서 53, -1에서 -53까지입니다.

관련 항목