function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
justinhowell82justinhowell82 

send massemail from apex using visualforce template + apex component with atribute

Currently, we have a VF page that contains a VF component that has an attribute passed into it that is a Sales Order ID.  The components controller then gathers all required data for that Sales Order and that page is rendered and emailed on a manual button click from Sales Order details page.  Trying to automate this process, I wrote a schedualable class that will grab all the Sales Orders that meet criteria to send this email and process them in batches, no problem there.  The problem I am having is when trying to send the email.  I would like to to be able to track these activities as well as send each email to multiple contacts so it seems as if I will need to use the MassEmailMessageClass.  I have a visualforce email template  with a component like this:

<messaging:emailTemplate subject="Smartnet Welcome Letter" recipientType="Contact" relatedToType="Sales_Order__c">
<messaging:plainTextEmailBody >
    <c:SOMessage SOID="{!relatedTO.id}"></SOMessage>
</messaging:plainTextEmailBody>
</messaging:emailTemplate>

What I don't understand is in my scheduled class to send these emails I loop over all the Sales Orders and build a collection of messages to be sent.  I grab and set the template ID (setTemplateId) and the list of contact ids (setTargetObjectIds) but how will the Sales Order ID get passed into the template to be used by the component?  I though I would use the setWhatId but it appears that for mass emails this has to be of type Contract, Case, Opportunity, or Product.  My other though was to use an html body instead of a template but when using the massemail class you have to use setTemplateID, setHTMLBody is not allowed.  Is there a way to use the massemail class for this instance?  Or do I need to use the single email with setTargetId, if so how can i cc or send to others as well?

Thanks,
Justin

ShashankShashank (Salesforce Developers) 
Currently, Visualforce templates cannot be used for mass email: https://success.salesforce.com/ideaview?id=08730000000BrDOAA0

You can try sending a single email to multiple addresses by setting the "setToAddresses" string list explicitly with all the email addresses. Sample: http://www.sfdc99.com/2014/03/01/sending-emails-using-apex/