Last active
March 1, 2024 10:05
-
-
Save creuserr/97a78069be7e33069f14b179d7bc3a9f to your computer and use it in GitHub Desktop.
📨 Building your Email API with Fastmail for free! (https://dev.to/creuserr/building-your-email-api-with-fastmail-for-free-h91)
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
const { createTransport } = require("nodemailer") | |
require("dotenv").config() | |
module.exports = (req, res) => { | |
// if the client is within the server, | |
// you can remove this header to | |
// prevent outside access. | |
res.setHeader("Access-Control-Allow-Origin", "*") | |
res.setHeader("Content-Type", "text/plain") | |
if(req.method != "POST") { | |
return res.status(400).end("400 Bad Request: Invalid method") | |
} | |
if(req.body.length < 5) { | |
return res.status(400).end("400 Bad Request: Body is too short (min 5)") | |
} | |
var reciever = req.headers["x-mail-reciever"] | |
var subject = req.headers["x-mail-subject"] | |
if(reciever == null || subject == null) { | |
return res.status(400).end("400 Bad Request: Incomplete headers") | |
} | |
const sender = process.env.EMAIL | |
const password = process.env.PASSWORD | |
try { | |
var transporter = createTransport({ | |
host: "smtp.fastmail.com", | |
port: 465, | |
auth: { | |
user: sender, | |
pass: password | |
} | |
}) | |
const options = { | |
from: sender, | |
to: reciever, | |
subject, | |
html: req.body | |
} | |
} catch(e) { | |
res.status(500).end(`500 Internal Error: Failed to initialize transporter: ${e}`) | |
} | |
try { | |
transporter.sendMail(options, function(e, i) { | |
if(e) { | |
res.status(400).end(`400 Bad Request: Failed to send mail: ${e}`) | |
} else { | |
res.status(200).end("200 Success") | |
} | |
}) | |
} catch(e) { | |
res.status(400).end(`400 Bad Request: Failed to send mail: ${e}`) | |
} | |
} |
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
{ | |
"version": 2, | |
"builds": [{ | |
"src": "api/index.js", | |
"use": "@vercel/node" | |
}], | |
"rewrites": [{ | |
"source": "/api/(.*)", | |
"destination": "/api/index.js" | |
}], | |
"headers": [{ | |
"source": "/api/index.js", | |
"headers": [{ | |
"key": "Access-Control-Allow-Origin", | |
"value": "*" | |
}, { | |
"key": "Access-Control-Allow-Methods", | |
"value": "POST" | |
}] | |
}] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment