0

I'm attempting send a Text email from Apex code, Email is sending without body.

I have created a new LWC button and Placed in custom Object Detailed page. On Clicking of the button this Apex method will be called and Send email to the User.( Email address are stored in Same Custom Object).

I'm successfully receiving the email, subject is coming across as I expect, but the body has some dynamic value.(Now the body coming as plain text)

public static void sendEnrollmentForm(Id EnrollmentId){

    //Get Email Address
    Enrollment__c Enrollment = [select  Id, Family_Email__c from Enrollment__c WHERE Id=:EnrollmentId]; 

    // get an email template
    EmailTemplate tpl = (EmailTemplate)[select Id, Subject, Body FROM EmailTemplate 
                                        WHERE Name = 'Enroll Email' limit 1];

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {Enrollment.Family_Email__c};


    mail.setTemplateId(tpl.Id);
    mail.setToAddresses(toAddresses);
    mail.setReplyTo('support@safarikid.com');
    mail.setSenderDisplayName('Safari Kid');
    mail.setSubject(tpl.Subject);
    mail.setPlainTextBody(tpl.Body);
    mail.setBccSender(false);
    mail.setSaveAsActivity(false);
    mail.setUseSignature(false);

    //send the email
    List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    // we can then check for success
    if (results[0].success) {
        System.debug('The email was sent successfully.');
    } else {
        System.debug('The email failed to send:  ' +  results[0].errors[0].message);
    }
}
1
  • First you didnt query body field from EmailTemplate object. Second you are not setting setHtmlBody or setPlainTextBody in your code either.
    – Mahmood
    Mar 19 '20 at 10:49
0

First you didnt query body field from EmailTemplate object. Second you are not setting setHtmlBody or setPlainTextBody in your code either.

e.g.

Query

EmailTemplate tpl = (EmailTemplate)[SELECT Id, Subject, Body FROM EmailTemplate WHERE Name = 'Enroll Email' LIMIT 1];

Setting the body

mail.setPlainTextBody = 'This is test email message.'; Or

mail.setPlainTextBody = tpl.Body;

2
  • in the Email has some dynamic value, sending the hyperlink with record Id of the object. But now it's coming raw value. Mar 19 '20 at 11:15
  • Use setHtmlBody property.
    – Mahmood
    Mar 19 '20 at 11:47

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.