Nodemailer
Nodemailer - is a package that connects sender mailbox for sending messages (so messages will be saved in Sent folder of the mailbox).
- npm init -y
- Add script "start:dev": "nodemon app"
- npm i nodemailer dotenv
- npm i nodemon -D
- Create in root of the proj .prettierrc.json
-
Add .env file in root of project with necessary
-
EMAIL_SENDER=... - mailbox from what messages send;
-
EMAIL_EXTAPP_PASS=... - some post services use additional
password for external applications.
f.e. EMAIL_EXTAPP_PASS is tookSo configs in node.js will be different, f.e. gmail, ukr.net etc.- "gmail" - in Security/How you sign in to Google/2-Step Verification/App passwords- "ukr.net" - in Management of IMAP access/Access for external applications
-
- Before pushing the initial repository to the github remember about adding .gitignore to the project including in the beginning .env
Example 1 - synchro fn send to a one receiver
app.js
See the Pen 123__app.js__nodemailer_from_gmail by Andrii (@imitator) on CodePen.
Example 2 - app.js without any web-servers
Example 3 - send a message from any CTRL
- Create repo according to MERN - quick guide till moment of user REGISTRATION and LOGIN.
- npm i nodemailer
- Look up of adding to .env EMAIL_SENDER, EMAIL_EXTAPP_PASS
-
Create utils\sendMailByNodemailer.js
See the Pen 126__nodemailer__Ex3 by Andrii (@imitator) on CodePen.
P.S. Remember about reexport in utils\index.js - Send email from f.e. controllers\auth\registerCTRL.js
Example 4 - "approve email after registration" message and verifyCodeCTRL
- Create repo according to MERN - quick guide till moment of user REGISTRATION and LOGIN.
- npm i nodemailer nanoid@3
- Look up of adding to .env EMAIL_SENDER, EMAIL_EXTAPP_PASS
- Add two fields to models\schemas\user.schema.js
- In controllers\auth\registerCTRL.js create verifyCode, add to user object and send email with a code link
-
In routes\auth.routes.js create verify route
router.get('/verify/:verifyCode', ctrl.verifyCodeCTRL);
-
controllers\auth\verifyCodeCTRL.js
P.S. Remember about service.findUser, service.updateUserSRV