Skip to content

Instantly share code, notes, and snippets.

@webbertakken
Created February 21, 2023 22:45
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 webbertakken/3f4f5071f8da54dd0ec968d773b3a07d to your computer and use it in GitHub Desktop.
Save webbertakken/3f4f5071f8da54dd0ec968d773b3a07d to your computer and use it in GitHub Desktop.
Cloudflare forwarding Email to Discord
// Todo - Replace next line with your own
const DISCORD_WEBHOOK_URL = 'https://discord.com/api/webhooks/YOUR_WEBHOOK_URL';
export default {
async email(message, env, ctx) {
const url = DISCORD_WEBHOOK_URL;
const { from, to } = message;
const subject = message.headers.get('subject') || '(no subject)'
let rawEmail = new Response(message.raw)
let fullBody = await rawEmail.text()
const [body = '(empty body)', ...rest] = splitMessage(fullBody)
const chunks = [`Email from ${from} to ${to} with subject "${subject}":\n\n${body}`, ...rest]
for (const content of chunks) {
const data = { content }
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
console.log('Failed to post message to Discord webhook');
console.log(await response.json())
throw new Error('Failed to post message to Discord webhook');
}
}
}
}
// Max message size must account for ellipsis and level parts that are added to the message.
const splitMessage = (message, maxMessageSize = 1940) => {
const numberOfMessages = Math.ceil(message.length / maxMessageSize);
const messages = new Array(numberOfMessages);
for (let i = 0, pointer = 0; i < numberOfMessages; i++) {
let messageSize = maxMessageSize;
let prefix = '';
if (i !== 0) {
prefix = '...';
messageSize -= 3;
}
let suffix = '';
if (i !== numberOfMessages - 1) {
suffix = '...';
messageSize -= 3;
}
// Break at spaces
let maxMessage = message.substr(pointer, messageSize);
const lastSpacePos = maxMessage.lastIndexOf(' ');
if (lastSpacePos >= maxMessageSize - 250) {
maxMessage = maxMessage.substr(pointer, lastSpacePos);
messageSize = lastSpacePos;
}
messages[i] = `${prefix}${maxMessage}${suffix}`;
pointer += messageSize;
}
return messages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment