Can we send SingleEmailMessage(s) under admin context and ignore current user sharings and profile access. Details: - visualforce email template is related to object B which is not available for users in particular profiles. user in these profiles has access to object A and editing this object A can initiate sending email based on template related to forbidden/hidden object B. As result email sending fails.
I tried the following code:
public without sharing class ToDelete {
public static void sendEmail(){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage ();
mail.setTargetObjectId('00520000001r17P');//admin
mail.setTemplateID('00XR0000000INj2');//VF email template related to Object B
mail.setSaveAsActivity (false);
mail.setWhatId('a0DR0000004PxQp');//=object B id
mail.settoAddresses(new String[] {'[email protected]'});
//mail.setorgWideEmailAddressId(General_Settings__c.getInstance().Org_Wide_Email_Address__c);
system.debug('---- ' + mail);
List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[]{mail});
system.debug('---- ' + results);
}}
and run unit test:
@IsTest(SeeAllData=true)
private class ToDeleteTest {
static testMethod void verify() {
Id userId = '00520000001r17P';
User u = [select id from User where id = :userId limit 1];
SYstem.runAs(u){
ToDelete.sendEmail();
}
}
This test runs with the following error:
System.EmailException: SendEmail failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, Read access denied for ObjectB__c: []
When I set read access on object B for user profile then test execution is sucessful