Отмена запросов на встречу с помощью Календаря

Вы можете отправить запрос на отмену встречи с помощью Aspose.Email, используя объект класса Appointment. Вам необходимо иметь информацию о первоначальном запросе встречи, чтобы отменить его. Пример в этой статье сначала отправляет запрос на встречу, сохраняет информацию в базе данных, а затем отменяет запрос на основе идентификатора сообщения.

Отправка запросов на встречу

Прежде чем мы сможем отменить запросы на встречу, мы должны сначала их отправить:

  1. Сначала создайте экземпляр типа SmtpClient для отправки сообщения.
  2. Для сбора информации об участниках мы создали таблицу данных, чтобы пользователи могли вводить имена и адреса людей, которым должно быть отправлено приглашение.
  3. После выполнения цикла по коллекции Rows таблицы сохраните всю информацию об участниках в коллекцию MailAddressCollection.
  4. Создайте экземпляр класса MailMessage и необходимые свойства, такие как From, To и Subject.
  5. Создайте экземпляр типа Appointment и укажите местоположение, время начала, время окончания, организаторов и информацию об участниках.
  6. Сохраните всю информацию в базе данных SQL Server. Работа с БД выполняется в методе SaveIntoDB.

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

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
private void button1_Click(object sender, EventArgs e)
{
try
{
// Create an instance of SMTPClient
SmtpClient client = new SmtpClient(txtMailServer.Text, txtUsername.Text, txtPassword.Text);
// Get the attendees
MailAddressCollection attendees = new MailAddressCollection();
foreach (DataGridViewRow row in dgAttendees.Rows)
{
if (row.Cells["EmailAddress"].Value != null)
{
// Get names and addresses from the grid and add to MailAddressCollection
attendees.Add(new MailAddress(row.Cells["EmailAddress"].Value.ToString(),
row.Cells["FirstName"].Value.ToString() + " " + row.Cells["LastName"].Value.ToString()));
}
}
// Create an instance of MailMessage for sending the invitation
MailMessage msg = new MailMessage();
// Set from address, attendees
msg.From = txtFrom.Text;
msg.To = attendees;
// Create am instance of Appointment
Appointment app = new Appointment(txtLocation.Text, dtTimeFrom.Value, dtTimeTo.Value, txtFrom.Text, attendees);
app.Summary = "Monthly Meeting";
app.Description = "Please confirm your availability.";
msg.AddAlternateView(app.RequestApointment());
// Save the info to the database
if (SaveIntoDB(msg, app) == true)
{
// Save the message and Send the message with the meeting request
msg.Save(msg.MessageId + ".eml", SaveOptions.DefaultEml);
client.Send(msg);
MessageBox.Show("message sent");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private bool SaveIntoDB(MailMessage msg, Appointment app)
{
try
{
// Save message and Appointment information
string strSQLInsertIntoMessage = @"INSERT INTO Message (MessageID, Subject, FromEmailAddress, FromDisplayName, Body,
CalUniqueID, CalSequenceID, CalLocation, CalStartTime, CalEndTime, Caldescription, CalSummary, MeetingStatus)
VALUES ('" + msg.MessageId + "' , '" + msg.Subject + "' , '" + msg.From[0].Address + "' , '" +
msg.From[0].DisplayName + "' , '" + msg.Body + "' , '" + app.UniqueId + "' , '" + app.SequenceId + @"' ,
'" + app.Location + "' , '" + app.StartDate + "' , '" + app.EndDate + "' , '" + app.Description + @"' ,
'" + app.Summary + "' , 1); ";
ExecuteNonQuery(strSQLInsertIntoMessage);
// Save attendee information
string strSQLInsertIntoAttendees = "";
foreach (DataGridViewRow row in dgAttendees.Rows)
{
if (row.Cells["EmailAddress"].Value != null)
{
strSQLInsertIntoAttendees += "INSERT INTO Attendent (MessageID, EmailAddress, DisplayName) VALUES (" + "'" + msg.MessageId + "' , '" + row.Cells["EmailAddress"].Value + "' , '" + row.Cells["FirstName"].Value.ToString() + " " + row.Cells["LastName"].Value.ToString() + "' );";
ExecuteNonQuery(strSQLInsertIntoAttendees);
}
}
// If records are successfully inserted into the database, return true
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // Return false in case of exception
return false;
}
}

Отмена запроса на встречу

Чтобы отменить запрос на встречу, сначала получите идентификатор сообщения электронной почты. Поскольку мы сохранили эту информацию в базе данных для этого примера, мы можем легко получить ее снова. Мы использовали таблицу для загрузки всех отправленных сообщений. Скриншот формы приведен ниже:

todo:image_alt_text

  1. Выберите строку, для которой хотите отправить запрос на отмену.
  2. Нажмите Отправить запрос на отмену, чтобы отправить запрос.
  3. Код получает идентификатор из выбранной строки таблицы и запрашивает базу данных, чтобы получить информацию об участниках, сообщении и календаре.
  4. Создайте экземпляры классов Calendar и MailMessage, используя информацию, полученную из базы данных.
  5. Используйте метод Appointment.CancelAppointment(), чтобы отправить запрос на отмену.
  6. Отправьте письмо с помощью SMTP.

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

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
try
{
OpenConnection();
// Get the message ID of the selected row
string strMessageID = dgMeetings.SelectedRows[0].Cells["MessageID"].Value.ToString();
// Get the message and calendar information from the database get the attendee information
string strSQLGetAttendees = "SELECT * FROM Attendent WHERE MessageID = '" + strMessageID + "' ";
// Get the attendee information in reader
SqlDataReader rdAttendees = ExecuteReader(strSQLGetAttendees);
// Create a MailAddressCollection from the attendees found in the database
MailAddressCollection attendees = new MailAddressCollection();
while (rdAttendees.Read())
{
attendees.Add(new MailAddress(rdAttendees["EmailAddress"].ToString(), rdAttendees["DisplayName"].ToString()));
}
rdAttendees.Close();
// Get message and calendar information
string strSQLGetMessage = "SELECT * FROM [Message] WHERE MessageID = '" + strMessageID + "' ";
// Get the reader for the above query
SqlDataReader rdMessage = ExecuteReader(strSQLGetMessage);
rdMessage.Read();
// Create the Calendar object from the database information
Appointment app = new Appointment(rdMessage["CalLocation"].ToString(), rdMessage["CalSummary"].ToString(), rdMessage["CalDescription"].ToString(),
DateTime.Parse(rdMessage["CalStartTime"].ToString()), DateTime.Parse(rdMessage["CalEndTime"].ToString()), new MailAddress(rdMessage["FromEmailAddress"].ToString(), rdMessage["FromDisplayName"].ToString()), attendees);
// Create message and Set from and to addresses and Add the cancel meeting request
MailMessage msg = new MailMessage();
msg.From = new MailAddress(rdMessage["FromEmailAddress"].ToString(), "");
msg.To = attendees;
msg.Subject = "Cencel meeting";
msg.AddAlternateView(app.CancelAppointment());
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587, "user@gmail.com", "password");
smtp.Send(msg);
MessageBox.Show("cancellation request successfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
CloseConnection();
}