Saturday, August 17, 2013

Send Calendar Meeting request in C#

To send Calendar meeting request through code first we need to format string in the form of iCalendar Outlook event. Then we have create a AlternateView object of Calendar MIME type with the formatted string. Now if we add this object to the Mail message, user will receive email in the format of Outlook Event.

Framing the String in iCalendar format and Sending Email
StringBuilder sw = new StringBuilder();        
sw.AppendLine("BEGIN:VCALENDAR");
sw.AppendLine("VERSION:2.0");
sw.AppendLine("METHOD:PUBLISH");
sw.AppendLine("BEGIN:VEVENT");
sw.AppendLine("CLASS:PUBLIC");
sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmss}", DateTime.UtcNow));
sw.AppendLine("DESCRIPTION: " + desc);
sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmss}", eventendDT));
sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmss}", eventstartDT));
sw.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", SPContext.Current.Web.CurrentUser.Email));
sw.AppendLine("SEQUENCE:0");
sw.AppendLine("UID:" + Guid.NewGuid().ToString());
if (lblIntLocation != null && lblIntLocation.Text != "")
    sw.AppendLine("LOCATION:" + lblIntLocation.Text);
if (lblCandidateName != null && lblCandidateName.Text != "")
    sw.AppendLine("SUMMARY;LANGUAGE=en-us: Scheduled for " + lblCandidateName.Text);
else
    sw.AppendLine("SUMMARY;LANGUAGE=en-us: Scheduled");

sw.AppendLine("BEGIN:VALARM");
sw.AppendLine("TRIGGER:-PT15M");
sw.AppendLine("ACTION:DISPLAY");
sw.AppendLine("DESCRIPTION:Reminder");
sw.AppendLine("END:VALARM");
sw.AppendLine("END:VEVENT");
sw.AppendLine("END:VCALENDAR");   

string from = SPContext.Current.Web.Site.WebApplication.OutboundMailSenderAddress;

string smtpAddress = SPContext.Current.Web.Site.WebApplication.OutboundMailServiceInstance.Server.Address;

// Assign SMTP address 
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = smtpAddress;

MailMessage mailMessage = new MailMessage(from, toRecipients);
mailMessage.Subject = subject;

// Create the Alternate view object with Calendar MIME type
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("method", "REQUEST");

//Provide the framed string here
AlternateView avCal = AlternateView.CreateAlternateViewFromString(sw.ToString(), ct);
mailMessage.AlternateViews.Add(avCal);

smtpClient.Send(mailMessage);
Check this article to create downloadable iCalendar files in C#
Related Posts Plugin for WordPress, Blogger...