Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

Sending emails using Apex

March 1, 2014

Preface: this post is part of the Advanced Apex Concepts series.

It’s surprisingly easy to send emails out using Apex!
Just don’t be tempted to become an email spammer, trust me, I used to work in that industry!

Here are a few things to keep in mind before sending emails with Apex:

  • There are limits to the number of emails you can send per day.
  • If you can create the email alert using workflows instead of code, always do it with workflows!
  • It’s sometimes helpful to send emails only when a field changes to a certain value.

Sending an email with Apex is easy because you always follow the same template:

// Send a business proposal to each new Contact
trigger Proposal on Contact (before insert) {
  // Step 0: Create a master list to hold the emails we'll send
  List<Messaging.SingleEmailMessage> mails = 
  new List<Messaging.SingleEmailMessage>();
  
  for (Contact myContact : Trigger.new) {
    if (myContact.Email != null && myContact.FirstName != null) {
      // Step 1: Create a new Email
      Messaging.SingleEmailMessage mail = 
      new Messaging.SingleEmailMessage();
    
      // Step 2: Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(myContact.Email);
mail.setToAddresses(sendTo);
// Step 3: Set who the email is sent from
mail.setReplyTo('sirdavid@bankofnigeria.com'); mail.setSenderDisplayName('Official Bank of Nigeria');
// (Optional) Set list of people who should be CC'ed List<String> ccTo = new List<String>(); ccTo.add('business@bankofnigeria.com');
mail.setCcAddresses(ccTo);
// Step 4. Set email contents - you can use variables!
mail.setSubject('URGENT BUSINESS PROPOSAL');
String body = 'Dear ' + myContact.FirstName + ', '; body += 'I confess this will come as a surprise to you.'; body += 'I am John Alliston CEO of the Bank of Nigeria.'; body += 'I write to request your cooperation in this '; body += 'urgent matter as I need a foreign partner '; body += 'in the assistance of transferring $47,110,000 '; body += 'to a US bank account. Please respond with '; body += 'your bank account # so I may deposit these funds.';
mail.setHtmlBody(body);
// Step 5. Add your email to the master list mails.add(mail); } } // Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
}

Don’t be intimidated by the lines of code, most of it is just fluff!

If you’re getting lost in any of the code, make sure to revisit the Core Apex Tools chapter to refresh!

Next post: Change your trigger on the fly using Custom Settings!

73 Comments
Anshul sahu
September 4, 2022 @ 12:07 pm

Hi,
send email through apex
your answer here
Please go through this link:

https://supportsalesforce.blogspot.com/2022/08/email-send-through-apex-class.html

let me know if this help you.

Happy to help You!

Thanks,
Anshul

Reply
PARAG BHOR
November 28, 2020 @ 9:18 am

Sorry in advanced if its a silly question.
How can we use .setReplyTo and setSenderDisplayName on Messaging.SingleEmailMessage object , as they are from email object.
This field is fine (setToAddresses) as it is from Messaging.SingleEmailMessage.
please clear my silly doubt.

Reply
Wendell B.
January 31, 2019 @ 9:00 am

I’ve created a button using Javascript to use the SingleEmailMessage and an email template and it works great! My question is, can the email be opened for editing and not just sent. I’ve found nothing on that so I presume not, but thought I’d ask.

Reply
    Anonymous
    November 28, 2020 @ 11:19 am

    Sorry wrong question , I got it . Just couldn’t find those fields at first in developer guide

    Reply
Santhish
March 24, 2018 @ 7:33 am

I have written adderror method in trigger. Whenever I am creating a record if criteria was not met, error is displaying in the top of the page.,due to that addError method in trigger. And at the same time I am getting apex exception email to my mail Id whenever this error happened. How to stop emails, i want to display the error on the page only, i don’t want to get email.

Please suggest me how we can stop this apex exception emails.

Reply
    Anonymous
    October 5, 2018 @ 11:58 pm

    Use try catch. In catch store the exception message into that varuble and display on vf page

    Reply
Sunny
March 22, 2018 @ 2:08 am

sunny.xie@edgewell.com

Reply
    David Liu
    March 22, 2018 @ 11:35 pm

    Hi Sunny!

    Reply
Nikhil Somvanshi
March 2, 2018 @ 11:00 am

This sure looks like a Spam Email :D

Good work anyways!

Reply
Prabhu
July 1, 2017 @ 5:32 am

David,

Sending email through apex worked fine, but trying to write a test class for it. But I Couldn’t make it.

Here is my test class and following error message getting during run test.

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Proposal_Email: execution of BeforeInsert

caused by: System.EmailException: SendEmail failed. First exception on row 3; first error: SINGLE_EMAIL_LIMIT_EXCEEDED, Email limit exceeded: []

Trigger.Proposal_Email: line 29, column 1: []

Test class:-

@IsTest
public class EmailMessage_Test {
public static testMethod void EmailMessage_Test() {

List totalcontacts = new List();
for (Integer i = 0; i < 200; i++) {

Contact newContact = new Contact();
newContact.FirstName = 'Hansika';
newContact.LastName = 'Motwani';
newContact.Email = 'prabhuselva.mech@gmail.com';
//insert newContact;
totalcontacts.add(newContact);

Messaging.singleEmailMessage newmail = new Messaging.singleEmailMessage();

List SendTo = new List();
SendTo.add(newContact.Email);
newmail.setToaddresses(SendTo);

newmail.setreplyTo(‘revprabu@gmail.com’);
newmail.setSenderDisplayName(‘Hansika’);

List CcTo = new List();
CcTo.add(‘revprabu@gmail.com’);
newmail.setCcaddresses(CcTo);

newmail.setSubject(‘Test class defined’);

String body = ‘Please execute ‘ + newContact.FirstName + newContact.LastName;
newmail.setHtmlbody(body);

}
insert totalcontacts;

List allmails = [SELECT Id, ToAddress FROM EmailMessage];

for (EmailMessage uniquemail : allmails) {
System.assertEquals(uniquemail.ToAddress, ‘prabhuselva.mech@gmail.com’);
}
}
}

Reply
Anonymous
August 10, 2016 @ 7:52 pm

I used the code in this post to send an email to contact.email when a Task is updated. The test run was successful and the code coverage is 100% . I am using one my email address but have still not received the email. How do I check if the email was sent?

Here is my test class

*******

@isTest (SeeAllData=true)
private class TestSendWinEmail
{
static testMethod void TestSendWinEmail ()
{
//Create some test data
//Owner -00540000003D4JK
//Case – 50029000004HKde
Task b = new Task (Subject =’Testing 123′,
Prefer_to_respond_via_Email__c = False,
OwnerId = ‘00540000003D4JK’,
WhatId=’50029000004HKde’
,WhoId=’00329000005ZiTB’
);

insert b;
Task b1=[select id, Subject from task where id=:b.id];
b1.Prefer_to_respond_via_Email__c = True;
update b1;

//Time to check that the Task was inserted
System.assertEquals(‘Testing 123’, b1.Subject);
}
}

*****
Here is the trigger….

trigger SendWinEmail on Task (after update) {
List mails =
new List();

for (Task t : Trigger.new) {
Contact myContact =[SELECT Id,Email,FirstName FROM Contact WHERE Id = :t.WhoId];

System.assertEquals(‘00329000005ZiTB’,myContact.Id);

Messaging.SingleEmailMessage mail =
new Messaging.SingleEmailMessage();

// Step 2: Set list of people who should get the email
List sendTo = new List();
sendTo.add(myContact.Email);

mail.setToAddresses(sendTo);

// Step 3: Set who the email is sent from
mail.setReplyTo(‘sirdavid@bankofnigeria.com’);
mail.setSenderDisplayName(‘Official Bank of Nigeria’);

// (Optional) Set list of people who should be CC’ed
List ccTo = new List();
ccTo.add(‘business@bankofnigeria.com’);
mail.setCcAddresses(ccTo);

// Step 4. Set email contents – you can use variables!
mail.setSubject(‘URGENT BUSINESS PROPOSAL’);
String body = ‘Dear ‘ + myContact.FirstName + ‘, ‘;
body += ‘I confess this will come as a surprise to you.’;
body += ‘I am John Alliston CEO of the Bank of Nigeria.’;
body += ‘your bank account # so I may deposit these funds.’;
mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);
}
Messaging.sendEmail(mails);
}

****

Thank you all for your help.

Reply
Saikiran
July 21, 2016 @ 11:34 pm

Parse Url in apex Class

for(Lead ld : leadlist){
String fullRecordURL = URL.getSalesforceBaseUrl().toExternalForm() + ‘/’ + ld.Id;
ldlist = ldlist + ”+ld.CreatedBy.Name+”+
‘‘+ld.Name+’‘+

Reply
Anonymous
May 1, 2016 @ 12:30 pm

How to send more than 10 emails using batch apex .Plz help.
global class Batch_to_SentEmailNotify implements Database.Batchable
{
global Database.QueryLocator start(Database.BatchableContext BC)
{

string s=’Blocked’;

String query = ‘Select Id,Resort_Master__r.Name,Executive_Name__r.Email__c,Name_of_the_Guest__c,Company_Name__c,Block_Release_Date__c,Check_In__c,Check_Out__c,Total_Number_of_Rooms_Booked__c,Booking_Status__c,Source__c,Market_Segment__c,Executive_Name__r.Name FROM Non_Member_Booking_Request__c where Booking_Status__c=: s AND Email_Sent_Test__c != TRUE’;
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List scope)
{
ListlstNMBReq = new list();
for(Non_Member_Booking_Request__c c : scope)
{
system.debug(‘++++++++++++++system.today+2 ++++++++++++++’+system.today()+2);
string email = c.Executive_Name__r.Email__c;
if(email !=null &&(system.today()+2 == c.Check_In__c))
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
mail.setToAddresses(new String[] { email});
mail.setSubject(‘Block Alert ‘);
mail.setReplyTo(‘harishk968@gmail.com’);
mail.setCcAddresses(new String[] { ‘harishk968@gmail.com’ });
mail.setHtmlBody(‘Dear ‘+c.Executive_Name__r.Name+ ‘,’+’Your current tentative blocks are as under with the respective block release dates.’+’ Name of Resort First Name Company /Travel Agent Block Release Date Check In Check Out Rooms Booking Status Source Market Segment Executive Name ‘ +”+”+ c.Resort_Master__r.Name +”+”+ c.Name_of_the_Guest__c +”+”+ c.Company_Name__c +”+”+ c.Block_Release_Date__c+”+”+ c.Check_In__c +”+”+ c.Check_Out__c +”+”+ c.Total_Number_of_Rooms_Booked__c +”+”+ c.Booking_Status__c+”+”+ c.Source__c +”+”+ c.Market_Segment__c +”+”+ c.Executive_Name__r.Name+”+’ ‘+’Please let us know of the payment and contract details in order to regularize & confirm the same on the system. In the event of the same not being regularized, the block will be automatically released from the system and further rooms will be subject to availability.’+’Thank You. ‘+’Regards’+’SanjeeviKumar G’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
system.debug(‘@@@@@@@@@@@@@@@mail@@@@@@@@@@@@@@@’+mail);
c.Email_Sent_Test__c = TRUE;
lstNMBReq.add(c);
}

if(lstNMBReq.size() > 0){

update lstNMBReq;
}
}
}
global void finish(Database.BatchableContext BC)
{
}
}

Reply
    Nilesh Patil
    September 22, 2021 @ 12:14 pm

    Plz can u improving your class for bulk mail sending

    Reply
Praveen
April 5, 2016 @ 5:00 am

David,
Nice post.
Can you provide test class for sendemail

Reply
Anonymous
February 11, 2016 @ 7:32 am

This should be re-factored. It’s just messy and not scalable to do this directly in a trigger.

Reply
    David Liu
    February 11, 2016 @ 7:34 pm

    Thanks for the comment! How would you refactor it?

    Reply
Kate
September 15, 2015 @ 1:20 am

Hi.I want to write a batch class code for updating a field if it has same value for more than 50 days.Please help.

Reply
mintu
August 14, 2015 @ 3:53 am

Hi
I am getting error like System.NoAccessException: The organization is not permitted to send email
how can i resolve this issue.

Reply
    David Liu
    August 17, 2015 @ 10:39 am

    You probably have to change your org’s settings somewhere, Google it =)

    Reply
Bob Poliquin
July 31, 2015 @ 11:47 am

I tried to convert the above code to send email email to a specific email address if the subject was troubleshooting, but nothing happens when i create the task. Can anyone help? The code is below. i have changed the email content yet until i get this to work.

trigger Trigger_SendPartsTechEmail on Task (before insert) {

// Step 0: Create a master list to hold the emails we’ll send
List mails =
new List();

for (Task tsk : Trigger.new) {

if (tsk.Subject==’Troubleshooting’ && tsk.CreatedBy.Username == ‘bpoliquin@cybexintl.com.cybextest’) {
// Step 1: Create a new Email
Messaging.SingleEmailMessage mail =
new Messaging.SingleEmailMessage();

// Step 2: Set list of people who should get the email
List sendTo = new List();
sendTo.add(‘bpoliquin@cybexintl.com’);
mail.setToAddresses(sendTo);

// Step 3: Set who the email is sent from
mail.setReplyTo(‘pcallery@cybexintl.com’);
mail.setSenderDisplayName(‘Cybex Parts’);

// (Optional) Set list of people who should be CC’ed
List ccTo = new List();
ccTo.add(‘bpoliqui@aol.com’);
mail.setCcAddresses(ccTo);

// Step 4. Set email contents – you can use variables!
mail.setSubject(‘URGENT BUSINESS PROPOSAL’);
String body = ‘Dear ‘ + ‘Bob’ + ‘, ‘;
body += ‘I confess this will come as a surprise to you.’;
body += ‘I am John Alliston CEO of the Bank of Nigeria.’;
body += ‘I write to request your cooperation in this ‘;
body += ‘urgent matter as I need a foreign partner ‘;
body += ‘in the assistance of transferring $47,110,000 ‘;
body += ‘to a US bank account. Please respond with ‘;
body += ‘your bank account # so I may deposit these funds.’;
mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);
}
}
// Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
}

Reply
    David
    June 29, 2016 @ 11:12 pm

    List mails =
    new List();

    Reply
    Anonymous
    August 10, 2016 @ 8:24 am

    Hello Bob, Did you figure out the issue with this trigger?

    Reply
hp
June 18, 2015 @ 2:15 am

Police.. we found him.. this is the guy who took 1000$ from me!!!!

Nice David, thanks for making this site so interesting. It is fun to learn..I spend at least an hour a day here. Kudos!!

Reply
Gregory
May 21, 2015 @ 9:03 am

Interestingly…. I did not find ‘setReplyto’ listed in the Apex documentation under singleEmailMessage methods… Since there are plenty of use-cases where those programming these emails might not want to reference a default email (i.e. in the case of the user commenting in the StackExchange link…..”email of the internal user… editing record…triggering email…

http://salesforce.stackexchange.com/questions/1243/setting-a-from-address-in-singleemailmessage

Good BG info for those writing email messages and handlers…. Perhaps if you have some time, you might comment on the comments:)

Reply
Murali
May 2, 2015 @ 5:21 am

Thanks David for taking time and doing this for helping us. Appreciate the same very much.

Reply
Chris Morgan
February 25, 2015 @ 9:25 am

Hey David,

Thanks for putting this together, I have used it many times already. I am running into one issue that I am hoping you can help with. I have a trigger (before insert,before update) that is sending an email to a Lead. When the email is received it displays the Owners name but the email displayed is mine. If we click Reply to reply to the message it shows the correct email address for the owner as the reply to, but I am concerned about my email address showing with the name of the owner when the customer looks at the initial email.

Some additional notes:

1. The owners of the Lead are Partner Community users that are being assigned a Lead and we want to send this email to the Lead containing the partners information.

2. I am running this in my Sandbox org.

3. I have a working trigger in production, but it is an after update trigger that fires with the action of the partner accepting the Lead. We are changing that process to this new one.

Here are the set lines for the owner information:

mail.setReplyTo(ownerEmail); – ownerEmail address is: jonezie127@email.com
mail.setSenderDisplayName(owner); – owner name is Elizabeth Jones

Displays in email:
Elizabeth Jones

Really appreciate any insight.

Keep up the GREAT work!!!

Chris

Reply
    David Liu
    February 28, 2015 @ 4:31 pm

    Too much for me to process honestly although I’m sure you’ll find your answer either on SFDC99 forums or the official ones!

    Reply
    David
    June 29, 2016 @ 11:15 pm

    You’ll need to register the owner email as an org-wide email address for it to be used.

    Reply
Mayank Srivastava
February 17, 2015 @ 12:31 pm

This is beautiful code, David! It’s so beautiful that my fingers are now itching to implement it in my org =)
On a side note, it would be nice and helpful to have 2-3 sample scenarios at the end of each chapter (whenever you introduce a new concept) to get a better idea about how a certain feature can be put to good use in Salesforce. For example: Chapter 6 ( Sub chapters 3. & 4.)
Just my 2 cents!

Reply
    David Liu
    February 17, 2015 @ 7:07 pm

    Great suggestion Mayank (as always)!

    My backlog is getting pretty long now!!

    Reply
      Tushar
      June 15, 2015 @ 6:21 am

      Hi David,

      How to write test class for above Messaging?

      Thanks in advance,
      Tushar

      Reply
Other David
January 8, 2015 @ 5:40 pm

Hi David,

I’ve used your tutorials to build out a trigger, which includes an email send.

Everything seems to be running OK on he Sandbox, but I’m not receiving the emails.

Any thoughts on what might be tripping this up? I’ve been going in circles for a couple of days now and got to the point where I’m tempted to just deploy it live and see if it works but I know I shouldn’t :)

Some notes on the troubleshooting I’ve tried:

– The Sandbox’s Deliverability Access level is set to “All email”.

– I have used “Test Deliverability” from the Sandbox to verify that it is able to send to these particular emails. One is a work email, one’s a personal Gmail, one’s a personal email on another domain – so I’d be really surprised if all 3 had spam or similar issues (and in a way where I still can’t find any trace of the message).

– None of these emails are users, or appear on Accounts/Contacts anywhere in the Sandbox org.

– I’m using SystemAsset to check sendEmailResult, and it looks OK. If I tweak the email content (e.g. deliberately set a malformed email address with no @), then it fails as expected. If I tweak the Assert conditions, then it fails as expected.

