Find your content:

Search form

You are here

sendemail method not working

 
Share

In a commandbutton I have an action called save and in that method in have sendemail method with condition in this way...

 public void save(){
        // my code here
      if(member.name=='MyName'){
         sendEmail(emailcontentbody);
      }
}

In sendemail method I'm having singleemail messaging values...when I check it with condition it is throwing me an error

System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

Error is in expression '{!save}'

Edit: Formatted code from comment below:


@future(callout=true)
  public static void sendEmail(string emailcontentbody,string Template,string useremail,string billingemail){

  Messaging.singleEmailMessage email1 = new Messaging.singleEmailMessage();
  List emailcontentinfo = 
    [Select 
       Mail_Content_Data__c 
     From 
       Designer_Content_Data__c 
     Where 
       CnP_Designer__r.name =:Template ]; 

  for(Designer_Content_Data__c econtent : emailcontentinfo){
    emailcontentbody+=econtent.Mail_Content_Data__c; 
  }
  email1.seToaddresses('emailaddress');
  email1.setHtmlBody(emailcontentbody);
  Messaging.sendEmailResult[] res = Messaging.sendEmail(new Messaging.singleEmailMessage[]{email1});
}

Attribution to: Eagerin Sf

Possible Suggestion/Solution #1

EDIT : Having said this, I've just tried sending an email after a DML Operation in both a Trigger and a Controller Save method, and it works okay in both cases. Are you doing something like saving inside a for loop and a send email after each save, all inside the for loop ?


Mixing callouts(I've only seen this behaviour with http callouts in the past) and dml operations in the same context is not permitted.

I'm guessing the reasoning behind this behaviour may be because salesforce hasn't fully committed the database operation, which can be rolled back, but any resulting action from the callout may not be idempotent. (I see it like a 2 phase commit in my mind)

One solution would be to move your sendEmail to a @future method.

(P.S. I'd also be tempted to try sending all emails first and then invoking the actually database save, to see if that also solves the problem.)


Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3963

My Block Status

My Block Content