Header Ads Widget

Responsive Advertisement

Send Emails with Calendar Invites (Google/Outlook) in Salesforce Using Apex

How to Send Emails with Calendar Invites (Google/Outlook) in Salesforce Using Apex
Send Calendar Invites from Salesforce

Introduction

Sending calendar invites via email is a common business requirement—whether for scheduling meetings, sending event reminders, or coordinating appointments. While Salesforce supports sending emails natively, adding calendar invites (ICS files) requires Apex integration with email services.

In this blog, you'll learn:

  • How to generate ICS files (for Google/Outlook compatibility)
  • Sending emails with attachments via Apex
  • Best practices for handling time zones and email limits
  • Troubleshooting common errors

Table of Contents

  1. Understanding ICS Files for Calendar Invites
  2. Apex Implementation
  3. Best Practices & Tips
  4. Common Errors & Fixes
  5. Performance & Security Considerations
  6. Testing & Compatibility Notes
  7. Conclusion

1. Understanding ICS Files for Calendar Invites

Calendar invites use the iCalendar (.ics) format, a universal standard supported by Google Calendar, Outlook, and Apple Calendar. An ICS file contains:

  • Event title, description, location
  • Start/end time (with timezone)
  • Attendee emails
  • Organizer details

⚠️ The Problem I Faced

My original solution worked flawlessly in Google Calendar, but in Outlook the invite wouldn't open or register as a calendar item. After investigation, I found that Outlook requires:

  • METHOD:REQUEST to be included
  • Proper \r\n (CRLF) line endings
  • Mandatory fields like UID, DTSTART, DTEND, SUMMARY
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
PRODID:-//YourCompany//Event Invite//EN
BEGIN:VEVENT
UID:uid
DTSTAMP: 20231015T090000Z
DTSTART: 20231015T100000Z
DTEND: 20231015T110000Z
SUMMARY: Salesforce Demo Meeting
DESCRIPTION:Discuss integration requirements
LOCATION:Auckland
STATUS:CONFIRMED
SEQUENCE:0
END:VEVENT
END:VCALENDAR

Workflow:

  1. Apex generates an ICS file dynamically.
  2. Email Service (SingleEmailMessage) attaches the ICS file.
  3. Recipient's Email Client (Gmail/Outlook) parses the ICS file and adds the event.

2. Apex Implementation

Generate an ICS File in Apex

public class CalendarInviteGenerator {
    public static Messaging.EmailFileAttachment createCalendarInvite(
        String subject,
        String description,
        String location,
        Datetime startTime,
        Datetime endTime
    ) {
        String uid = 'event-' + String.valueOf(Crypto.getRandomLong());

        // Escape commas and newlines
        subject = escapeText(subject);
        description = escapeText(description);
        location = escapeText(location);

        String icsBody = 
            'BEGIN:VCALENDAR\r\n' +
            'VERSION:2.0\r\n' +
            'METHOD:REQUEST\r\n' +
            'PRODID:-//YourCompany//Event Invite//EN\r\n' +
            'BEGIN:VEVENT\r\n' +
            'UID:' + uid + '\r\n' +
            'DTSTAMP:' + formatDateTime(Datetime.now()) + '\r\n' +
            'DTSTART:' + formatDateTime(startTime) + '\r\n' +
            'DTEND:' + formatDateTime(endTime) + '\r\n' +
            'SUMMARY:' + subject + '\r\n' +
            'DESCRIPTION:' + description + '\r\n' +
            'LOCATION:' + location + '\r\n' +
            'STATUS:CONFIRMED\r\n' +
            'SEQUENCE:0\r\n' +
            'END:VEVENT\r\n' +
            'END:VCALENDAR\r\n';

        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('event-invite.ics');
        attachment.setBody(Blob.valueOf(icsBody));
        attachment.setContentType('text/calendar; method=REQUEST; charset=UTF-8');
        return attachment;
    }

    private static String formatDateTime(Datetime dt) {
        return dt.formatGmt('yyyyMMdd\'T\'HHmmss\'Z\'');
    }

    private static String escapeText(String input) {
        if (String.isBlank(input)) return '';
        return input.replace(',', '\\,').replace('\n', '\\n').replace('\r', '');
    }
}

Send Email with ICS Attachment

public class EventConfirmationEmailService {
    public static void sendConfirmationEmail(
        String toAddress,
        String eventName,
        String location,
        Datetime startTime,
        Datetime endTime
    ) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        email.setToAddresses(new String[] { toAddress });
        email.setSubject('You are Registered: ' + eventName);
        email.setPlainTextBody('Thank you for registering! Please find the event invite attached.');

        Messaging.EmailFileAttachment invite = CalendarInviteGenerator.createCalendarInvite(
            eventName,
            'You are invited to attend ' + eventName,
            location,
            startTime,
            endTime
        );

        email.setFileAttachments(new Messaging.EmailFileAttachment[] { invite });

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
    }
}

3. Best Practices & Tips

  • Time Zone Handling: Always use GMT in ICS files to avoid time discrepancies.
  • Batch Processing: If sending invites in bulk, use Batch Apex to avoid governor limits.
  • Error Logging: Log failed email sends in a custom object for debugging.
  • Testing: Use Test.setMock for email testing in unit tests.
  • Opt-Out Mechanism: Allow recipients to unsubscribe from calendar invites.

4. Common Errors & Fixes

Error Solution
ICS file not recognized Ensure Content-Type: text/calendar is set.
Time zone mismatch Use .formatGmt() for consistent timestamps.
Email limit exceeded Use Batch Apex for large sends.
Missing ORGANIZER field Required for Outlook compatibility.

5. Performance & Security Considerations

  • Governor Limits:
    • Max 5,000 emails/day in Salesforce.
    • Use Batch Apex for bulk sends.
  • Security:
    • Validate recipient emails to prevent spam.
    • Avoid exposing sensitive data in ICS files.

6. Testing & Compatibility Notes

  • ✅ Google Calendar (Web & Mobile): Works perfectly
  • ✅ Outlook (Desktop & Web): Works once METHOD:REQUEST and \r\n fixes applied
  • ✅ Apple Calendar: Supported via .ics standard
  • 📛 If the file won't open in Outlook: recheck UID, DTSTAMP, and Content-Type

7. Conclusion

Sending calendar invites from Salesforce via Apex is a powerful way to automate meeting scheduling. By generating ICS files and attaching them to emails, you ensure compatibility with major calendar providers.

📌 Bonus Tips

  • Support RSVPs with ATTENDEE and ORGANIZER fields
  • Add reminders with VALARM blocks
  • Attach these invites via Flows by wrapping the email method in an @InvocableMethod

📎 Related Resources

🚀 Ready to implement? Try the code above and customize it for your org!

📢 Found this helpful? Share your thoughts in the comments!

🔔 Subscribe for more Salesforce developer tutorials.

💬 Questions?

Still stuck or want to automate this further with Flow or Experience Cloud? Reach out or comment below — I’d be happy to help!

Post a Comment

0 Comments