Messaging.sendEmailResult[] sendEmailResults = Messaging.sendEmail(new Messaging.Email[] {email});

System.assertEquals(1, sendEmailResults.size()); // the trigger should send exactly 1 email
System.assertEquals(true, sendEmailResults[0].success);

– I can see the email details in the debug log, and it seems OK (I’ve altered the toAddresses when posting here, in the code they are real working emails).

12:04:16:061 EMAIL_QUEUE [87]|subject: test trigger email, bccSender: false, saveAsActivity: false, useSignature: false, toAddresses: [email@workemail.com, email@gmail.com, email@iinet.net.au], plainTextBody: The trigger has done stuff,

12:04:16:061 TOTAL_EMAIL_RECIPIENTS_QUEUED 3

Reply
    David Liu
    January 8, 2015 @ 5:50 pm

    Other David, ha ha ha, you are experiencing one of the most frustrating problems!

    You sound extremely thorough (sign of a good coder) so I’m guessing you already checked all your spam folders.

    Other things to check:
    – The “Email Log Files” link in Setup
    – “Test Deliverability” in Setup and make sure you get exactly the 52 or so emails

    Or you can always try sending the mail to me =) Wait a minute, no, don’t do that!!! =P

    David

    Reply
      Other David
      January 8, 2015 @ 7:27 pm

      Thanks for the quick reply :)

      – Yes I’ve had a good look through the spam folders, no sign of the emails or even of a rejection/warning notification.

      – With Test Deliverability I do get exactly 52 emails each time.

      – “Email Log Files” are NOT showing the emails from my Trigger. All I’m seeing in the Log Files are the batches of 52 Deliverability test emails, plus the notification emails telling me that my log request has finished.

      So the issue seems to lie somewhere with the email entering the email queue, but the queue not actually being processed/sent?

      Reply
        David Liu
        January 8, 2015 @ 8:08 pm

        Not 100% ready to put it on that yet but it very well could be! Are you positive it’s set to “All email” in deliverability?!

        Whenever and whatever solution you find please let us know!

        Reply
          Other David
          January 11, 2015 @ 11:45 pm

          Sooooo, I figured out what the problem was.

          Everything in my trigger is working fine, it’s just that a test class cannot send an email!

          This is documented in the info about creating unit tests (e.g. https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_unit_tests.htm says “You can’t send email messages from a test method.”), but it doesn’t seem to be documented on any of the the pages related to email methods like Messaging.sendEmail or SendEmailResult.

          I’ve suggested Salesforce update the pages relating to email methods to make it clearer that a unit test can’t send emails.

          So in this particular case, deploying to live in frustration turned out to be the right thing to do :)

          Reply
            David Liu
            January 12, 2015 @ 6:14 pm

            Ha ha ha of course!

            Great job debugging – you’ll never get stuck on this error again, guarantee it! =)

            Reply
            Padma Sharma
            September 6, 2021 @ 4:54 am

            Thank you David!! I am in same situation as yours and this article really helped me! I had no clue why the email wasn’t getting sent from test class despite of no issue with code and configuration.

            Reply
