Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active December 29, 2023 13:54
Show Gist options
  • Save ahallora/2161076ac91b9ccfeebd60ee34a1160d to your computer and use it in GitHub Desktop.
Save ahallora/2161076ac91b9ccfeebd60ee34a1160d to your computer and use it in GitHub Desktop.
CloudFlare Email Forwarding - Support for Gmail alias

CloudFlare Email Routing with alias

Steps to make it work

  1. Create a new Email Worker with this script (modify to your needs)
  2. Enable catch-all in CloudFlare Email Routing and send all catch-all mail to this worker
  3. Make sure the forwarded emails are in fact verified to receive email forwarding
  4. You should still keep the "plain" custom mapping without alias enabled; like dad => [email protected]
  5. ??
  6. Profit

This will enable using CloudFlare Email Routing to forward emails from your custom domain to your Gmail, including alias support, so e.g. all mails sent to [email protected] will be routed to [email protected] - including aliases like [email protected].

To set up Gmail to sent on behalf of your custom email domain please follow this excellent guide: https://paulonteri.com/thoughts/how-to/custom-domain-with-gmail#3-sending-mail

export default {
async email(message, env, ctx) {
const users = {
"dad": "[email protected]",
"mom": "[email protected]",
"kid": "[email protected]"
}
const rawEmail = message.headers.get("to").toLowerCase();
// Required for cases where name is defined in to, e.g. "User <[email protected]>"
const emailRegex = /<([^>]*)>/;
const emailWithName = rawEmail.match(emailRegex);
const toEmail = emailWithName ? emailWithName[1] : rawEmail;
const recipient = toEmail.split("@")[0]?.split("+")[0] ?? "";
const isValidRecipient = users[recipient];
if(!isValidRecipient) {
message.setReject("Address not allowed");
return;
}
// Optional special treatment for kids' emails to relay to dad while minor
if(isValidRecipient === users.kid) {
await Promise.all([
message.forward(users.dad),
message.forward(users.kid)
])
} else {
await message.forward(isValidRecipient);
}
}
};
@ahallora
Copy link
Author

ahallora commented Dec 29, 2023

Needs a bit more testing though... 😅

@ahallora
Copy link
Author

It appears to be working now with the added regexp to take into account to-mails containing names too. 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment