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
sales4cesales4ce 

send email from trigger

Hi,

 

i have an object called agreement which has a look up with Opportunity.

Also, on agreement i have a custom field called status__c.

 

Whenever the status values changes, i want to send an email to the opportunity owner.

 

The trigger below is raising an error:

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger sendEmail caused an unexpected exception, contact your administrator: sendEmail: execution of AfterUpdate caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_SAVE_AS_ACTIVITY_FLAG, saveAsActivity must be false when sending mail to users.: []: 

 

trigger sendEmail on echosign_dev1__SIGN_Agreement__c (after Update) {

    List<Id> agrmntId=New List<Id>();
    Id opptyowner=Trigger.New[0].echosign_dev1__Opportunity__r.OwnerId;
    
    for(echosign_dev1__SIGN_Agreement__c agrmnt:Trigger.New){
    
        if(agrmnt.echosign_dev1__Status__c=='Signed')
            agrmntId.add(agrmnt.Id);
    }
    
    List<echosign_dev1__SIGN_Agreement__c> agrmt=[Select echosign_dev1__Opportunity__r.OwnerId From echosign_dev1__SIGN_Agreement__c Where Id IN: agrmntId];
    
    for( echosign_dev1__SIGN_Agreement__c agr: agrmt){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(agr.echosign_dev1__Opportunity__r.OwnerId);
        mail.setTemplateId('00X600000011PoF');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
}

 

Any help on this is highly appreciated.

 

Thanks,

Sales4ce

 

Best Answer chosen by Admin (Salesforce Developers) 
ipsita.biswas@in.v2solutions.comipsita.biswas@in.v2solutions.com

 Hi,

Add the line (in red) to your code

 

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(agr.echosign_dev1__Opportunity__r.OwnerId);
        mail.setTemplateId('00X600000011PoF');

        mail.saveAsActivity = false;
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

Hope this helps!