The following exception is thrown when sending emails and updating the users using apex with setSaveAsActivity set as true while sending emails.
Exception:
MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: EmailMessage: []
Sample Code to reproduce the issue:
User objUser = [
SELECT Id, IsActive
FROM User WHERE Name = 'Test User'
LIMIT 1
];
List < Messaging.SingleEmailMessage > listMessages = new List < Messaging.SingleEmailMessage >();
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
List < String > listToAddresses = new List < String > { '[email protected]' };
message.setToAddresses( listToAddresses );
message.setSubject( 'Testing Email' );
message.setUseSignature( false );
message.setHtmlBody(
'<h1>Testing</h1>'
);
listMessages.add( message );
if ( listMessages.size() > 0 ) {
Messaging.sendEmail( listMessages );
}
objUser.IsActive = false;
update objUser;
Use setSaveAsActivity( false ) to resolve the issue.
Sample Code to fix the issue:
User objUser = [
SELECT Id, IsActive
FROM User WHERE Name = 'Test User'
LIMIT 1
];
List < Messaging.SingleEmailMessage > listMessages = new List < Messaging.SingleEmailMessage >();
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
List < String > listToAddresses = new List < String > { '[email protected]' };
message.setToAddresses( listToAddresses );
message.setSubject( 'Testing Email' );
message.setUseSignature( false );
message.setSaveAsActivity( false );
message.setHtmlBody(
'<h1>Testing</h1>'
);
listMessages.add( message );
if ( listMessages.size() > 0 ) {
Messaging.sendEmail( listMessages );
}
objUser.IsActive = false;
update objUser;