Search code examples
salesforceapex-codesoql

Salesforce.com : getting SOQL statement to return a string to be used in an email template?


I have made an Apex Scheduler Class for Birthdays. The class works and successfully sends an email to our director when a birthday is 2 days away.

However, the email template that is sent when there is a birthday two days away needs to contain the contact's first, last name and birthdate. (The email template looks like this: This is a scheduler-generated email to notify you that the birthday of First Name: {!Contact.FirstName} , Last Name: {!Contact.LastName} is on {!Contact.Next_Birthday__c}.

In my scheduler, I use a SOQl statement to query the database for the contact's id and first name.

After I call the query, how do I convert the information I just queried to a string/method to be used in the email template?

My guess is return the results of the query as a string? Any Advice is appreciated!

Here is my code:

global class BirthdayName implements Schedulable
{
    global void execute (SchedulableContext ctx) 
    { 
        sendBirthdayEmail(); 
    }

    public void sendBirthdayEmail()
    {
        for(Contact con : [SELECT Contact.name, Id FROM Contact WHERE Next_Birthday__c = : system.Today().addDays(2)])
        {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
            mail.setTemplateId('00XJ0000000M31w'); 
            mail.setTargetObjectId('005J0000000JWYx'); 
            mail.setSaveAsActivity(false);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); 
        }
    }
}

Solution

  • The Quick Answer

    Mail objects have two IDs that you can set, the first is the target object as you've done, and the second is the 'what' object, which is the object the email refers to.

    Therefore, all you need here is the line below and you should be set.

    mail.setWhatId(con.Id);
    

    Some More Notes

    Using hard coded IDs as you've done here is considered bad practice, primarily because IDs are not likely to be the same in production org as they are in a sandbox or other org. You should grab the email template itself via it's API/Developer name:

    EmailTemplate template = [Select id, Body from EmailTemplate
                              where DeveloperName = 'BirthdayReminder'];
    

    And also grab the Director's ID via name, or email address:

    User theDirector = [select Id from User where Email = '[email protected]'];
    

    Then just use the IDs as you were before:

    mail.setTemplateId(template.Id); 
    mail.setTargetObjectId(theDirector.Id); 
    

    Obviously I'm not checking for errors here which is something you may want to add, and you should be wary with regards to email sending limits, but given this scenario they're not somethign you're likely to hit unless you're dealing with a seriously large company!