function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Benjamin BogartBenjamin Bogart 

Set user for template render in scheduled apex

I have an apex class that sends visualforce email template based email to leads.  Because its a scheduled task, I believe it runs as the System user.  But the merge field {!$User.FirstName} ini the rendered email is filled with my User information.  I'm confused by this.  How does the template determine which user information to use for the merge when the code is run as system?

What I'm really after is being able to use the record owner's profile information in the merge fields.  (We are using an Org Wide Email Address so I don't need to send as the record owner.)  Is there a way to do this?
Benjamin BogartBenjamin Bogart
I've done some further testing, and the Scheduled Apex Class sets the $User variable to the user that scheduled the class to run.

My hope was to be able to use the same template for sending mail manually and automated but it seems that the only option for being able to do that would be to schedule the class to run for each user that needs to send the automated messages.  That isn't practical because it means giving permission to each user to schedule apex classes and if the class needs to be updated all the schedules have to be stopped and restarted.

If there are any ideas on how to send automated messages as a user without scheduling the class to run as that user it would be appreciated.

Thanks,