Skip to content

Instantly share code, notes, and snippets.

@fdorantesm fdorantesm/common.js
Last active Mar 11, 2019

Embed
What would you like to do?
Send emails using nodemailer
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
}
}
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
You can’t perform that action at this time.