Sendgrid
Sendgrid - the service that take the management of messaging sending.
Example 1. Send e-mail by sendgrid
Example without any express/web-server
- Create project folder to test e-mail sending by sendgrid
- Add script "start:dev": "nodemon app"
- npm i @sendgrid/mail dotenv
- npm i nodemon -D
- Create in root of the proj .prettierrc.json
-
Add .env file in root of project with necessary
- SENDGRID_KEY=thisKeyCopiedInTimeOfCreatingItAndSavedSomewhere
- Before pushing the initial repository to the github remember about adding .gitignore to the project including in the beginning .env
-
app.js
See the Pen 120__send_email_by_SENDGRID by Andrii (@imitator) on CodePen.
Example 2. Send e-mail by sendgrid in any CTRL
- Create repo according to MERN - quick guide till moment of controllers (get, post, update, delete) creating .
-
Add to .env
- SENDGRID_KEY=...
- SENDGRID_SENDER=...
-
Create utils/sendMailBySendgrid.js
See the Pen 121__send_email_by_SENDGRID__function_unified by Andrii (@imitator) on CodePen.
P.S. remember about reexport in utils/index.js -
Import this util in any CTRL, f.e. in addProductCTRL
- const { sendMailBySendgrid } = require('../../utils');
-
Send mail like:
-
const sendMailAnswer = await sendMailBySendgrid({});to: 'john.wick@gmail.com',subject: 'Product added',text: 'Products successfully added',html: ' <h2>Product successfully added</h2> ',console.log('Message send on:', sendMailAnswer[0].headers.date);
-