Created
February 21, 2023 22:45
-
-
Save webbertakken/3f4f5071f8da54dd0ec968d773b3a07d to your computer and use it in GitHub Desktop.
Cloudflare forwarding Email to Discord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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