Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active December 29, 2023 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 => dads-email@gmail.com
  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 dad@example.com will be routed to dads-email@gmail.com - including aliases like dad+dy@example.com.

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": "dads-email@gmail.com",
"mom": "moms-email@gmail.com",
"kid": "kids-email@gmail.com"
}
const rawEmail = message.headers.get("to").toLowerCase();
// Required for cases where name is defined in to, e.g. "User <user@example.com>"
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