-1

Is it possible to create a button (or something equivalent) to generate and send an email from the Opportunity tab? I am really new in Salesforce and struggle with the basics.

I have created an customer Opportunity tab enter image description here

And an email template enter image description here

Ideally, there should be a button (or anything else) which generates an email using the template and send it.

With my thanks for your help.

2 Answers 2

0

In order to achieve that you can have two options:

  1. Flow:
  • Create a Flow which will send email using Opportunity fields.
  • Also create new Action button on Opportunity object with Action type as your flow and add the action button to your Opportunity layout page as 'Mobile & Lightning action'
  1. Using LWC:
  • You can create a LWC component and place it on your opportnity page. Call an apex through your component where you will send email

I would suggest you to try this with Flow, to avoid writing code.

Also please note that, no one is going to write all code for you here from scratch. To get answers you will have to show your efforts/trials here so that one would help with your code or process.

Good Luck! And Happy Learning.. :)

0

Let's attempt to approach this systematically, one step at a time.

Step 1: Create an Apex controller for email transmission.
For the sake of simplicity, we'll focus on sending emails to the primary contact associated with an opportunity.

public class EmailController {
    @AuraEnabled
    public static void sendEmail(String opportunityId, String templateName) {
        Opportunity opportunityRecord = [
                SELECT (
                        SELECT ContactId, Contact.Email
                        FROM OpportunityContactRoles
                        WHERE IsPrimary = TRUE
                )
                FROM Opportunity
                WHERE Id = :opportunityId
        ];
        if (!opportunityRecord.OpportunityContactRoles.isEmpty()) {
            OpportunityContactRole primaryContact = opportunityRecord.OpportunityContactRoles[0];
            EmailTemplate template = [SELECT Id FROM EmailTemplate WHERE Name = :templateName];

            List<String> toAddresses = new List<String>{ primaryContact.Contact.Email };
            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setTemplateId(template.Id);
            email.setTargetObjectId(primaryContact.ContactId);
            email.setWhatId(opportunityId);
            email.setToAddresses(toAddresses);
            email.setSaveAsActivity(false);
            emails.add(email);

            Messaging.sendEmail(emails);
        } else {
            throw new AuraHandledException('No primary contact found');
        }
    }
}

The given code receives two parameters, opportunityId and templateName. It proceeds to fetch the Opportunity record along with its primary contact role. Next, it checks if the contact role is not empty; otherwise, an exception is thrown. Finally, an email message is prepared and sent to the primary contact using the specified template.

Step 2: Develop an LWC (Lightning Web Component) with the Action type, allowing placement on the Opportunity record page.

HTML (no refactoring needed as this is an Action):

<template>
</template>

JS

import {LightningElement, api} from 'lwc';
import {ShowToastEvent} from "lightning/platformShowToastEvent";
import sendEmail from '@salesforce/apex/EmailController.sendEmail';

const TOAST_TITLE = 'Send Email';

export default class SendEmailAction extends LightningElement {
  @api recordId;

  @api invoke() {
    sendEmail({
      opportunityId: this.recordId,
      templateName: 'TestEmailTemplate'
    })
    .then(() => {
      this.dispatchEvent(new ShowToastEvent({
        title: TOAST_TITLE,
        message: 'Email sent successfully',
        variant: 'success'
      }))
    })
    .catch(error => {
      this.dispatchEvent(new ShowToastEvent({
        title: TOAST_TITLE,
        message: error.body?.message || 'Unexpected error',
        variant: 'error'
      }))
    });
  }
}

Metadata

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiVersion>58.0</apiVersion>
  <description>Send Email Action</description>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__RecordAction</target>
  </targets>
  <targetConfigs>
    <targetConfig targets="lightning__RecordAction">
      <actionType>Action</actionType>
    </targetConfig>
  </targetConfigs>
  <masterLabel>Send Email Action</masterLabel>
</LightningComponentBundle>

In this step, we will utilize the Apex method created in Step 1 to send emails when our action is invoked. Additionally, we will handle exceptions and display them in a popup toast.

Step 3: Generate an action on the Opportunity object.

  • Click on the Setup Gear button in your organization.
  • Go to the Object Manager tab and locate Opportunity.
  • Select Buttons, Links, and Actions.
  • Click on the "New Action" button in the top right corner.
  • Configure as follows: New Action
  • Click Save button.

Step 4: Add your new Action button to the Opportunity Layout.

  • Go to the Object Manager tab and locate Opportunity.
  • Select Page Layouts
  • Select the desired layout.
  • Find you Action in "Mobile & Lightning Actions" section.
  • Perform a drag-and-drop operation to add this action to the layout.
  • Click Save button.

Step 5: Congratulations, everything is set up. Now you can navigate to the Opportunity record page and test the functionality of your new action button. Send Email Success Send Email Error

I hope this information proves helpful. Happy coding! :)

P.S If you have any questions, feel free to ask me in the comments section. I'll be glad to assist.

2
  • A Flow that uses an email action (with template) seems much simpler
    – cropredy
    Aug 9 at 4:21
  • Agreed, using a Flow with an email action and template can often simplify things. It's great for automating processes and maintaining consistent communication. Still, the choice depends on specific needs. Flows are user-friendly, while custom methods offer more control for dynamic content.
    – Ivan
    Aug 9 at 7:41

You must log in to answer this question.

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