The following post explains how to send a complex, stylized table formatted email with data records from your Salesforce system.  For this, we will be using Visualforce Email Template, Visualforce Component with an apex custom controller.

The visualforce component will be placed in the email template; the custom controller will pull the required data from Salesforce using SOQL query and displays it in the Email Template.

First create the email template (of type Visualforce) by clicking New Template in Communication Templates in Salesforce


Here’s the email template (of type Visualforce).  Observe that the email body contains the VF component  along with the text content.

Note: We are passing the accountId from the email template to the visualforce component as an attribute.  This accountId will be used in querying the related Opportunity records to display in the email.

Here’s the code for the VF component.  The component has to display Opportunities and another repeat to show the related Matches as well for each Opportunity.  (Match is an object that is a related list to opportunities).  Of course, you can add all the kind of styling you want in the component as it is pure html data table.

And finally here is the apex class where we query the Opportunity and related matches (in confirmed status)

Here’s the complete github code.

You might also be interested in reading building dynamic Search functionality in Visualforce page with pagination.