Criando compromissos ICS e enviando por e-mail com C#

0

Criar um iCal (arquivo ics) é muito simples. Neste post, mostrarei como criar um, anexá-lo à um e-mail e enviá-lo

Primeiro de tudo, este é o formato básico de parâmetros que precisamos preencher para criar um ICS

  • BEGIN:VCALENDAR
  • PRODID:-//LEEDS MUSIC SCENE//EN
  • VERSION:2.0
  • METHOD:PUBLISH
  • BEGIN:VEVENT
  • SUMMARY:BAND @ VENUE
  • PRIORITY:0
  • CATEGORIES:GIG
  • CLASS:PUBLIC
  • DTSTART:STARTTIME
  • DTEND:ENDTIME
  • URL:LINK TO LMS GIG PAGE
  • DESCRIPTION:FULL BAND LIST
  • LOCATION:VENUE
  • END:VEVENT
  • END:VCALENDAR

O calendário começa com a palavra-chave BEGIN: VCALENDAR e termina com END: VCALENDAR . Entre o calendário, você pode adicionar quantos eventos desejar, começando cada evento com BEGIN: VEVENT e terminando com END: VEVENT .

Veja como criá-lo utilizando uma StringBuilder:

     StringBuilder sb = new StringBuilder();
     string DateFormat = "yyyyMMddTHHmmssZ";
     string now = DateTime.Now.ToUniversalTime().ToString(DateFormat);

     sb.AppendLine("BEGIN:VCALENDAR");
     sb.AppendLine("PRODID:-//Compnay Inc//Product Application//EN");
     sb.AppendLine("VERSION:2.0");
     sb.AppendLine("METHOD:PUBLISH");
     DateTime dtStart = Convert.ToDateTime("01/01/2019");
     DateTime dtEnd = Convert.ToDateTime("02/02/2019");
     sb.AppendLine("BEGIN:VEVENT");
     sb.AppendLine("DTSTART:" + dtStart.ToUniversalTime().ToString(DateFormat));
     sb.AppendLine("DTEND:" + dtEnd.ToUniversalTime().ToString(DateFormat));
     sb.AppendLine("DTSTAMP:" + now);
     sb.AppendLine("UID:" + Guid.NewGuid());
     sb.AppendLine("CREATED:" + now);
     sb.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + "<b>OIII</b>");
     sb.AppendLine("LAST-MODIFIED:" + now);
     sb.AppendLine("LOCATION:" + "Sala Principal");
     sb.AppendLine("SEQUENCE:0");
     sb.AppendLine("STATUS:CONFIRMED");
     sb.AppendLine("SUMMARY:" + "Isto é uma reunião");
     sb.AppendLine("TRANSP:OPAQUE");
     sb.AppendLine("END:VEVENT");
     sb.AppendLine("END:VCALENDAR");


Para anexá-lo dentro de um e-mail, basta convertê-lo para Stream, veja o código completo:

    MailMessage message = new MailMessage();
    message.To.Add("[email protected]");
    message.From = new MailAddress("[email protected]", "Company, Inc");
    message.Subject = "subject";
    message.Body = "emailbody";
    message.BodyEncoding = UTF8Encoding.UTF8;
    message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    message.IsBodyHtml = true;
    message.IsBodyHtml = true;

    StringBuilder sb = new StringBuilder();
    string DateFormat = "yyyyMMddTHHmmssZ";
    string now = DateTime.Now.ToUniversalTime().ToString(DateFormat);

    sb.AppendLine("BEGIN:VCALENDAR");
    sb.AppendLine("PRODID:-//Compnay Inc//Product Application//EN");
    sb.AppendLine("VERSION:2.0");
    sb.AppendLine("METHOD:PUBLISH");
    DateTime dtStart = Convert.ToDateTime("01/01/2019");
    DateTime dtEnd = Convert.ToDateTime("02/02/2019");
    sb.AppendLine("BEGIN:VEVENT");
    sb.AppendLine("DTSTART:" + dtStart.ToUniversalTime().ToString(DateFormat));
    sb.AppendLine("DTEND:" + dtEnd.ToUniversalTime().ToString(DateFormat));
    sb.AppendLine("DTSTAMP:" + now);
    sb.AppendLine("UID:" + Guid.NewGuid());
    sb.AppendLine("CREATED:" + now);
    sb.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + "<b>OIII</b>");
    sb.AppendLine("LAST-MODIFIED:" + now);
    sb.AppendLine("LOCATION:" + "Sala Principal");
    sb.AppendLine("SEQUENCE:0");
    sb.AppendLine("STATUS:CONFIRMED");
    sb.AppendLine("SUMMARY:" + "Isto é uma reunião");
    sb.AppendLine("TRANSP:OPAQUE");
    sb.AppendLine("END:VEVENT");
    
    sb.AppendLine("END:VCALENDAR");


    var calendarBytes = Encoding.UTF8.GetBytes(sb.ToString());
    MemoryStream ms = new MemoryStream(calendarBytes);
    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar");
    message.Attachments.Add(attachment);

    SmtpClient smtp = new SmtpClient("xxxxxxxxx",587);
    System.Net.NetworkCredential aCred = new System.Net.NetworkCredential("[email protected]", "xxxxxxxx");
    smtp.EnableSsl = true;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = aCred;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

    smtp.Send(message)


Com isso, o sistema deverá enviar um e-mail com um arquivo ICS como anexo, que contém um compromisso/reunião. Você pode customizá-lo para colocar parâmetros dinâmicos, múltiplos remetentes etc.

Um grande abraço a todos!

Refs: https://esausilva.com/2016/11/17/create-ical-ics-files-in-c-asp-net-mvc-several-methods/

Compartilhe.

Sobre o autor

Criador do blog Código Simples e com mais 9 anos de experiência em TI, com títulos de MVP Microsoft na área de Visual Studio Development, Neo4j Top 50 Certificate, Scrum Master e MongoDB Evangelist. Atuando em funções analista, desenvolvedor, arquiteto, líder técnico e gestor de equipes. Mais informações em : http://jhonathansoares.com