0

I've created a Visualforce email template and I'm trying to send it. It needs a recipient and a related to field, but there's no selector for the related-to field:

enter image description here

Because I can't select a related-to field, I get that error at the top. How can I work around this?

EDIT

I've included the relatedTo field in the template, too:

enter image description here

4
  • 1
    relatedTo should be the Task's whatId
    – cropredy
    Commented May 9, 2016 at 23:59
  • Oh, really? How do I set that, then? Also, you're helping me out a lot this week.
    – t56k
    Commented May 10, 2016 at 0:00
  • can you add debug logs and see where the list of rows is empty? Commented May 10, 2016 at 3:07
  • The "Sending an Email" action above doesn't log anything even on the finest settings.
    – t56k
    Commented May 10, 2016 at 3:22

2 Answers 2

1

While creating the visualforce email template, you need to choose the RelatedToType and RecipientType too.

enter image description here

1
  • Yeah, that's done. See updated question.
    – t56k
    Commented May 10, 2016 at 2:59
0

So even with custom Apex methods it doesn't work. I get this error:

SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available with saveAsActivity for sending emails to Leads.: [whatId, 00Q17000008LRcA]

Which after researching leads me to this:

Don't use setWhatId in this case. You cannot specify a WhatId with a Lead WhoId. Why? Because it's a limitation of the platform.

Fucking useless. Nevertheless, I found my solution:

Class:

public void send(Lead lead, String senderName, String replyTo) {
    EmailTemplate emailTemplate       = [SELECT Id, Name FROM EmailTemplate WHERE Name = 'VF template'];
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses              = new String[] { lead.Email };

    mail.setToAddresses(toAddresses);
    mail.setSenderDisplayName(senderName);
    mail.setReplyTo(replyTo);
    mail.setTargetObjectId(lead.Id);
    // mail.setWhatId(lead.Id);
    mail.setTemplateId(emailTemplate.Id);

    Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    inspectResults(results);
}

Controller:

public PageReference sendEmail() {
    SendClass email = new SendClass();
    email.send(lead, senderName, replyTo);
    PageReference redirectPage = new PageReference('/' + lead.Id);
    return redirectPage;
}

Page:

<div class="content">
    <apex:form >
        Sender name: <apex:inputText value="{!senderName}" id="senderName" /><br />
        Reply-to address: <apex:inputText value="{!replyTo}" id="replyTo" /><br /><br />
        <apex:commandButton value="Send" action="{!sendEmail}"/>
    </apex:form>
</div>

You can just use params like I did with senderName to get other information through.

You must log in to answer this question.

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