- the URL needs to be fully specified, so protocol, server, port and directory are also needed. These data are not available outside the Apex context
- the function apex_util.prepare_url can only be called from within an Apex session
My first idea was to prepare the URL for every possible mail while being in an Apex session and store it in the database. The stored URL can be used when generating the email.
This would be technically complex, because a new column would have to be created and the content of this column would have to be kept up to date all the time.
Another possibility would be to create a fake Apex session within the batch process. Then the rest of the code need not be changed. Martin Giffy d’Souza provides a way to create an Apex session in this blogpost. Although this is an 5 year old post I was able to create an Apex session and generate a valid link.
The last solution was chosen because of the simplicity and the absence of need for code change.