My Email Worker Catchall: Backup Routing, Plus Addressing, and Subdomain Addressing

I guess its not needed. It should be enough to just do:
message.setReject(gmx_error.message + "\n" + gmail_error.message);
without the return (as it is the last call in the code) and I also guess that the setReject method is returning void and so the return is not giving anything back to the caller.

would be great if you can confirm that @user15545

edit 1: At least my assumption with void seems to be true: Cloudflare email worker: do not forward for given domain extensions - #3 by Chaika

edit 2: based on void and some more tests I did I refactored it to this:

        let reject_reason;
        try {
            await message.forward(target_user.primary);
        } catch (gmail_error) {
            reject_reason = gmail_error.message;
            try {
                await message.forward(target_user.backup);
            } catch (gmx_error) {
                reject_reason = gmx_error.message + "\n" + reject_reason;
                message.setReject(reject_reason);
            }
        }

so my final version looks like this:

Final Version
export default {
    async email(message, env, ctx) {

        // defining all alias to user mappings we have
        const users = [{
            alias: [
                "[email protected]",
                "[email protected]",
            ],
            primary: "[email protected]",
            backup: "[email protected]",
        }, {
            alias: [
                "[email protected]",
            ],
            primary: "[email protected]",
            backup: "[email protected]",
        }, {
            alias: [
                "[email protected]",
                "[email protected]",
            ],
            primary: "[email protected]",
            backup: "[email protected]",
        }, {
            alias: [
                "[email protected]",
            ],
            primary: "[email protected]",
            backup: "[email protected]",
        }, ]

        // setting the target_user as our catch all user
        let target_user = {
            primary: "[email protected]",
            backup: "[email protected]",
        }

        // checking if we have a user matching and overwrite the target_user with it
        users.forEach(user => {
            if (RegExp(user.alias.join("|"), "i").test(message.to)) {
                target_user = user;
            }
        });

        // sending mail out, first to google and on error to gmx
        let reject_reason;
        try {
            await message.forward(target_user.primary);
        } catch (gmail_error) {
            reject_reason = gmail_error.message;
            try {
                await message.forward(target_user.backup);
            } catch (gmx_error) {
                reject_reason = gmx_error.message + "\n" + reject_reason;
                message.setReject(reject_reason);
            }
        }
    }
}
2 Likes