+ Start a Discussion
Kevin Chiles 930Kevin Chiles 930 

Complete Trigger for Sending an Email with All related Attachments

Hello!

Below is complete code with test class for sending an Email from a custom object with all of the related attachments upon a variable on the object being set:
 
trigger Send_TechDocs on Sales_Handoff_Activity__c (before update) {



for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.Tech_Doc_Status__c == 'Completed') {
    
    //Retrieve Email template
     EmailTemplate et=[Select id from EmailTemplate where name=:'Tech Doc Complete Full'];
     
     
    //Create email list
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

       //Create attachment list
       List<Messaging.EmailFileAttachment> efalist = new List<Messaging.EmailFileAttachment>();
       
       contact c =[select id, email from Contact where Email=:'Salesops@megapath.com' limit 1];
       //Create message
       
       Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
        //add template
       singleMail.setTemplateId(et.Id);              
        //set target object for merge fields
        singleMail.setTargetObjectId(c.Id);
        singlemail.setwhatId(SHA.Id);       
        //set to save as activity or not
        singleMail.setSaveAsActivity(false);
         
         
        //add address's that you are sending the email to
        String []ToAddress= new string[] {'SSS1@Megapath.com','megapath.highcap@megapath.com' }; 

        //set addresses
        singlemail.setToAddresses(toAddress);
        
        
            //add mail
                emails.add(singleMail);
        
        {
           
                      

            // fetch attachments for Object
                     
            List<Attachment> allatt = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id];                     
         
         // Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id limit 1];

           for(Attachment att : allatt) {
            // List of attachments handler
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

   {
      // try{

        

//Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(att.Name);

efa.setBody(att.Body);

efa.setContentType(att.ContentType);

efaList.add( efa );

  
    
   }

    // Attach files to email instance
   // singlemail.setFileAttachments(attachmentList);
   
  {
    singlemail.setFileAttachments(efaList);
   }
   }
    //send the message
     Messaging.sendEmail(emails);
          }

 }  
}
}

Test Class:
 
@isTest
private class EngineerNotesCreateTest
{
    static testMethod void EngineerNotesCreate()
    {
    
    Account acc=New Account(Name='test');
    insert acc;
    
     Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='Salesops@megapath.com',AccountId=acc.id);
        insert ct;
      
     Opportunity opp= New Opportunity (Name='Test',Closedate=date.today(),NextStep='test',StageName='1 – Solution Design',Sales_Engineer__c='Joel Thomas',
     LeadSource='Call - Service Transfer',Type='Change Voice Services',Channel__c='SMB',    
        Install_Street__c='Test',
        Install_Zip__c='94582',
        Install_State__c='CA', 
        Install_City__c='Test',
        Install_Phone__c='3157775695',
        Install_Country__c='USA');
        Insert opp;
     
Booking_Checklist__c  bc= New Booking_Checklist__c(   
Active_Date__c=date.Today(),
Adjusted_Revenue__c=100,
Adjusted_Revenue_Reason__c='Product Line Adjustment',
Affiliate_Name_Matches__c='Yes',
Approval_Status__c='Approved',
Booked_Deal_More_Than_75_Locations__c='Yes',
Booking_Checklist_Record_Owner__c='Joy Cortez',
Checklist_Notes__c='test',
Child_or_Parent_Account_Correct__c='Yes',
Contracted_items_match_products__c='Yes',
Contracted_pricing_match_product_Pricing__c='Yes',
Contract_Signed_by_Valid_Date_Shown__c='Yes',
Correct_Shipping_Address__c='Yes',
Disposition__c='Construction Cost',
Does_Circuit_Speed_Qualify_W_Carrier__c='Yes',
Enrolled_Date__c=system.Today(),
Existing_Cust_Is_the_org_RMR_Reflected__c='Yes',
Existing_Customer__c='No',
Flowed_with_Layer_2_circuit__c='Yes',
Have_residential_services_been_ordered__c='No',
Incorrect_Missing_LCON_Information__c='No',
Is_the_contract_legible__c='Yes',
Is_this_an_out_of_contract_Move_order__c='No',
Is_this_an_R14_to_R17_voice_migration__c='No',
Is_this_a_Sylantro_or_Duet_migration__c='No',
LAN_set_up_missing__c='Yes',
Location_sold_as_new_within_6_months__c='No',
Missing_IP_Blocks__c='No',
Missing_Supp_Address_Information__c='No',
New_customer_booked_by_CAS_Dept__c='No',
NRR_Included_in_Quote__c='No',
Opportunity__c=opp.id,
Order_booked_previously_at_same_location__c='No',
Order_Stage__c='Enrolled',
Partner_splits_Partner_being_tagged__c='No',
Pre_Install_Cancelled_Date__c=system.today(),
Quote_Linked_to_Opportunity_b2b_ID__c='Yes',
Quote_Ordered_Status__c='Data Ready for Review',
Reason_Code__c='Awaiting FOC',
Agent_Matches_Named_Acct_Ent_SMB_HO_Mang__c='Yes',
SCR_Approval_completed_prior_to_booking__c='Yes',
Signed_Contract_Attached_To_Opp__c='Yes',
Signed_contract_has_additional_Writting__c='Yes',
Signed_contract_uploaded_into_MPQT__c='Yes',

Voice_Cloud_MPLS_Orders_SHA_Completed__c='Yes');

insert bc;

     
     
     
        
        Sales_Handoff_Activity__c Sha= new Sales_Handoff_Activity__c(
        Number_of_Seats_Trunks__c='5',
        Primary_Contact_Time_Zone__c='West',
        Opportunity_Name_2__c=opp.id,
        Customer_Contact_Name__c='Kevin Chiles',
        Customer_Contact_Email__c='kchiles2@gmail.com',
        Customer_Contact_Phone__c='0000000000',
        Quote_ID__c='255555.2',
        Expedite_Hand_Off_Date__c= date.today(),
        
        VPM_Notes__c='test notes',
        Assigned_VPM__c='Alex Stewart'
        
        );
        insert Sha;
        Attachment attach=new Attachment();  
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=sha.id;
        insert attach;
        
        sha.tech_doc_status__c='Completed';
        
        update Sha;
    }
}

This works like a dream, enjoy!
Best Answer chosen by Kevin Chiles 930
Kevin Chiles 930Kevin Chiles 930
Solved