{"title":"Email bot","url":"https://seanbehan.ca/posts/email-bot","description":"Cloudflare email routing plus Workers AI: an inbox that answers its own mail.","author":"Sean Behan","published":"2024-12-04T20:29:41.990Z","updated":null,"draft":false,"tags":["cloudflare","serverless","typescript"],"readingMinutes":1,"image":null,"sections":[{"id":"how-it-works","text":"How it Works","level":2}],"content_format":"text/markdown","content_url":"https://seanbehan.ca/posts/email-bot.md","content":"### How it Works\n\nIn this post I'm just going to show you something cool I made using cloudflare workers.\n\n```typescript\nimport { EmailMessage } from 'cloudflare:email';\nimport { createMimeMessage } from 'mimetext';\n\nexport default {\n\tasync email(message, env, ctx) {\n\t\tconst content = await new Response(message.raw).text();\n\t\tconst messages = [\n\t\t\t{ role: 'system', content: 'you are an email responder, reply to the given message' },\n\t\t\t{ role: 'user', content }\n\t\t];\n\t\t// @ts-expect-error broken bindings\n\t\tconst { response } = await env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', { messages });\n\t\tconst msg = createMimeMessage();\n\t\tmsg.setHeader('In-Reply-To', message.headers.get('Message-ID') as string);\n\t\tmsg.setSender({ name: 'Sean Behan', addr: 'contact@seanbehan.ca' });\n\t\tmsg.setRecipient(message.from);\n\t\tmsg.setSubject('RE');\n\t\tmsg.addMessage({\n\t\t\tcontentType: 'text/plain',\n\t\t\tdata: `${response}\\n\\nThis was an automated message. If this is urgent, message Sean on Telegram https://t.me/codebam`\n\t\t});\n\n\t\tconst replyMessage = new EmailMessage('contact@seanbehan.ca', message.from, msg.asRaw());\n\n\t\tawait message.reply(replyMessage);\n\t\tawait message.forward('codebam@riseup.net');\n\t}\n} satisfies ExportedHandler<Env>;\n```\n\nThis small amount of code is all it takes to automatically reply to all my emails with llama3.2!\n\nFeel free to copy it and use it yourself. The source code is on [GitHub](https://github.com/codebam/email-bot).\n"}