Работа с встречами
Загрузка и сохранение встречи в формате ICS
Этот Appointment класс в Aspose.Email для Java может использоваться для загрузки встречи в формате ICS, а также для создания новой встречи и её сохранения на диск в формате ICS. В этой статье мы сначала создаём встречу и сохраняем её на диск в формате ICS, а затем загружаем её обратно.
Загрузка встречи в формате ICS
Чтобы загрузить встречу в формате ICS, требуется выполнить следующие шаги:
- Создать экземпляр Appointment класс.
- Вызвать load() метод, указывая путь к файлу ICS.
- Прочитайте её свойства, чтобы получить информацию о встрече (файл ICS).
Следующий фрагмент кода показывает, как загрузить встречу в формате ICS.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
// Load the appointment from an ICS file
Appointment appointment = Appointment.load(dataDir + "appointment.ics");
// Read its properties
System.out.println("Summary: " + appointment.getSummary());
System.out.println("Location: " + appointment.getLocation());
System.out.println("Description: " + appointment.getDescription());
System.out.println("Start date: " + appointment.getStartDate());
System.out.println("End date: " + appointment.getEndDate());
System.out.println("Organizer: " + appointment.getOrganizer());
System.out.println("Attendees: " + appointment.getAttendees());
Создание встречи и сохранение её на диск в формате ICS
Для создания встречи и сохранения её в формате ICS требуется выполнить следующие шаги.
- Создать экземпляр Appointment класс, передавая местоположение, сводку, описание, дату начала, дату окончания, организатора и участников в его конструктор.
- Установите даты создания и последнего изменения, если они нужны в выводе.
- Вызвать save() метод, указывая имя файла и формат.
Встречу можно открыть в Microsoft Outlook или любой программе, способной загрузить файл ICS. Если файл открыт в Microsoft Outlook, он автоматически добавит встречу в календарь Outlook.
Следующий фрагмент кода демонстрирует, как создать встречу и сохранить её на диск в формате ICS.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
// Set the start and end date of the appointment
java.util.Calendar calendar = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2026, java.util.Calendar.NOVEMBER, 1, 10, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2026, java.util.Calendar.NOVEMBER, 1, 11, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee@domain.com", "Attendee"));
// Location, summary, description, start, end, organizer and attendees
Appointment appointment = new Appointment(
"Room 112",
"Monthly Meeting",
"Please confirm your attendance.",
startDate,
endDate,
new MailAddress("organizer@domain.com", "Organizer"),
attendees);
appointment.setCreatedDate(new Date());
appointment.setLastModifiedDate(new Date());
// Save it in ICS format
appointment.save(dataDir + "appointment_out.ics", AppointmentSaveFormat.Ics);
Сохранение встреч в формате MSG
Aspose.Email позволяет сохранять встречи напрямую в файлы .msg. Доступны следующие публичные классы для настройки процесса сохранения встреч:
- AppointmentMsgSaveOptions класс с дополнительными параметрами для сохранения встреч в формате msg.
- AppointmentIcsSaveOptions класс с дополнительными опциями для сохранения встречи в формате ICS. Он заменяет устаревший
IcsSaveOptions.
Приведённый ниже пример кода показывает, как загрузить встречу из файла, а затем сохранить её в двух разных форматах: .ics и .msg.
String dataDir = "data/";
Appointment appointment = Appointment.load(dataDir + "appointment.ics");
appointment.save(dataDir + "appointment_out.ics", new AppointmentIcsSaveOptions());
appointment.save(dataDir + "appointment_out.msg", new AppointmentMsgSaveOptions());
Создание встречи с HTML‑содержимым
Это распространённая практика использовать заголовок X-ALT-DESC в формате iCalendar (RFC 5545). Это расширенное свойство, предоставляющее альтернативное читаемое человеком описание элемента календаря или события. Этот заголовок часто используется для включения текстового или HTML‑представления описания события, что может быть полезно для совместимости со старым календарным ПО или для предоставления упрощённой версии описания. В случаях, когда основное описание не поддерживается или отображается некорректно в календарном приложении получателя, используется заголовок X-ALT-DESC для предоставления альтернативного описания события. Он позволяет отправителю включать разные представления описания события, обеспечивая лучшую совместимость и доступность в разных календарных программах и платформах. Чтобы создать встречу с HTML‑контентом, передайте разметку в setHtmlDescription метод. Пример кода ниже создаёт встречу с датой, временем, местом, организатором, участником и оформленным описанием:
Date startDate = new Date();
// One hour later
Date endDate = new Date(startDate.getTime() + 60 * 60 * 1000);
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("AinaMartensson@to.com", "Aina Martensson"));
Appointment appointment = new Appointment("Bygget 83",
startDate, // start date
endDate, // end date
new MailAddress("TintinStrom@from.com", "Tintin Strom"), // organizer
attendees); // attendees
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>");
Создание запроса черновика встречи
Чтобы сохранить встречу в режиме черновика, тип метода Appointment класс должен быть установлен в Publish с setMethodType. Обратите внимание на имя аксессора: в Aspose.Email для Java оно setMethodType, а не setMethod. Следующий пример кода демонстрирует его использование.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
String sender = "sender@domain.com";
String recipient = "recipient@domain.com";
MailMessage message = new MailMessage(sender, recipient, "", "");
java.util.Calendar calendar = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2026, java.util.Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2026, java.util.Calendar.DECEMBER, 1, 0, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee@domain.com", "Attendee"));
Appointment app = new Appointment("", startDate, endDate,
new MailAddress("organizer@domain.com", "Organizer"), attendees);
// Publish marks the appointment as a draft rather than a request
app.setMethodType(AppointmentMethodType.Publish);
message.addAlternateView(app.requestApointment());
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as a draft
msg.save(dataDir + "appointment-draft.msg");
Создание черновика встречи из текста
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
String ical = "BEGIN:VCALENDAR\r\n"
+ "METHOD:PUBLISH\r\n"
+ "PRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN\r\n"
+ "VERSION:2.0\r\n"
+ "BEGIN:VEVENT\r\n"
+ "ATTENDEE;CN=attendee@domain.com:mailto:attendee@domain.com\r\n"
+ "DTSTART:20130220T171439\r\n"
+ "DTEND:20130220T174439\r\n"
+ "DTSTAMP:20130220T161439Z\r\n"
+ "END:VEVENT\r\n"
+ "END:VCALENDAR";
MailMessage message = new MailMessage("sender@domain.com", "recipient@domain.com", "", "");
AlternateView av = AlternateView.createAlternateViewFromString(ical, new ContentType("text/calendar"));
message.getAlternateViews().addItem(av);
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as a draft
msg.save(dataDir + "DraftAppointment.msg");
Добавление и удаление вложений из элементов календаря
Aspose.Email предоставляет коллекцию вложений, которую можно использовать для добавления и получения вложений, связанных с элементами календаря. В этой статье показано, как:
- Создать и добавить вложения к 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 = "data/";
java.util.Calendar calendar = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2026, java.util.Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2026, java.util.Calendar.DECEMBER, 1, 0, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee@domain.com", "Attendee"));
WeeklyRecurrencePattern recurrence = new WeeklyRecurrencePattern(3);
Appointment app = new Appointment("Appointment Location", "Appointment Summary",
"Appointment Description", startDate, endDate,
new MailAddress("organizer@domain.com", "Organizer"), attendees, recurrence);
// Attach a file from disk to this appointment
File file = new File(dataDir + "sample.xlsx");
try (FileInputStream fis = new FileInputStream(file)) {
app.getAttachments().addItem(new Attachment(fis, file.getName()));
}
String savedFile = "appWithAttachments.ics";
app.save(dataDir + savedFile, AppointmentSaveFormat.Ics);
// Load it back and extract the attachments
Appointment loaded = Appointment.load(dataDir + savedFile);
System.out.println("Total Attachments: " + loaded.getAttachments().size());
for (int i = 0; i < loaded.getAttachments().size(); i++) {
Attachment att = loaded.getAttachments().get_Item(i);
System.out.println(att.getName());
// Save the attachment to disk
att.save(dataDir + att.getName());
}
Форматирование встреч
Приведённые ниже примеры кода демонстрируют, как использовать AppointmentFormattingOptions класс для форматирования текста и HTML.
Пример кода — Форматирование текста
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
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));
Пример кода — HTML‑форматирование
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
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));
Конвертировать ICS в MSG
API позволяет легко преобразовать встречу в объект сообщения. Следующий пример кода демонстрирует, как преобразовать запрос встречи в MailMessage или MapiMessage:
String dataDir = "data/";
Appointment appointment = Appointment.load(dataDir + "appRequest.ics");
MailMessage eml = appointment.toMailMessage();
MapiMessage msg = appointment.toMapiMessage();
msg.save(dataDir + "appRequest.msg");
Определить версию встречи
Чтобы определить версию встречи, используйте getVersion() метод Appointment класс. Помогает определить, на какой версии основаны файлы, обеспечивая интеграцию с другими системами и приложениями.
Следующий пример кода показывает, как использовать этот метод в вашем проекте:
Appointment app = Appointment.load("data/meeting.ics");
// The version is a string that holds the ICS/VCS version, e.g. "2.0" for iCalendar
if ("2.0".equals(app.getVersion())) {
// do something
}
Чтение нескольких событий из файла ICS
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
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());
// Reading events from a specific index
appointments = new ArrayList<Appointment>();
AppointmentLoadOptions options = new AppointmentLoadOptions();
options.setEventIndex(4);
// Start reading from the fifth event in the file
reader = new CalendarReader(dataDir + "US-Holidays.ics", options);
while (reader.nextEvent()) {
appointments.add(reader.getCurrent());
}
System.out.println("Number of events read from index 4: " + appointments.size());
Записать несколько событий в файл ICS
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
AppointmentIcsSaveOptions saveOptions = new AppointmentIcsSaveOptions();
saveOptions.setAction(AppointmentAction.Create);
CalendarWriter writer = new CalendarWriter(dataDir + "WriteMultipleEventsToICS_out.ics", saveOptions);
// Set the start and end date of the meeting
java.util.Calendar calendar = java.util.Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2026, java.util.Calendar.JUNE, 19, 19, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2026, java.util.Calendar.JUNE, 19, 20, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addItem(new MailAddress("recipient@domain.com"));
try {
for (int i = 0; i < 10; i++) {
Appointment app = new Appointment(
"Room 112", // location
startDate, // start time
endDate, // end time
new MailAddress("organizer@domain.com"), // organizer
attendees); // attendees
app.setDescription("Test body " + i);
app.setSummary("Test summary: " + i);
writer.write(app);
}
} finally {
writer.dispose();
}
Установка статуса участников встречи
Aspose.Email для Java позволяет установить статус участников встречи при формировании ответа. Это добавляет свойство PARTSTAT в файл ICS.
// 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(2026, java.util.Calendar.DECEMBER, 10, 10, 12, 11);
Date startDate = c.getTime();
c.set(2026, java.util.Calendar.DECEMBER, 10, 13, 11, 12);
Date endDate = c.getTime();
MailAddress organizer = new MailAddress("organizer@domain.com", "Organizer");
MailAddress attendee1 = new MailAddress("first@domain.com", "First attendee");
MailAddress attendee2 = new MailAddress("second@domain.com", "Second attendee");
attendee1.setParticipationStatus(ParticipationStatus.Accepted);
attendee2.setParticipationStatus(ParticipationStatus.Declined);
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(attendee1);
attendees.addMailAddress(attendee2);
Appointment target = new Appointment(location, startDate, endDate, organizer, attendees);
Настройка идентификатора продукта для iCalendar
Aspose.Email для Java позволяет получить или задать идентификатор продукта, создавшего объект iCalendar. Его можно задать на самом приёме, или на AppointmentIcsSaveOptions при сохранении.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
Appointment appointment = Appointment.load(dataDir + "appointment.ics");
// Read the product identifier that created the iCalendar object
System.out.println("Product ID: " + appointment.getProductId());
// The identifier written to the output file can be set on the appointment ...
appointment.setProductId("-//My Company//My Product//EN");
// ... or on the save options
AppointmentIcsSaveOptions saveOptions = new AppointmentIcsSaveOptions();
saveOptions.setProductId("-//My Company//My Product//EN");
appointment.save(dataDir + "appointment_out.ics", saveOptions);
Как обойти проверку адреса при загрузке встреч
Aspose.Email для Java позволяет обойти ошибку проверки электронной почты, установив IgnoreSmtpAddressCheck опция для AppointmentLoadOptions объект и передача его в вызов загрузки.
AppointmentLoadOptions lo = new AppointmentLoadOptions();
lo.setIgnoreSmtpAddressCheck(true);
Appointment appointment = Appointment.load("data/app.ics", lo);