1

I am using an email service and apex class to handle inbound emails and attach them to an associated custom object record. The same Apex class is also sending an email to the user in the "Assigned to" field in the custom object. This is also working. the problem is the templates merge fields are not populating when the email is sent.

Below is the code I am using

// Add the email plain text into the local variable       
    Task task = new Task(
       WhatId = request.Id,
       Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',           
       Type = 'Email',
       Subject = subject,
       ActivityDate = System.today(),
       RecordTypeId = '01250000000HkEw');
    insert task;

    //Find the template
    EmailTemplate theTemplate = [select id, name from EmailTemplate where DeveloperName = 'New_Email_Reply'];
    //Create a new email right after the task
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    //Add email To addresses to list
    List<String> toAddresses = new List<String>();
    toAddresses.add(email.fromAddress);
    //Set the list of to addresses
    mail.setToAddresses(toAddresses);
    //Set the template id
    mail.setTemplateId(theTemplate.id);
    //The Id of the user
    mail.setTargetObjectId(request.Assigned_To__c);
    //Set the id of the request
    //mail.setWhatId(request.Id);
    //If you need the email also saved as an activity, otherwise set to false
    mail.setSaveAsActivity(false); 

I know the Mail.setWhatId is commented out. I was getting an error saying cannot use WhatId. It works when the line is commented out.

Any help appreciated.

1
  • post a snippet of the email template with a merge field that is not showing -- (note, just a snippet, we don't need the whole email. Is email template text? html? or VF?
    – cropredy
    Commented Mar 6, 2015 at 22:14

1 Answer 1

1

I recreated the email template as a visualforce template and this accepted the WhatId.

Thanks for your help

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .