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
EPSWDEVEPSWDEV 

Sending email from apex class using template.

Hi I'd appreciate it if anybody can shed any light on this problem.  I am trying to send a email from a Apex class using a template. See code below.

 

 

APEX CLASS--------------------- global someapexclass { someCustomObject cust = [Select name,attr1, attr2 from someCustomObject] for(User usr : [Select u.Id, u.email, u.name From User u where u.profile.Name = 'System Administrator']){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTargetObjectId(usr.Id); EmailTemplate et = [SELECT id from emailtemplate where name='MyEmailTemp']; mail.setTemplateId(et.Id); mail.setSaveAsActivity(false); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } EMAIL TEMPLATE--------------------------- Dear {!usr.name} This is a test email. . Thanks.

 

 The problem is the email is sent where the {!usr.name} not substitued at runtime hence the email just says 'Dear' instead of 'Dear <the user name>'

My question is Can I reference cust and usr (variables in the apex class) in a email template  ? is this even possible ? if so what am i doing wrong. If not - then is my only alternative to set the email body at runtime inthe class and not use the template.

 

thanks

 

werewolfwerewolf

That merge field looks funny.  It seems to be trying to refer to the Apex variable instead of just the object.

 

Try a more normal merge field like {!Receiving_User.Name}.

EPSWDEVEPSWDEV

I have tried both {!User.Name} and  {!usr.Name} with out luck, user being variable used in the script. Note

that I am trying to use the User objects fetched from the query.

 

Am what I doing fundamentally wrong... or is this the correct way to use template and that there may be something else wrong ?

 

Thanks

 

werewolfwerewolf
Well note that in my example I used Receiving_User.  I'm not sure there's a merge field for just "User," because you have to distinguish between the sending user and the receiving user.  Try Receiving_User.
wesnoltewesnolte
Insert some System.debug message to make sure your values are correct.
Chris987654321Chris987654321
I read something in my Apex book (from my Dev 501 Class) that said you cannot use templates to email Users. Maybe that's the problem?
Rasmus MenckeRasmus Mencke
You can use the $User merge fields, it gives you the merge fields for the logged in user.
tonantetonante

Here is one way to do it: You must get the email tample by using a SOQL query on the email Templat eobject and then use the Messaging class to send it like this segment  which is based on portal user info:

  if(SendEmail)
        {
            List<EmailTemplate> AvailableTemplates = [Select e.TimesUsed, e.TemplateType, e.TemplateStyle, 
                e.SystemModstamp, e.Subject, e.OwnerId, e.NamespacePrefix, e.Name, e.Markup,  
                e.LastUsedDate, e.LastModifiedDate, e.LastModifiedById, 
                e.IsActive, e.Id, e.HtmlValue, e.FolderId, e.Encoding, e.DeveloperName, e.Description, 
                e.CreatedDate, e.CreatedById, e.BrandTemplateId, e.Body, e.ApiVersion From EmailTemplate e
                Where DeveloperName = 'Customer_Portal_New_User_Login_Information'];
            
            if(AvailableTemplates.size() > 0)
            {
                String EmailFirstName = null;
                
                if(new_portal_user.FirstName != null) { 
                    EmailFirstName = new_portal_user.FirstName; }
                else {
                    EmailFirstName = 'Mr. or Ms.'; }
                
                String siteURL = 'some.secure.force.com';
                if(Userinfo.getOrganizationId() == '00DQ000000XXXX') { siteURL = 'some.sites.cs3.force.com'; }
                
                EmailTemplate CurrentTemplate = AvailableTemplates[0];
                
                String LoginURL = 'https://'+SiteURL+'/reg_auto_login'
                    + '?un=' + EncodingUtil.urlEncode(new_portal_user.Username, 'UTF-8')
                    + '&pw=' + Password;
                
                // begin to define email object
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
                mail.setToAddresses(new String[] {new_portal_user.Email});
                mail.setReplyTo('customerservice@awana.org');
                mail.setBccAddresses(new String[] {'portal@awana.org'});
                mail.setSenderDisplayName(CurrentTemplate.Name);
                mail.setSubject(CurrentTemplate.Subject);
                    
                mail.setPlainTextBody(
                    'Hi ' + EmailFirstName + ' ' + new_portal_user.LastName + ', \n\n' +
                    'Thank you for registering for ' + CurrentTemplate.Name + 
                    '. Please use your e-mail address and the temporary password, listed below, to login. \n\n' +
                    'User Name: ' + new_portal_user.Username + ' \n' + 
                    '(Temporary or Set) Password: ' + Password + ' \n' +
                    'Login Link: ' + LoginURL + ' \n\n' +
                    CurrentTemplate.Body
                );
                
                // send email
                Messaging.SendEmailResult[] emailresult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                system.debug(emailresult);
            }
        }