+ Start a Discussion
SFDC_BigDogSFDC_BigDog 

Unable to Save email in the Activity History

I have a custom button to send an email. The code is working fine. Now I would like to insert those email in the activity history. I did set mail.setSaveAsActivity(true). But when I click the button it is showing the error as: I am unable to resolve this. Any help is appreciated. The following is my code.
User-added image

Apex Class Code:
 

global class memberApproval {

webservice static boolean callApproval(Id localId) { 
            set<Id> Uid = new set<Id>();
            String grpId = Label.GroupId;
     List<GroupMember> Lst =[Select Id, UserOrGroupId From GroupMember Where GroupId =: grpId];
     if(Lst.size()>0){
     opportunity opp =[select id,owner.email from opportunity where Id =:localId];
     for(GroupMember g:Lst){
         Uid.add(g.UserOrGroupId);
     }

     if(Uid.size()>0){
     List<User> Lstuser = [select id,email from user where Id In:Uid];
     if(Lstuser.size()>0){

     List<String> EmailIds = new List<string>();


     for(User u:Lstuser){
     EmailIds.add(u.Email);
     }
       //New instance of a single email message
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        // Who you are sending the email to

           mail.setToAddresses( EmailIds  );
        String templateIdVal= Label.TemplateId;
       String[] bccEmail = new String[]{opp.owner.email};

           // The email template ID used for the email
           mail.setTemplateId(templateIdVal);
           mail.setTargetObjectId(userinfo.getuseriD());
           mail.setwhatid(opp.id);
           mail.setBccSender(true);
           mail.setBccAddresses(bccEmail);
           mail.setUseSignature(false);
           mail.setReplyTo(opp.owner.email);
           mail.setSenderDisplayName('Confirmation of Order Quote');
           mail.setSaveAsActivity(true);  

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }
     }
     }
    return true;               
}
}
Custom Button Code:
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 
sforce.connection.sessionId = "{!$Api.Session_ID}"; 


var contactCheck = sforce.connection.query("SELECT id from Attachment where parentid = '{!Opportunity.Id}'"); 
records = contactCheck.getArray("records"); 
if(records.length == 0){ 
alert('With out Attachment you can not send Email'); 

}else{ 
sforce.apex.execute("memberApproval","callApproval",{localId:"{!Opportunity.Id}"}); 
alert("Email Sent."); 

}


 
SonamSonam (Salesforce Developers) 
Currently you cannot store the email in the Activity History unless you specify a contact as the TargetObjectId.
Email.setTagetObjectId() must specify a contact, otherwise setWhatId() is not allowed.

It seems to be behaving as expected and there is already an existing idea to modify this behavior:
https://success.salesforce.com/ideaView?id=08730000000HgbwAAC