因為目前 mailgun 免費版只有試用期間,之後都要付費,所以如果只是要測試暫時只能選擇 sendgrid,sendgrid 目前無提供 POP server 服務,所以無法使用 gmail 設置來收取綁定在 sendgrid 服務上的 domain 信件。
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey("...")
const msg = {
to: '', // Change to your recipient
from: '', // Change to your verified sender
subject: '',
text: '',
html: '<strong>Node.js</strong>',
}
sgMail
.send(msg)
.then(() => {
console.log('Email sent')
})
.catch((error) => {
console.error(error)
})
Node.js inbound email 接收範例
因為是 multipart/form-data 所以用 busboy 模組解析
const express = require("express");
const app = express();
const busboy = require("busboy");
app.use(express.json());
// GET route
app.get("/", (req, res) => {
res.send("Test OK");
});
// POST route
app.post("/parse", (req, res) => {
console.log("POST request");
const bb = busboy({ headers: req.headers });
bb.on("file", (name, file, info) => {
const { filename, encoding, mimeType } = info;
console.log(
`File [${name}]: filename: %j, encoding: %j, mimeType: %j`,
filename,
encoding,
mimeType
);
file
.on("data", (data) => {
console.log(`File [${name}] got ${data.length} bytes`);
})
.on("close", () => {
console.log(`File [${name}] done`);
});
});
bb.on("field", (name, val, info) => {
console.log(`Field [${name}]: value: %j`, val);
if (name === "html") {
console.log("---------------");
console.log("content:", val);
console.log("---------------");
}
});
bb.on("close", () => {
console.log("Done parsing form!");
res.writeHead(303, { Connection: "close", Location: "/" });
res.end();
});
req.pipe(bb);
});
// Start the server
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});