23 Mar 2013

Send a Meeting Request with System.Net.Mail

The calendar appointment email is just normal email attached with ics file contains appointment details.
This code will show you how to create simple ics file and how to attach it with the email.

SmtpClient sc = new SmtpClient();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("patelpc.mits@gmail.com""PC Patel");
msg.To.Add(new MailAddress("youremail@host.com""Your Name"));
msg.Subject = "Send Calendar Appointment Email";
msg.Body = "Here is the Body Content";

StringBuilder str = new StringBuilder();
str.AppendLine("BEGIN:VCALENDAR");
str.AppendLine("PRODID:-//patelpc.blogspot.in");
str.AppendLine("VERSION:2.0");
str.AppendLine("METHOD:REQUEST");
str.AppendLine("BEGIN:VEVENT");
str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime));
str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}"DateTime.UtcNow));
str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime));
str.AppendLine("LOCATION: Mumbai");
str.AppendLine(string.Format("UID:{0}"Guid.NewGuid()));
str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));

str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));

str.AppendLine("BEGIN:VALARM");
str.AppendLine("TRIGGER:-PT15M");
str.AppendLine("ACTION:DISPLAY");
str.AppendLine("DESCRIPTION:Reminder");
str.AppendLine("END:VALARM");
str.AppendLine("END:VEVENT");
str.AppendLine("END:VCALENDAR");
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("method""REQUEST");
AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct);
msg.AlternateViews.Add(avCal);

sc.Send(msg);
The calendar text lines limit is 76 character if the body or any line more than that you have to split it to more lines the first line must be 76 character and the others is 75 with tab space in the begin of the line "\t" in C# and vbTab in VB.

2 comments:

  1. I am following this method, but seems like the HTML in the body is not getting fomatted correctly. It is still showing in plain text. Any suggestions?

    ReplyDelete
  2. for the body to support html tags you need to set
    msg.IsBodyHtml = True

    hope this helps.

    ReplyDelete