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
SF_Admin96SF_Admin96 

Sending Email Alert when a new Attachment is added

Hi Experts,

I know that this is not a standard functionality. However, can anyone share a sample code for sending email alert when a new attachment has been added to the custom object.

Here is the specific scenario:

When a new file or multiple files has been added for a custom object, I would like a specific set of users to be notified.

Any assistance is greatly appreciated. Thanks.
Best Answer chosen by SF_Admin96
Gigi.OchoaGigi.Ochoa
I typically like to send emails using workflow instead of via code. 

So here is your design pattern:
  1. Create a checkbox field on your object called Send Attachment Notification Email.  Do not display this field on the page layout.
  2. Create a workflow rule with criteria Send Attachment Notification Email = True, with Evaluation Criteria: created, and any time it’s edited to subsequently meet criteria
  3. Have this workflow rule send an email and do a field update to uncheck the Send Attachment Notification Email field.
Create a trigger on the Attachment to check the Send Attachment Email field when an Attachment is created.

trigger attachmentTrigger on Attachment (after insert) {	
	// 1. Get List of Object Ids you wish to notify on
	Set<Id> objectIds = new Set<Id>();
	
	// 2. Loop through list of attachments, and if attachment is associated to object you want to notify on, add Parent Id to objectIds set
	for(Attachment a:trigger.new){
		 String keyPrefix = a.ParentId.substring(0, 3);
		 
		 if(keyPrefix == '3 DIGIT PREFIX OF OBJECT YOU WANT TO NOTIFY ON'){
		 	objectIds.add(a.ParentId);
		 }
	}
	
	// 3. Get your objects you want to notify on, and set the Send Attachment Notification Email field to True 
        // This will to fire the workflow rule to send the email
	if(objectIds.size() > 0){
		List<YOUR OBJECT> yourObjectList = [SELECT Id FROM YOUR OBJECT WHERE Id IN :objectIds];
		
		for(YOUR OBJECT obj:yourObjectList){
			obj.Send_Attachment_Email__c = true;
		}
		
		if(yourObjectList.size() > 0){
			update yourObjectList;
		}		
	}	  
}


All Answers

AshlekhAshlekh
Hi,

Below code helps you please make some modificatin in code accorind to you.
// Send a business proposal to each new Contact
trigger attachmentTrigger on Attachment (after insert) {
  
  
	  List<attachment> listofAttachment = Trigger.new;
		
	  // Step 0: Create a master list to hold the emails we'll send
	  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
  
      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(add email address here);
      mail.setToAddresses(sendTo);
    
      // Step 3: Set who the email is sent from
      mail.setReplyTo(send to reply email addres.com);
      mail.setSenderDisplayName('What you want to display');
    
      // (Optional) Set list of people who should be CC'ed
      List<String> ccTo = new List<String>();
      ccTo.add('cc address ');
      mail.setCcAddresses(ccTo);

      // Step 4. Set email contents - you can use variables!
      mail.setSubject('URGENT BUSINESS PROPOSAL');
      String body = 'Dear ' + myContact.FirstName + ', ';
      body += 'YOUR TEXT HERE';
      body += 'hello hello .';
      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);
}


IF it helps you than please mark it as a solution and ENJOY APEX
SF_Admin96SF_Admin96
Hi @ashlekh,

Thank you for your help.

I have follow up question though, where should I add this trigger? Because I cannot find a section to add the Attachment trigger. Should I add it to the Parent Object?
Gigi.OchoaGigi.Ochoa
I typically like to send emails using workflow instead of via code. 

So here is your design pattern:
  1. Create a checkbox field on your object called Send Attachment Notification Email.  Do not display this field on the page layout.
  2. Create a workflow rule with criteria Send Attachment Notification Email = True, with Evaluation Criteria: created, and any time it’s edited to subsequently meet criteria
  3. Have this workflow rule send an email and do a field update to uncheck the Send Attachment Notification Email field.
Create a trigger on the Attachment to check the Send Attachment Email field when an Attachment is created.

trigger attachmentTrigger on Attachment (after insert) {	
	// 1. Get List of Object Ids you wish to notify on
	Set<Id> objectIds = new Set<Id>();
	
	// 2. Loop through list of attachments, and if attachment is associated to object you want to notify on, add Parent Id to objectIds set
	for(Attachment a:trigger.new){
		 String keyPrefix = a.ParentId.substring(0, 3);
		 
		 if(keyPrefix == '3 DIGIT PREFIX OF OBJECT YOU WANT TO NOTIFY ON'){
		 	objectIds.add(a.ParentId);
		 }
	}
	
	// 3. Get your objects you want to notify on, and set the Send Attachment Notification Email field to True 
        // This will to fire the workflow rule to send the email
	if(objectIds.size() > 0){
		List<YOUR OBJECT> yourObjectList = [SELECT Id FROM YOUR OBJECT WHERE Id IN :objectIds];
		
		for(YOUR OBJECT obj:yourObjectList){
			obj.Send_Attachment_Email__c = true;
		}
		
		if(yourObjectList.size() > 0){
			update yourObjectList;
		}		
	}	  
}


This was selected as the best answer
SF_Admin96SF_Admin96
Thanks for this Gigi. The steps are very straight forward and it should help me achieve the functionality that I need.
Tierney CraigTierney Craig
Gigi, can you give me an example of how I would use your code? Meaning, what pieces would I need to overwrite with specific data? Thanks!
Tierney CraigTierney Craig
Gigi, I'm also getting an error message when I try to use your code "Method does not exist or incorrect signature: void substring(Integer, Integer) from the type Id." Do you know why this would be? Thanks again!
Rob PezzuloRob Pezzulo
Tierney,
To get Gigi's code working, I had to change line 7 to:
String keyPrefix = String.valueOf(a.LinkedEntityId).substring(0, 3);
This makes it a string instead of Id and the code becomes error-free.

I modified the code a bit to get it to work for Files like so:
trigger cdlTrigger2 on ContentDocumentLink (after insert) {	
	// 1. Get List of Object Ids you wish to notify on
	Set<Id> objectIds = new Set<Id>();
	
	// 2. Loop through list of attachments, and if attachment is associated to object you want to notify on, add Parent Id to objectIds set
	for(ContentDocumentLink a:trigger.new){
		 String keyPrefix = String.valueOf(a.LinkedEntityId).substring(0, 3);
		 
		 if(keyPrefix == '500'){
		 	objectIds.add(a.LinkedEntityId);
		 }
	}
	
	// 3. Get your objects you want to notify on, and set the Send Attachment Notification Email field to True 
        // This will to fire the workflow rule to send the email
	if(objectIds.size() > 0){
		List<Case> yourObjectList = [SELECT Id FROM Case WHERE Id IN :objectIds];
		
		for(Case obj:yourObjectList){
			obj.Send_Attachment_Notification_Email__c = true;
		}
		
		if(yourObjectList.size() > 0){
			update yourObjectList;
		}		
	}	  
}

 
Alejandra Cruz 14Alejandra Cruz 14
Hello all,

I am not familiar on writing code, could anyone help me on writing a new one? I need to create a trigger to check a checkbox on the Case object every time an attachment is added, then I will use this to build a process in process builder to send an email to corresponding users every time the checkbox is true AND/OR there are modifications on the case.

I am stuck on trying to write the code for the trigger. I would highly appreciate your help on it! The checkbox field name is New_Attachment__c.

Thank you, thank you, thank you.