|
| 1 | +import { POST as postReceiveEmail } from "../route"; |
| 2 | + |
| 3 | + |
| 4 | +export async function POST(request: Bun.BunRequest) { |
| 5 | + const event = await request.json() as { |
| 6 | + type: 'email.received'; |
| 7 | + data: { |
| 8 | + email_id: string; |
| 9 | + }; |
| 10 | + }; |
| 11 | + const emailthingKey = request.params.emailthing_key; |
| 12 | + const resendKey = request.params.resend_key; |
| 13 | + const categoryId = request.params.category_id; |
| 14 | + |
| 15 | + if (event.type === 'email.received') { |
| 16 | + const res = await fetch(`https://api.resend.com/emails/receiving/${event.data.email_id}`, { |
| 17 | + method: "GET", |
| 18 | + headers: { |
| 19 | + "Content-Type": "application/json", |
| 20 | + Authorization: `Bearer ${resendKey}`, |
| 21 | + "user-agent": "EmailThing (https://emailthing.app)", |
| 22 | + }, |
| 23 | + }); |
| 24 | + |
| 25 | + if (!res.ok) { |
| 26 | + const errorData = await res.json(); |
| 27 | + return new Response(`Failed to fetch email data: ${res.status} - ${errorData.message}`, { status: 500 }); |
| 28 | + } |
| 29 | + |
| 30 | + const emailData = await res.json() as { |
| 31 | + from: string; |
| 32 | + to: string[]; |
| 33 | + raw: { |
| 34 | + download_url: string; |
| 35 | + }; |
| 36 | + }; |
| 37 | + |
| 38 | + const rawReq = await fetch(emailData.raw.download_url) |
| 39 | + |
| 40 | + if (!rawReq.ok) { |
| 41 | + return new Response(`Failed to download raw email: ${rawReq.status} - ${await rawReq.text()}`, { status: 500 }); |
| 42 | + } |
| 43 | + |
| 44 | + const rawEmail = await rawReq.text(); |
| 45 | + |
| 46 | + const newRequest = new Request(`https://api.emailthing.app/v0/receive-email`, { |
| 47 | + method: "POST", |
| 48 | + headers: { |
| 49 | + "Content-Type": "application/json", |
| 50 | + Authorization: `Bearer ${emailthingKey}`, |
| 51 | + ...request.headers, |
| 52 | + }, |
| 53 | + body: JSON.stringify({ |
| 54 | + raw: rawEmail, |
| 55 | + from: emailData.from, |
| 56 | + to: emailData.to[0], |
| 57 | + categoryId, |
| 58 | + }), |
| 59 | + }); |
| 60 | + |
| 61 | + return await postReceiveEmail(newRequest); |
| 62 | + } |
| 63 | + |
| 64 | + return new Response("Unknown event type") |
| 65 | +} |
0 commit comments