[SalesForce] How to send an email from Apex with a template based on an Event record

I have been trying to figure out how to send an email from Apex for a template that needs an Event object to work.

In my example below, I want to have a visualforce template that will work off of an Event record. It will have a custom controller for a component within the Visualforce Email Template which will need the Event.Id in order to query the Event and a list of child objects from another object.

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { 'test@test.com' });
email.setTargetObjectId(myContact.Id);
email.setTemplateId(mytemplate.Id);

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

Questions

  • I can specify the template id as I have above, but I am not sure how to pass (if it is at all possible) the event id so that it can be used in the template.
  • I am also not sure how to specify in the Visualforce Email template that this is an Event driven template.
  • In addition, as there are no page parameters for the component controller to pick up the event id from, where does it get the id from?

Thank you

Best Answer

First of all, you are looking for the setWhatId method.

As for your question about type, there is a relatedToType attribute for that in your opening messaging:emailTemplate tag (documentation).

<messaging:emailTemplate recipientType="Contact" relatedToType="Event">

The Event Id comes from setWhatId as mentioned above.