2

I am trying to send an email and the related attachments to a custom object in salesforce. Currently the code saves but I am not getting any emails sent out. Not sure why the email is not sending.
Any assistance would be greatly appreciated.

    trigger Send_To_PropSub on Sales_Handoff_Activity__c (before update) {

for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.Tech_Doc_Status__c == 'Complete') {
       Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

       List<Messaging.EmailFileAttachment> attachmentList = new List<Messaging.EmailFileAttachment>();

       //SHA = [SELECT id, Name, Primary_Email__c, Account_Name__c FROM Sales_Handoff_Activity__c WHERE Id = :SHA.Id];                    

        // create email content
        String Name = SHA.Name; 
        String AccountName = SHA.Account_Name__c;

        String subject = 'Tech Docs Complete for '+Name;
        email.setSubject(subject);


        String line1 = 'Please review the attached completed tech docs for:'+AccountName+'+';
        String line2 = 'You can also view these on the Sales Handoff Activity ::'+Name+'+';
        String line3 = 'thank you!  Sales Ops';
        String body = line1 + line2 ; 
        email.setPlainTextBody(body);


        email.setToAddresses(new String[]{'Kevin.chiles@megapath.com'});
        {

            SHA.Tech_Doc_Status__c = 'Complete'; 

            // fetch attachments for Sales_Handoff_Activity__c
            Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id];

   // List of attachments handler
   Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

   {


     // Create the email attachment
     efa.setFileName(att.Name);
     efa.setBody(att.body);
     efa.setContentType(att.ContentType);
     efa.setInline(false);

        attachmentList.add(efa);
   }

    // Attach files to email instance
    email.setFileAttachments(attachmentList);

     Messaging.sendEmail(new Messaging.singleEmailMessage[] {email});
          }
      }  
   }
}

and its test class passing at 100 percent. However, the email is not hitting my inbox.

@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='test@test.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;


        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='Complete';

        update Sha;
    }
}
  • (1) emails not being sent? when running through the UI or via testmethods (tests never send emails) (2) Are you getting any exception on the sendEmail() method? (3) you are adding attachments to the email after sending it (and such attachments can't exist in a before insert use case) – cropredy Mar 23 '16 at 22:11
  • Hello! When running through the UI it is not sending. I have modified the code to move the send after the attachments are uploaded and moved the code to an After update, after insert function. – Kevin Chiles Mar 25 '16 at 16:02
  • Kevin. What about point (2) ? – cropredy Mar 25 '16 at 16:04
  • no exception on the error, it runs clean with the test class and with the Ui save, but no email is sent. – Kevin Chiles Mar 25 '16 at 17:20
2

also check Email Deliverability

Access level : All email

you can help from here

https://help.salesforce.com/HTViewHelpDoc?id=emailadmin_deliverability.htm

1

A few questions:

  • Are you getting any exceptions at all when your trigger is fired?
  • Do you have any test coverage for this trigger?
  • How are you exercising the code to see if the emails are sent?

I can see several issues with your code. Fixing them could expose the cause as to why your emails are not being sent:

  • You're sending the email before you're adding the attachment to it.

The line:

Messaging.sendEmail(new Messaging.singleEmailMessage[] {email});

should be moved to the end of the if statement, so that your message goes out with the attachment in it.

  • The code is not bulkified! If you insert more than 10 'Complete' records at once, only the first 10 emails will be sent (as the governor limits only allow for 10 email invocations max)
  • There are a few unnecessary variables that can be inlined (Name, subject) or are not used (line3)
  • There is an unnecessary null check (to a variable you initialised above)
  • There is an unnecessary code block ({ and } without a preceding block statement like an if or a for)

All of the above makes the code harder to read and debug, and possibly hiding the cause for your issue. I would suggest cleaning your code, adding some unit tests, and perhaps the reasons for the email not going out will become clear.

  • Here is a copy of the Test class I am using, passing and getting 100 percent coverage with currently. – Kevin Chiles Mar 25 '16 at 16:36
0

Ok, Here is the final code. This is working perfectly`

`trigger Send_To_PropSub 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> attachmentList = new List<Messaging.EmailFileAttachment>();

   //Create message

   Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
    //add template
   singleMail.setTemplateId(et.Id);              
    //set target object for merge fields
    singleMail.setTargetObjectId(SHA.OwnerId);

    //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','highcap@megapath.com' ,'Salesops@megapath.com'}; 

    //set addresses
    singlemail.setToAddresses(toAddress);


        //add mail
            emails.add(singleMail);

    {



        // fetch attachments for Object
 Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id];

// List of attachments handler Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

{

 // Create the email attachment
 efa.setFileName(att.Name);
 efa.setBody(att.body);
 efa.setContentType(att.ContentType);
 efa.setInline(false);

    attachmentList.add(efa);

}

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

}
} }

0

I did the same thing to send emails in an automated way, however found that this does not work well when there are attachments in the emailtemplate object.

To be more specific: I am working with Summer '18 and if I create a lightning emailtemplate (not classic) and use it with this code, it works great. However, if I add an attachment to the email template, it will not work and instead it will generate this error "SendEmail failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []" when the sendEmail() command is executed.

I am quite sure that this will happen with your code too. Can you check? Maybe we can join forces to get to a final code that is even more robust and works great with attachements of the emailtemplate too.

Thanks

Sebastiano

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.