Created
July 27, 2016 18:07
-
-
Save brickpop/1b0dbfb168d6c611402f1f5ae40c194e to your computer and use it in GitHub Desktop.
Mailing with images attached
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 config from 'config'; | |
import { sendMail } from './mailer'; | |
export function sendValidationEmail(recipientEmail, userId, validationToken){ | |
let htmlContent, txtContent, title; | |
title = "Welcome to Right Side Coffee" | |
htmlContent = `<html><head><style> body { font-family: monospace; }</style></head><body> | |
<p>Welcome to Right Side Coffee,</p> | |
<p>To activate your account, click on <a href="${config.SERVER_URL}/en/confirm/${userId}/${validationToken}">the link here</a>.</p> | |
<p>If the link does not work, copy the following to the address bar of your browser: <br/> | |
<strong>${config.SERVER_URL}/en/confirm/${userId}/${validationToken}</strong></p> | |
<p>Right Side Coffee Roasters</p> | |
</body></html>`; | |
txtContent = `Welcome to Right Side Coffee, | |
To activate your account, visit the following link on your browser: | |
${config.SERVER_URL}/en/confirm/${userId}/${validationToken} | |
Right Side Coffee Roasters`; | |
sendEmail(recipientEmail, htmlContent, txtContent, title); | |
} |
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 nodemailer from 'nodemailer'; | |
import config from 'config'; | |
const transporter = nodemailer.createTransport(); | |
function imgReplaceFunction(imgStr){ | |
imgStr = imgStr.replace(/<img alt="[^"]*" src=(['"])/ig, ''); | |
return { | |
filename: imgStr, | |
path: process.cwd() + '/media/' + imgStr, | |
cid: imgStr | |
} | |
} | |
// MAIN | |
const imagePattern = /<img alt="[^"]*" src=(['"])([a-z0-9\-\.]+)/ig; | |
export function sendEmail(recipientEmail, htmlContent, txtContent, title){ | |
if(!htmlContent) return; | |
let params = { | |
from: config.FROM_EMAIL, | |
to: recipientEmail, | |
subject: title, | |
text: txtContent, | |
html: htmlContent | |
}; | |
var contentImages = htmlContent.match(imagePattern); | |
if(contentImages) { | |
contentImages = contentImages.map(imgReplaceFunction); | |
if(contentImages.length) { | |
htmlContent = htmlContent.replace(/<img alt="([^"]*)" src=(['"])([a-z0-9\-\.]+)/ig, "<img alt=\"$1\" src=$2cid:$3"); | |
params.attachments = contentImages; | |
} | |
} | |
transporter.sendMail(params); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment