How do I block sender domains with email worker?

How do I modify “blocklist senders” script to block domains? Trying bare domain or “*.example.com” in starting example below doesn’t work. Thanks!

export default {
  async email(message, env, ctx) {
    const block = ["[email protected]", "[email protected]"]
    if (block.indexOf(message.headers.get("from")) == -1) {
      await message.forward("inbox@corp");
    } else {
      message.setReject("Address is blocked");
    }
  }
}

Untested, but something like this should do the trick:

export default {
	async email(message, env, ctx) {
		const blockedDomains = ['example.com'];
		const from = message.headers.get('from');
		const isBlocked = blockedDomains.some(domain => from.includes(domain));

		if (isBlocked) {
			message.setReject('Address is blocked');
			return;
		}
		await message.forward('inbox@corp');
	},
};

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.