[SalesForce] Sending email in sandbox post copy

When I refresh a sandbox I have a class that runs to fix some things like email addresses and custom settings. I've also been asked to email the developer the new org ID so that their testing environments can stay connected.

The problem is when I refresh the sandbox, email deliverability defaults to "system email only", and I cannot switch it to "All Emails" until after logging in, which is well after the refreshpostcopy has run. This means I can't email as part of the refreshpostcopy.

Is there a way to set email deliverability to "all emails" in apex? If not is there another way to get the developer that information?

    String sysemail = [SELECT Email FROM User WHERE Email like 'myusername' LIMIT 1].email;

    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> sendTo = new List<String>();
    sendTo.add('myemail@test.com');
    mail.setToAddresses(sendTo);
    mail.setSubject('Subject');
    mail.setPlainTextBody('New Sandbox ID is '+context.organizationId());
    mails.add(mail);
    Messaging.sendEmail(mails);

The error I get is System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.: []

Best Answer

When you create/refresh sandbox, Email Deliverability default to System Email Only. System Email Only allows us to send emails to users or reset passwords.You can run below class, when you create/refresh sandbox. enter image description here

When you run below class then it will update all System Admin's user's email address and that will eventually send email to user.

global class SandboxPostRefresh_AC implements SandboxPostCopy { 

    global void runApexClass(SandboxContext context) { 

        System.debug(context.organizationId()); 

        System.debug(context.sandboxId()); 

        System.debug(context.sandboxName()); 

        run(); 

    } 

   global static void run() { 

   //List of all emails from the User object  

    List<User> userEmailList = [select Email from User where profile.name = ‘System Administrator’]; 

    for(User uc : userEmailList) 

    { 

        uc.Email = uc.Email.replace('=','@'); 

        //to remove appended domain 

        String addedPhrase = '@example.com'; 

        uc.Email = uc.Email.remove(addedPhrase); 

        userEmailList.add(uc); 

    } 

    if(userEmailList.size() > 0) 

    { 

         Update userEmailList; 

    } 

    } 
} 
Related Topic