| 1 | import type { EmailMessage, Mailer } from "./types"; |
| 2 | |
| 3 | // Minimal Resend HTTP client. Workers can't open SMTP, so transactional mail |
| 4 | // goes through Resend's REST API. |
| 5 | export class ResendMailer implements Mailer { |
| 6 | constructor( |
| 7 | private readonly apiKey: string, |
| 8 | private readonly from: string, |
| 9 | ) {} |
| 10 | |
| 11 | async send(msg: EmailMessage): Promise<void> { |
| 12 | const res = await fetch("https://api.resend.com/emails", { |
| 13 | method: "POST", |
| 14 | headers: { |
| 15 | Authorization: `Bearer ${this.apiKey}`, |
| 16 | "Content-Type": "application/json", |
| 17 | }, |
| 18 | body: JSON.stringify({ |
| 19 | from: this.from, |
| 20 | to: msg.to, |
| 21 | subject: msg.subject, |
| 22 | text: msg.text, |
| 23 | html: msg.html, |
| 24 | }), |
| 25 | }); |
| 26 | if (!res.ok) { |
| 27 | const detail = await res.text().catch(() => ""); |
| 28 | throw new Error(`resend send failed: ${res.status} ${detail.slice(0, 300)}`); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 |