Created
May 2, 2026 03:56
-
-
Save iamparthaonline/135ac0196194f9f9468b1cbe2933d219 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import { Resend } from 'resend'; | |
| import fetch from 'node-fetch'; | |
| import { getEmailTemplate } from './template'; | |
| const resend = new Resend(process.env.RESEND_API_KEY); | |
| // Unified function | |
| export const sendEmail = async ({ | |
| to, | |
| subject, | |
| content, | |
| }: { | |
| to: string; | |
| subject: string; | |
| content: string; | |
| }) => { | |
| const html = getEmailTemplate(content); | |
| try { | |
| // 1. Try SDK first | |
| const sdkResponse = await resend.emails.send({ | |
| from: '[APP_NAME] <no-reply@yourdomain.com>', | |
| to, | |
| subject, | |
| html, | |
| }); | |
| return { | |
| success: true, | |
| source: 'sdk', | |
| data: sdkResponse, | |
| }; | |
| } catch (sdkError) { | |
| console.error('SDK failed, falling back to API', sdkError); | |
| try { | |
| // 2. Fallback to direct API call | |
| const apiResponse = await fetch('https://api.resend.com/emails', { | |
| method: 'POST', | |
| headers: { | |
| Authorization: `Bearer ${process.env.RESEND_API_KEY}`, | |
| 'Content-Type': 'application/json', | |
| }, | |
| body: JSON.stringify({ | |
| from: '[APP_NAME] <no-reply@yourdomain.com>', | |
| to, | |
| subject, | |
| html, | |
| }), | |
| }); | |
| const data = await apiResponse.json(); | |
| if (!apiResponse.ok) { | |
| throw new Error(data?.message || 'API send failed'); | |
| } | |
| return { | |
| success: true, | |
| source: 'api', | |
| data, | |
| }; | |
| } catch (apiError) { | |
| console.error('API also failed', apiError); | |
| return { | |
| success: false, | |
| error: apiError, | |
| }; | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment