Saturday 6 July 2013

ICS File In Salesforce

Have you ever tried sending a meeting Invitation from Salesforce using Apex Code. Below is the code to Achieve the Same.

It creates and sends an email. For any Calendar meeting the universal format for file Accepted is .ICS
and it is nothing but a string containing all the information.

I have used this file as the mail attachment and have set the Content type of email as "text/calendar"

Code Below
--------------------------------------------------------------------------------------------------------------------------

String vCal = 'BEGIN:VCALENDAR' + '\n' + 'PRODID:-//Force.com Labs//iCalendar Export//EN' + '\n' +
'VERSION:2.0' + '\n' + 'CALSCALE:GREGORIAN' + '\n' + 'METHOD:REQUEST'+ '\n'+ 'BEGIN:VEVENT'+ '\n' +
'DTSTART:20131008T103000Z' + '\n' + 'DTEND:20131008T113000Z' + '\n' + 'DTSTAMP:20091008T103839Z' + '\n' +
'ORGANIZER;CN=varun.vatsa@gmail.com:mailto:varun.vatsa@gmail.com' + '\n' + 'UID:varun.vatsa@gmail.com'+ '\n' +
'CREATED:20091008T103839Z' + '\n' + 'DESCRIPTION:something' + '\n' + 'LAST-MODIFIED:20091008T103839Z' + '\n' +
'SEQUENCE:0' + '\n' + 'STATUS:CONFIRMED' + '\n' + 'SUMMARY:Test ICS Mail Format' + + '\n' + 'TRANSP:OPAQUE' + '\n' +
'END:VEVENT'+ '\n' + 'END:VCALENDAR';
List<String> toAddresses = new List<String>();
        toAddresses.add('varun.vatsa@gmail.com');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSubject('Test');
        email.setToAddresses(toAddresses);
        email.setHtmlBody('Test');
        email.setPlainTextBody('Test');
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('rfc2445.ics');
     
        efa.setBody(blob.valueOf(vCal));
        //attachments.add(efa);
        efa.setContentType('text/calendar');
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
         Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});