Assign automatic email sending to a button using nodemailer

Asked

Viewed 100 times

-2

I own a site and I would like that when the user sent a message through the contact, the site sent me this message via email... already configured the sending and is working using NODEMAILER

    const nodemailer = require ('nodemailer');

var assunto = 'teste';
var nome = 'teste2';
var email = '[email protected]';
var msg = 'teste 2 teste 2 teste 2';

let transporter = nodemailer.createTransport({
    host: "mail.example.com",
    port: 465,
    secure: true, 
    auth: {
        user:'[email protected]',
        pass:'****minhasenhasupersegura****'
    }
});

transporter.sendMail({
    from: '<[email protected]>',
    to: '[email protected]',
    subject: assunto,   
    text: 'nome: ' + nome + ' Email: ' + email + ' -- mensagem: ' +msg,

});

the send form where I have the send button of the form is like this:

<form id='contatos'>
    <div class="form-group">
      <h2 id='tituloCont'>Envie sua mensagem</h2>
      <label for="nomeCont" id='labelNome'>Seu nome</label>
      <input type="text" class="form-control" id="nomeCont" placeholder="Digite aqui seu nome">
    </div>
    <div class="form-group">
      <label for="motivoCont" id='labelMot'>Qual o motivo do contato ?</label>
      <input type="text" class="form-control" id="motivoCont" placeholder="Digite aqui o motivo do seu contato">
    </div>     
    <div class="form-group">
      <label for="emailCont" id='labelMot'>Seu Email</label>
      <input type="text" class="form-control" id="emailCont" placeholder="Digite aqui seu Email">
    </div>     
    <div class="form-group">
      <label for="textoCont" id='mensagemCont'>Digite sua mensagem</label>
      <textarea class="form-control" id="textoCont" rows="4"></textarea>
    </div>
    <button id='enviarCont' onclick="envia()">
      Enviar
    </button>
  </form>

I imagined doing something like :

$('#enviarCont').click(function(){

})

and paste inside it the code q is sending the Email... but it does not work...

  • Yes, it does not work, the nodemailer must be configured in the backend(nodejs). You must expose a published route that calls the e-mail sending. (via post) to your backend. So in your click action just call the endpoint with the form data.

  • But when I call at the prompt the Node index.js command (name of the file q ta send) it sends the email normally...

  • I don’t understand what you mean, can you show me ?? I’m caught up in it and it seems to be something so simple

1 answer

1

To create a route in your backend to handle email submissions, you’ll need to create an endpoint to manipulate the sending of your email.

For this we will create the following steps:

  1. Create an endpoint that sends via nodemailer
  2. Calling endpoint in our frontend for the email to be sent

To create our server, we will need to install the libs express to mount the server that will receive the requests and the cors to free the access of our application to our frontend. In addition to the node-mailer

To create the endpoint in the backend we have:

app js.

const express = require('express');
const cors = require('cors');
const app = express();
cors({ credentials: true, origin: true });
app.use(express.json());
app.use(cors());

app.use(require('./server/index'));
module.exports = app;

server/index.js

const nodemailer = require('nodemailer');
const router = require('express').Router();

const transporter = nodemailer.createTransport({
    host: "mail.example.com",
    port: 465,
    secure: true,
    auth: {
        user: '[email protected]',
        pass: '****minhasenhasupersegura****'
    }
});

router.post('/enviaremail', (req, res) => {
    const mailOptions = {
        from: '[email protected]',
        to: req.body.email,
        subject: req.body.assunto,
        text: `Mensagem de: ${req.body.nome}, ${req.body.mensagem}`
    }
    transporter.sendMail(mailOptions).then((trans) => {
        res.status(200).json(trans);
    }).catch((error) => {
        res.status(500).json(error);
    })
});
module.exports = router;

bin/www

#!/usr/bin/env node
const app = require('../app');
try {
    app.listen(process.env.PORT);
    console.log(`Microsservice listening at http://localhost:${process.env.PORT}`);
} catch (err) {
    throw err;
}

After developing this application in the backend, just point the frontend to this route and make the call via ajax. This code would be in the action of clicking your button. The data I am leaving hardcoded in the request, must have come from your html form.

const axios = require('axios');
axios.post('http://localhost:3000/enviaremail', {
    nome: 'aaaa',
    email: '[email protected],
    assunto: 'assunto principal',
    mensagem: 'minha mensagem',
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

There are some settings you should make in order to have security, configure the Cors with some value that makes sense to your environment. And for the values that are hardcoded in my backend, you should utilize environment variables.

Another feature you can implement is to validate the form values (in the frontend) before doing Ubmit and validate in the backend (before sending). Yes it is necessary to validate in frontend and backend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.