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
Henrique RodriguesHenrique Rodrigues 

How to send a email in a trigger

Hi experts, i'm trying to develop a trigger that send an email when a record is created with a condition, but when I insert the record in the object i'm not receive the email.

This is my code: 
trigger Fila on Fila__c (before insert) {

	 	
    	List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
  
    	for(Fila__c fila : Trigger.New) {
            
            if(fila.Posicao__c == 2){
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
	  		//  list of people who should get the email
          	List<String> sendTo = new List<String>();
          
          	sendTo.add('henriquelive19@gmail.com');
          	mail.setToAddresses(sendTo);
        
          	// Set email is sent from
          	mail.setReplyTo('henrique@mobiaplicativos.com.br');
          	mail.setSenderDisplayName('henrique');
        
          	// Set email contents
          	mail.setSubject('URGENT BUSINESS PROPOSAL');
          	String body = 'Dear ';
          	body += 'Email Body.';
          
          	mail.setHtmlBody(body);
        
          	// Add your email to the master list
          	mails.add(mail);
            
            try
             {
               Messaging.sendEmail(mails);	
             }
            catch (Exception e) {
               System.debug('erro' + e);
             }
      	}
  	}
}

my test class is working, but the trigger are not working, anybody can help me in this case?
Best Answer chosen by Henrique Rodrigues
Zachary WaltonZachary Walton
Its hard to tell with how your code is formatted but I would move the try/catch out of the For loop and see if that helps. I cant seem to find anything wrong with how you are building the Email but maybe refer to https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm for any extra help.

All Answers

Raj VakatiRaj Vakati
Can you please check email deliverability? Setup --> Email Administration --> Deliverability . Make sure All emails 
 
Zachary WaltonZachary Walton
Its hard to tell with how your code is formatted but I would move the try/catch out of the For loop and see if that helps. I cant seem to find anything wrong with how you are building the Email but maybe refer to https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm for any extra help.
This was selected as the best answer