I have a code where I send email using single email message.
I am setting targetObjectId
as a contact Id.
I am getting the following error:
System.EmailException: SendEmail failed. First exception on row 0; first error: UNABLE_TO_LOCK_ROW.
The record for which the error occurs is a Contact.
As per my research, if a record is under process, still we can query its value and use it. Why is this error occurring?
The error doesn't occur always, but is happening regularly.
Below is the method :
public static void sendEmail(List<Id> contactids)
{
EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'XYZ'];
if(et.Id!= Null)
{
List<SingleEmailMessage> emailList = new List<SingleEmailMessage>();
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = '[email protected]'];
for(Id conId: contactids)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(conId);
mail.setTemplateId(et.Id);
mail.setOrgWideEmailAddressId(owea.get(0).Id);
emailList.add(mail);
}
}
if(!emailList.isEmpty()){
Messaging.sendEmail(emailList); // I am getting the Unable_To_Lock_Row error here
}
}
setSaveAsActivity()
at all, or useFOR UPDATE
in a SOQL query? Can you include your email sending code?if(et.Id!= Null)
is not necessary here-- if the template is not found, you'll get a QueryException.