I need to pass a list of records into the email body in apex code. I am looking for the code sample or an Idea to start doing this. so far i am doing this.

Java script button on detail page. onclick calls a webservice method in a Apex class and sends an email with the list of records. All this code is part of my POC.

Button Code:


var retStr; 
var accId = "{!Account.Id}"; 
alert('**** Acc Id'+accId) 
retStr = sforce.apex.execute("MyWebServiceTest","makeContact",{accId:accId}); 

alert('The method returned: ' + retStr); 

document.location = '/{!Account.Id}';

Class Code:

global class MyWebServiceTest{
    webService static Id makeContact(Id accId) {
        List<Contact> cntList=new List<Contact>();
        cntList = [Select Id, Name from Contact where AccountId=:accId];
        string template ='<html><head><style> body {font-family:verdana; font-size:13px;}</style></head><body>';

        template += // Here I am expecting to add the cntList records to the template;
        Messaging.Email[] emailList = new Messaging.Email[0];
        for (id userId : userIds) {
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();


    if (!emailList.isEmpty())
        Messaging.sendEmail(emailList, false);
  • Tables are constructed of a <table>, <tr> for every row, a <td> </td>for every cell, a </tr> at the end of each row of cells, and a closing </table> tag. Its a matter of you working out what you want yours to look like isn't it?
    – crmprogdev
    May 28, 2015 at 18:49

1 Answer 1


I had the same problem before and came up with a solution. Basically, you can append the table to your setHtmlBody text value by passing in a list of records (be sure to change to appropriate sObjectType).

public static string getTableEmailBody(List<Lead> myList){

    String htmlBody = '';

    //open table..
    htmlBody = '<table border="1" style="border-collapse: collapse"><caption>Request Summary Data</caption><tr><th>Name</th><th>Phone</th></tr>';

    //iterate over list and output columns/data into table rows...
    for(Lead l : myList){

        String myName = l.Name; if(l.Name == null){myName = '[Not Provided]';}
        String myPhone = l.Phone; if(l.Phone == null){myPhone = '[Not Provided]';}

        htmlBody += '<tr><td>' + myName + '</td><td>' + myPhone + '</td></tr>';


    //close table...
    htmlBody += '</table>';

    system.debug('Email Body: ' + htmlBody);   

    return htmlBody;


//see output from above method...
List<Lead> myList = [select Name, phone from Lead where name != null LIMIT 15];


You can run this in the execute anonymous window to see sample output.

  • awesome! i'm sure there's a much mor efficient solution, but I feel this just gets it done
    – James
    May 28, 2015 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.