[node+JS] The front end uses nodemailer to send emails

  • Preface
  • Email configuration
  • Complete code

Foreword

Recently, it is necessary to realize that after the customer submits the form, the content of the form is sent to the corresponding mailbox as an email. The front-end sends it directly without going through the back-end service. Hiss–, just do it!
After searching, there are many ways to get it, but. . . After trying them all, only one succeeded.

Let me first list the methods I found:
1. formspree: The front-end implements the function of sending emails (Formspree)
After registering a formspree account, when I was about to create a project form, a system crash form kept popping up. Well…

2. SmtpJS: Tutorial on sending emails with SmtpJS
This article seemed to be very reliable, so I operated it like a tiger. . . It always pops up an error for me: Only elasticemail is supported as an SMTP host. To open an account please visit https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8- bae7-911f6097521c, which probably means: only elasticemail is supported as the SMTP host. To open an account, please visit https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c, uh…

3. EmailJS: EmailJS is an email sending that does not require server-side implementation.
This article seems more reliable, but it tells me that a foreign mobile phone number is needed to authenticate a Gmail account, (⊙o⊙)…

4. nodemailer: “nodemailer” Node email sending module
Okay, there is always a way, so we should just write an interface using node…

Email configuration

1. Open NetEase Mailbox–>Settings–>[POP3/SMTP/IMAP]

2. Enable POP3/SMTP/IMAP service

3. Obtain the authorization password

4. You can remember this

5. Initialize your project: npm init -y
6. Add dependencies: npm install express@next dotenv nodemailer --save

dotenv: Load variables in the .env file into process.env
nodemailer: Node.JS email sending module

7. Configure .env information

Complete code

Table of contents

index.html

<form id="myForm">
<label for="name">Name:</label>
<input class="text" type="text" id="name" name="name"><br><br>

<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">female</label><br><br>

<label for="age">Age:</label>
<input class="text" type="number" id="age" name="age"><br><br>
\t
<input class="submit" type="submit" value="Submit">
</form>
  <script>
    //You can add JavaScript code here to handle operations such as form submission.
    const myform = document.getElementById('myForm');
    myform.addEventListener('submit', function (event) {<!-- -->
      event.preventDefault();
      const name = myform.elements.name.value;
      const gender = myform.elements.gender.value;
      const age = myform.elements.age.value;
      const form = `name=${<!-- -->name} & amp;gender=${<!-- -->gender} & amp;age=${<!-- -->age}`

      var ajaxObj = new XMLHttpRequest();
      ajaxObj.open("POST", 'http://localhost:3000/send', true);
      ajaxObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      ajaxObj.send(form);
      ajaxObj.onreadystatechange = function () {<!-- -->
        if (ajaxObj.readyState == 4 & amp; & amp; ajaxObj.status == 200) {<!-- -->
          console.log(ajaxObj.responseText)
        }
      }
    });
  </script>

emailsend.js

var nodemailer = require('nodemailer');
module.exports = class Email {<!-- -->
  constructor() {<!-- -->
    this.config = {<!-- -->
      host: process.env.smtp,
      port: 25,
      auth: {<!-- -->
        user: process.env.mailFrom, //The email account you just registered
        pass: process.env.mailPwd //The authorization code of the email, not the password during registration
      }
    };
    this.transporter = nodemailer.createTransport(this.config);
  }

  sendEmail(mail) {<!-- -->
    return new Promise((resolve, reject) => {<!-- -->
      this.transporter.sendMail(mail, function (error, info) {<!-- -->
        if (error) {<!-- -->
          console.log(error)
          reject(error)
        }
        resolve(true)
      });
    })
  }
}

serve.js

const app = require('express')()
require('dotenv').config()
const sendEmail = require('./emailsend')
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({<!-- --> extended: false }));
app.use((req, res, next) => {<!-- -->
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
app.get('/', async (req, res) => {<!-- -->
  res.send('hello')
})
app.post('/send', async (req, res) => {<!-- -->
  res.header('Access-Control-Allow-Origin', '*')
  const formData = req.body;
  console.log(formData);
  const send = new sendEmail();
  const emailContent = `
  Name: ${<!-- -->formData.name}
  Gender: ${<!-- -->formData.gender}
  Age: ${<!-- -->formData.age}
  `;
  try {<!-- -->
    let email = await send.sendEmail({<!-- -->
      from: '[email protected]',//Sender's email address
      to: '[email protected]',//recipient's email address
      subject: "xxx please check!",//title
      text: emailContent,
    })
    if (email) {<!-- -->
      console.log("Sent successfully!");
      res.send('Sent successfully!')
    }
  } catch (e) {<!-- -->
    console.log("Sending failed");
    res.send(e)
  }
})

app.listen(3000, () => {<!-- -->
  console.log('http://localhost:3000')
})

The above can successfully send the email!