Aron Schor
December 29, 2014 @ 3:50 pm

Hi David,

I am attempting my first email trigger but need some guidance.
I have tested Workflow and created Sales Orders/Sales Order Lines in my Dev account.
I am not quite sure what I need to change and to what. I have tried watching the vids and reading your tips/comments!
I want to send an Email to Email in the TransmissionEmail (custom) field in Accounts when a Sales Order (custom) is status 8.
I have had mixed luck with Workflow sending emails to myself (sometimes the suggested code in the template creator doesn’t result in text, see my comments below.)

I guess you can call this a sad start? :) Any help would be appreciated!

// Send shipping update to Transmission email
trigger ShippingAlert on Sales_Order__C (after insert, after OrderStatus__c = 8) {
// Step 0: Create a master list to hold the emails we’ll send
List mails =
new List();

for (Contact myContact : Trigger.new) {
if (Transmission_Email__c != null && myContact.FirstName != null) {

// Step 1: Create a new Email
Messaging.SingleEmailMessage mail =
new Messaging.SingleEmailMessage();

// Step 2: Set list of people who should get the email-I switched myContact.Email to be Transmission_Email__c
List sendTo = new List();
sendTo.add(Transmission_Email__c); mail.setToAddresses(sendTo);

// Step 3: Set who the email is sent from – This should be fine
mail.setReplyTo(info@—.com);
mail.setSenderDisplayName(‘Pac-Kit Customer Service’);

// Step 4. Set email contents – The subject and second line works. Lines after “Your order includes” doesn’t work in Workflow. I am guessing the issue is there could be numbers I have to use, as there could be multiple Sales Order lines?
mail.setSubject(‘{!Sales_Order__c.Name} is shipping today’);
String body = ‘Hi’
body += Your purchase order {!Sales_Order__c.Name} (our Sales Order {!Sales_Order__c.SalesOrderNumber__c}) is now status 8, so it will ship today.
body += Your order includes the following item (possibly more.)
body += ‘Product {!Sales_Order_Line__c.ProductName__c}’;
body += ‘Name {!Sales_Order_Line__c.Name}’;
body += ‘Any questions feel free to reply!’;

// Step 5. Add your email to the master list (as is)
mails.add(mail);
}
}
// Step 6: Send all emails in the master list (as is)
Messaging.sendEmail(mails);}
}

Reply
    David Liu
    December 29, 2014 @ 4:46 pm

    This one’s a job for System.debug!
    https://www.sfdc99.com/2014/02/22/debug-your-code-with-system-debug/

    Reply
      Aron Schor
      January 10, 2015 @ 6:09 pm

      Hi David, I got help from the forums regarding this trigger and now I am reading the Development with the Force.com Platform book (retaining what I can, some parts are a bit advanced.)

      Question (which can apply to others Objects)
      I created a custom object called Timecard.
      It’s related to Contact (Master-Detail(Contact))
      When I created the relationship and set the API name, should I have called it Contact like the standard field? I created a unique name (ContactTimecardlookup__c) but its causing problems when I use the examples in my book. I assumed naming it the same thing might cause problems.

      Reply
        David Liu
        January 12, 2015 @ 6:20 pm

        You can name it anything you like as long as it’s easy for you =)

        Not too late to change it!

        Reply
Saro
November 3, 2014 @ 12:51 am

How can i move to new line in body of the email.

i need my output as given below :

Dear Name,

Please find the attachment.

Regards,
Sys Admin

but i’m getting like this

Dear Name, Please find the attachment. Regards, Sys Admin.

what can i do to get in different lines.???

Reply
    David Liu
    November 3, 2014 @ 5:24 pm

    Use this for each line break =)

    <br />

    Reply
      Bradley Farquhar
      May 5, 2021 @ 5:16 am

      I was wondering the same thing. Thank you.
      body += ‘I confess this will come as a surprise to you.’ + ”;

      Reply
Hiker to Climber (@wolfieorama)
October 6, 2014 @ 1:48 am

Hi Liu,

the code works very well, but i was wondering if there is a way to invoke the email to be set from the inbuilt templates with the org. with the code the formatting of the email sent is quite basic.

any help with that ?

Reply
    David Liu
    October 6, 2014 @ 8:12 pm

    Yes!

    You can select a template using one of the methods here:
    https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm#apex_Messaging_SingleEmailMessage_methods

    Reply
Amit
September 28, 2014 @ 2:34 pm

List mails =
new List();
..david can u plz elaborate the above code…i m nt geting it….

Reply
    David Liu
    September 29, 2014 @ 10:01 pm

    Creating a list of a special object in Salesforce. It’ll be more clear once you learn about objects in Chapter 8! For now, simply copy and paste in this scenario =)

    Reply
rachel
August 24, 2014 @ 3:18 pm

I’m not really sure how to explain because I don’t understand :-)
When you make a list, sometimes it’s
List
List

So my question is how do I know how to “setup” the list

Reply
    Lutgardo García Escalera
    September 23, 2014 @ 1:02 pm

    Hello Rachel,
    I think I got your question. There are two steps to get a List with records:

    1. You create (declare a List)
    2. You star adding data or records to the List

    So, going back to the post example:

    // Step 2: Set list of people who should get the email
    List sendTo = new List();
    sendTo.add(myContact.Email);
    mail.setToAddresses(sendTo);

    Does this answer you question?
    What do you mean by “setup”?

    Reply
rachel
August 22, 2014 @ 12:54 pm

Hey David, I’m a little confused about the list as in howhich do I know what to put in?

Also, would you happen to have sample data I can upload to my dev or so I can practice everything?

Reply
    David Liu
    August 24, 2014 @ 3:00 pm

    No sample data sorry! But you might be able to create a bunch quickly in a spreadsheet and upload to your org.

    You can log into my org too if you’re lazy:
    https://www.sfdc99.com/login-to-sfdc99/

    A little confused on your question about lists, let me know!

    Reply
Anonymous
July 12, 2014 @ 4:35 am

hi david,
can u give me testclass for this trigger

Reply
    David Liu
    July 15, 2014 @ 10:10 pm

    Try writing one and I’ll let you know how you did!

    Reply
      Anonymous
      July 16, 2014 @ 1:11 am

      I wrote it with 100% Code coverage.

      Reply
        David Liu
        July 16, 2014 @ 9:40 pm

        Well done!!! You’re good to go then!

        Don’t forget to make sure you followed these principles (100% does not necessarily mean you tested something perfectly!)
        https://www.sfdc99.com/2013/11/02/principles-of-a-good-test-class/

        Reply
yamini
July 10, 2014 @ 4:10 pm

Hi David,

What if we want to send any attachment with the email?

Thanks,
Yamini

Reply
    David Liu
    July 10, 2014 @ 9:29 pm

    Best to put a link to the attachment in the email =)

    Reply
Tan
June 12, 2014 @ 4:16 pm

David
1. Could you please explain me Step 2 please.
2. Is Email a field in contact in “mycontacts.Email that you have mentioned in the above code.

Thanks

Reply
    David Liu
    June 12, 2014 @ 11:00 pm

    No problem!

    The mail.setToAddresses() method only accepts a List as an argument. However we only want to send to one person. Since we can’t use a single email address as the argument (must be a list), we simply create a list with only our record as a workaround!

    And yes, Email is a field on the Contact!

    Reply
Momin
May 20, 2014 @ 12:51 pm

Hi David,

I am using Professional edition, I am looking to set automatic emails to all my fellow workers when a value in a field matches the pre defined value in the apex code. for example if I set value of a field “A” is changed to “0” then it should trigger a template-E-mail to the user of that salesforce account. Is it possible?

Could you please help me? I’ve read that I will have to create a package and then install it for this to function.

Thanks in advance

Reply
    David Liu
    May 20, 2014 @ 5:41 pm

    Hahaha no way! It’s actually pretty easy!

    This post will tell you everything you need to know!
    https://www.sfdc99.com/2014/02/25/comparing-old-and-new-values-in-a-trigger/

    David

    Reply
      Pranav
      May 22, 2014 @ 1:58 am

      Hi David,

      Momin is using Professional Edition.. And you can’t write Apex in PE..

      Pranav

      Reply
        David Liu
        May 22, 2014 @ 5:19 pm

        Ouch! Sorry I don’t have much experience with PE! Have you tried workflow rules and email alerts?

        Reply
          Pranav Marathe
          May 22, 2014 @ 10:36 pm

          Yes. Workflow Rules, API, Profiles & Page Layouts can be bought as an add-on in PE but you will never get the flexibility of Apex classes & Triggers. However, there are some built in features like Lead/Case assignment Rules, Big Deal Alerts can come handy which are similar to a Workflow & trigger.

          PE ready Managed AppExchange Apps can be installed easily and it is the only way Apex code can be deployed on a PE edition. (E.g. Roll-up Helper)

          Reply
            David Liu
            May 22, 2014 @ 10:38 pm

            Thank you for your insight Pranav!!

            Reply
newsfdcdev
May 7, 2014 @ 10:12 pm

Hi David – I’m trying to send an email each time a record is inserted in a custom object to the CreatedBy person.

Is there a way to traverse to the users object and retrieve the email address or do I need to utilize SOQL for that task?

Reply
    newsfdcdev
    May 7, 2014 @ 10:19 pm

    Actually, it seems like that’s possible via CreatedBy.Email.

    However, it doesn’t seem to be sending the email for me (I made it an after insert trigger). Are there certain settings you need to enable for this to work?

    Thanks!

    Reply
    David Liu
    May 7, 2014 @ 10:23 pm

    You’ll need to query that field! A workaround will be to create a formula field to pull that into your object. Every base object field is auto-queried in your trigger!

    Reply
Ian
March 2, 2014 @ 11:02 pm

David,

This is incredibly helpful. Thanks for making it all so straightforward. You should be writing the documentation for SFDC. I’ve read the Apex Workbook and done all the tutorials in it but having read your guide, it all makes so much more sense. I understood what I was doing before, but now I feel like I really get it.

I’m really excited to try setting up my own trigger to send emails. I’m even more excited to see the rest of the chapters come out! Please keep up the steady pace you’ve been on.

Thanks!

Ian

Reply
    David Liu
    March 3, 2014 @ 10:27 pm

    Thanks Ian!

    Maybe Salesforce should give me a ring!!

    David

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


*

*

Theme: Simple Style by Fimply