Showing posts with label Email Alert. Show all posts
Showing posts with label Email Alert. Show all posts

Thursday, 26 May 2022

Setting up merge fields and sending emails using email template on the custom object through apex


SCENARIO

While working on one of the requirements for a Service sector project for a client based out of Atlanta, GA, there was a requirement to send an email using an email template where the related entity type was the custom object.

CHALLENGE

In SingleEmailMessage, if we set template-id (using setTemplateId), then target object id is required. setTargetObjectId() can accept contact, lead, user or person account id only. We cannot pass the custom object id in the parameter of setTargetObjectId() - reference link. Also, the custom object is not having any relationship to any of these standard objects.

APPROACH

With a little magical Apex hand-waving, we can indeed send emails using custom email templates.

The key thing we used here is Salesforce doesn't send an email immediately when the sendEmail() method is executed, instead, Salesforce waits for the very end of the transaction. If we roll back the transaction, Salesforce doesn't send the email at all.

Below is the text value of the email template having some merge fields that we want to populate automatically,

Hi {{{Sourcing__c.Full_Name__c}}},

Good afternoon, I hope you are having a great day, and that this email finds you well. 

I just wanted to reach out to follow up with you about your application for one of
our Entry-Level IT Career Opportunities. We are very interested in speaking with you.

Our initial phone call takes less than 10 minutes. You can reach me on my direct line,
{{{Sender.Phone}}} If for some reason I do not answer please leave a voice mail
and reply to this email. 

Regards,
{{{Sender.Signature}}}

Below is a code we used for sending emails,

public class SendEmailSourcing{
    
    public void sendEmailMessage(){
	// Fetching email template
        EmailTemplate emailTemplate = [SELECT Id, DeveloperName, Subject, HtmlValue, Body
                                       FROM EmailTemplate WHERE Name = '1st Call - Email' LIMIT 1];
									   
	// Picking a dummy contact where email is not null
        Contact con = [SELECT Id, Email FROM Contact WHERE email <> NULL LIMIT 1];    
        
        List<Messaging.SingleEmailmessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        List<Messaging.SingleEmailmessage> emailMessagesToSend = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailmessage email = new Messaging.SingleEmailmessage();  
        
	// For every sourcing record, creating email message and adding it to the list of email messages
        for (Sourcing__c sourcing :  sourcingList) {                
		email = new Messaging.SingleEmailmessage();
		email.setTemplateId(emailTemplate.Id);
		email.setTargetObjectId(con.Id);
		email.setWhatId(sourcing.Id);
		email.setToAddresses(new List<String>{sourcing.Email__c});
		email.setTreatTargetObjectAsRecipient(false);
		email.setUseSignature(false);
		emailMessages.add(email);
	}       
        
	// Setting save point to rollback the transaction after sending email message
        Savepoint sp = Database.setSavepoint();
        Messaging.sendEmail(emailMessages);
        Database.rollback(sp);
        
	// Copying content of the each email message that we just sent using sendEmail() and rolled back
	// and sending these new messages
        for (Messaging.SingleEmailMessage singleEmail : emailMessages) {
		email = new Messaging.SingleEmailMessage();
		email.setToAddresses(singleEmail.getToAddresses());
		email.setPlainTextBody(singleEmail.getPlainTextBody());
		email.setHTMLBody(singleEmail.getHTMLBody());
		email.setSubject(singleEmail.getSubject());
		email.setWhatId(singleEmail.getWhatId());
		email.setUseSignature(false);
		email.setSaveAsActivity(true);
		emailMessagesToSend.add(email);
        }
		
        Messaging.sendEmail(emailMessagesToSend);  
    }
	
}

In the above code, first, we created email message for each sourcing record and added it to the list of email messages. Then trying to send email messages in a transaction that can be rolled back.

After rolling back the transaction, we are iterating through all the emails we just sent and are copying the content of those emails into another list of emails.

That newly created list is then used to send the emails.

CONCLUSION

Using Apex effectively and rolling back the transaction, we are able to set merge fields and send email messages using email templates where a related entity type is a custom object.

If you have any questions you can reach out our Salesforce Consulting team here.

Thursday, 22 April 2021

Introduction to Workflow Rule in Salesforce

INTRODUCTION

The workflow rule in Salesforce is one kind of process automation that basically contains the business logic that automates certain actions based on particular criteria.

What are the benefits of using Workflow Rules?

In a workflow rule, you get one set of criteria with multiple conditions and then a list of actions to run once the criteria is met. Being able to ‘chain’ multiple sets of criteria provides for if-then-else logic to easily build complex business processes. With traditional workflow rules, you would need several different rules to catch the different scenarios in your requirements. This can make complex business processes difficult to maintain.

There are endless ways you can use workflows, but of course, it is easier to illustrate what is a workflow in Salesforce with some examples. Mentioning the specific things that can be performed, you may automate the following 4 workflow actions in Salesforce:
  • creating tasks
  • Updating fields
  • Sending email alerts
  • Sending outbound messages

How to create workflow rules?
  • From Setup, enter the workflow rules in the Quick Find box, then select Workflow Rules.
  • Click New Rule.
  • Choose the object to which you want this workflow rule to apply.
  • Click Next.
  • Give the rule a name and description.
  • Set the evaluation criteria.(As per your requirement)
    • Created – Evaluate the rule criteria each time a record is created. If the rule criteria is met, run the rule. Ignore all updates to existing records.
    • Created, and every time it’s edited –Evaluate the rule criteria each time a record is created or updated. If the rule criteria is met, run the rule.
    • Created, and any time it’s edited to subsequently meet criteria - (Default) Evaluate the rule criteria each time a record is created or updated.


  • Enter your rule criteria.
  • Click Save & Next.

What are the Workflow Actions?

Email Alert: Email alerts are emails generated by an automated process and sent to designated recipients. These actions consist of the standard text and list of recipients for an email.

Field Update: A common use case of workflow rules is the function to overwrite field values with new data. This is, perhaps, the most frequently used action but please note that it won’t work in the cross-object case.

Outbound Message: An outbound message sends information to a designated endpoint, like an external service. You configure outbound messages from Setup. Provide the external endpoint and create a listener for the messages using the SOAP API. You can associate outbound messages with workflow rules, approval processes, or entitlement processes.

Task Creation: Task actions determine the details of an assignment given to a specified user by an automated process. You can associate task actions with workflow rules, approval processes, or entitlement processes.

How to Add Time-Dependent Action in Workflow Rule?
  • Open a workflow rule.
  • In the Time-Dependent Workflow Actions section, click Add Time Trigger.
  • Specify the number of days or hours before or after a date that’s relevant to the record, such as the date the record was created. Refer below image for better understanding.


  • Save your time trigger.
  • In the section for the time trigger you created, click Add Workflow Action.
  • Select one of the options to create an action or select an existing one.
  • Click Done.
If the workflow rule is still active and valid when this time occurs, the time trigger fires the workflow action.

Limitations of Workflow Rules:
  • You can’t add a time trigger if:
    • The evaluation criteria are set to evaluate the rule when a record is: Created, and any time it’s edited to subsequently, meet criteria.
    • The rule is activated.
    • The rule is deactivated but has pending actions in the workflow queue.
  • Please refer to the link for limitations.

SUMMARY

As illustrated, Salesforce Workflow is a much better and more efficient tool that let Salesforce admin creates business solutions with no code and with few clicks. So, we can easily perform some actions like email send, field update, etc.
        
    If you have any questions you can reach out to our Salesforce Consulting team here.