+ Start a Discussion
bathybathy 

Apex trigger to send an email with an attachment from the Attachemnts and Notes Section of the Object's Related list

hi Guys,

I have a requirement to send an email alert with a PDF FIle attached to that record when a particular codnition is met . Can nayone please help with the Trigger code for this? 
Best Answer chosen by bathy
Rahul Sangwan7341Rahul Sangwan7341

Hi Bathy, you can reuse the code, based on some button like take Send Email button make a field update and based on your field update send the Email with attachment.

//Put your record id in ParentId
List<Attachment> attList = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : opp.id];
// List of attachments handler
Messaging.EmailFileAttachment[] efaList = new Messaging.EmailFileAttachment();
for(Attachment att : attList)
{ // Create the email attachment Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(att.Name);
efa.setBody(att.body);
efa.setContentType(att.ContentType);
efa.setInline(false);
efaList.add(efa); }
// Attach files to email instance
email.setFileAttachments(efaList);

Please mark this as Best answer if it helps you and let me know if you finding any difficulty in this.

All Answers

Rahul Sangwan7341Rahul Sangwan7341

Hi Bathy, you can reuse the code, based on some button like take Send Email button make a field update and based on your field update send the Email with attachment.

//Put your record id in ParentId
List<Attachment> attList = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : opp.id];
// List of attachments handler
Messaging.EmailFileAttachment[] efaList = new Messaging.EmailFileAttachment();
for(Attachment att : attList)
{ // Create the email attachment Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(att.Name);
efa.setBody(att.body);
efa.setContentType(att.ContentType);
efa.setInline(false);
efaList.add(efa); }
// Attach files to email instance
email.setFileAttachments(efaList);

Please mark this as Best answer if it helps you and let me know if you finding any difficulty in this.
This was selected as the best answer
bathybathy
Thank you so much Rahul for your help. I was able to accomplish this with your help.
 
Admin User 4747Admin User 4747
I'm very new to this -- is it possible to get a more explicit declaration of the trigger and how you actually send the email? I am trying to have this trigger run when "status" field is updated. And I want to send the email to the value in email field associated with the record.