Last active
March 11, 2019 17:05
-
-
Save fdorantesm/77c281f225670dfbd1e13d00996bb0d9 to your computer and use it in GitHub Desktop.
Send emails using nodemailer
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
import fs from 'fs' | |
const $app = process.env.APP_PATH | |
const $src = process.env.SRC_PATH | |
export function view(path) { | |
const file = `${$app}/views/${path}.pug` | |
if (fs.existsSync(file)) { | |
return file | |
} | |
else { | |
const error = new Error("Not Found") | |
error.message = "View not found" | |
throw error | |
} | |
} |
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
import mailer from 'nodemailer' | |
import pug from 'pug' | |
import {view} from 'helper/common' | |
export default async function send(options) { | |
try { | |
const html = options.view ? pug.renderFile(view(options.view), options.data || {}) : (options.html || "") | |
const transport = mailer.createTransport({ | |
host: process.env.MAIL_HOST, | |
port: process.env.MAIL_PORT, | |
auth: { | |
user: process.env.MAIL_USER, | |
pass: process.env.MAIL_PASS | |
} | |
}) | |
let mailOptions = { | |
//from: `"${process.env.MAIL_FROM_NAME}" <${process.env.MAIL_FROM_MAIL}>`, | |
from: options.from || process.env.MAIL_FROM_MAIL || `noreply@${process.env.APP_HOST}`, | |
to: options.to.toString() || process.env.MAIL_FROM_MAIL, | |
subject: options.subject || "", | |
text: options.text || "", | |
html | |
} | |
return await transport.sendMail(mailOptions) | |
} | |
catch(error) { | |
throw error | |
} | |
} | |
const message = 'Hello world' | |
send({ | |
from: "Fernando Dorantes <fernando@dorant.es>", | |
to: ["John Doe <doe@email.com>"], | |
subject: "Testing mail using nodemailer", | |
view: "email/testing", | |
text: message, | |
data: { | |
message | |
} | |
}) | |
.then(info => console.log(info)) | |
.catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment