+ Start a Discussion
vikram fartyalvikram fartyal 

how to send email using visualforce template using User Id as setTargetId?

Hi,

I have been trying to send an email by using visual force template, but not got success. I created a component and used it in my VF Template, but when i use it in apex class and try to send email either it gives the error or send mail with no data.

My Controller Class Code:
private void sendEmailNotifications(Map<Id, Store__c> mapRf, EmailTemplate emailTemp) {    	
    	List<Messaging.SingleEmailMessage> mailsToSend = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            
    	for(Id rfId : mapRf.keySet()){
        	Store__c r = mapRf.get(rfId);
        	
        	// fetch list of the uses to whom mails gonna sent
        	List<Id> uIds = new List<Id>();
        	if(mapGrpEmail.containsKey(mapGrpNameRfId.get(rfId))){
        		for(User u : mapGrpEmail.get(mapGrpNameRfId.get(rfId))){
                	uIds.add(u.Id);
                }
        	}
           
            email.setTargetObjectId('005w0000003dyDo');
            String[] toAddresses = new String[] {'abc@xyz.com'}; 
            email.setToAddresses(toAddresses); 
            //email.setWhatId(rfId) ;
			email.setSaveAsActivity(false);
			email.setTemplateId(emailTemp.Id)			
			mailsToSend.add(email);
        }

i am setting userId in setTargetId() method, so if i set Store__c.Id in setWhatId() method it gives me following error:

System.EmailException: SendEmail failed. First exception on row 1; first error: INVALID_FIELD_WHEN_USING_TEMPLATE, When a template is specified the plain text body, html body, subject and charset may not be specified : []

And if i don't set WhatId how i gonna get merged fields to be populated in my template, which is quite annoying. I read somewhere that WhatId supports only When a ContactId is set into setTargetId() but i simply need to UserId.

Here is my template:
 
<messaging:emailTemplate subject="Store - Created" recipientType="User" relatedToType="Store__c">
    <messaging:htmlEmailBody >
        <c:RedFlagComponent rfId="{!relatedTo.Id}" flag="true" /><br/><br/>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>
Here is Componenet:
 
<apex:component controller="RedFlagComponentController" access="global">
    <apex:attribute name="sId" type="Id" description="Id of the store" assignTo="{!storeId}"/>{!isNew}
    
    	<table>
    	<apex:repeat value="{!lstRfs}" var="r">
	    	<apex:outputText rendered="{!isNew}" value="A red flag notification has been raised in {!r.Store__r.Name}, {!r.Address_Concatenated__c }/{!r.External_Reference__c} on {0,date,dd/MM/yyyy}." >
	    		<apex:param value="{!TODAY()}" />
	        </apex:outputText>
	      
	        <br/>
	        <hr/>
		        <tr>
		            <td>Priority: {!r.Priority__c}</td>              
		        </tr>		        
		        <tr>
		            <td>Link to the latest visit: <a href="{!orgUrl}{!r.Photo_Attachments__r[0].Visit__c}" target="_blank">{!r.Photo_Attachments__r[0].Visit__c}</a></td>              
		        </tr>
		        <tr>
		            <td>Link to red flag photos: 
		            	<apex:outputPanel >
		            	<apex:repeat value="{!r.Photo_Attachments__r}" var="p">
		            		<a href="{!orgUrl}{!p.Id}" target="_blank">{!p.Name}</a><br/>
		            	</apex:repeat>
		            	</apex:outputPanel>
		            </td>              
		        </tr>
        </apex:repeat>        
    </table>
    <hr/>
</apex:component>

Any help would be appreciated. Thanks in advance.


Vikram
lifewithryanlifewithryan
I think the problem may be that you are specifying a templateId in the apex controller, but you are also specifying an htmlEmailBody on the visualforce page.
<messaging:htmlEmailBody >
        <c:RedFlagComponent rfId="{!relatedTo.Id}" flag="true" /><br/><br/>
    </messaging:htmlEmailBody>
I could definitely be wrong though as I've not tried to use a visualforce template AND an email template from the point & click interface at the same time. But in reading the message and seeing the code, that's what I am seeing. If you specify a templateId in the apex, it wants to use the body from that template and won't allow specify a plain text or email body.