Sending e-mail through Nodejs

Asked

Viewed 902 times

1

I am beginner learning Node.js and I am caught in a question of sending email on the site as if it were that ''contact us'' using Node.js

The point is, I can send the email, but it only sends when the page gives error and does not update. Displays the message on the screen "Cannot POST /index''

But if I get this problem to direct to the page itself (in this case, index), it does not send the email, I can not understand, could help me?

The way I’ll put in the example it sends the email, but returns a page with the error reported ("Cannot POST /index"), but if I fix this by putting in the server.js:

app.use('/index', require('./routes/index'));

Email is not sent. And if I take action or leave action = /' in Html, it returns the right page, but does not send the email either.

Note: I am using express

server.js

const nodemailer = require('nodemailer');
var enviar = function(req, res, next) {
var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: '123'
    }
});
var mailOptions = {
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Nome: ' + req.body.nome + ' / Telefone: ' + req.body.telefone,
    text: req.body.mensagem
};
transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});
next();
};
app.use(enviar);
index.html

<form method="POST" action="/index">
    <div class="image fit">
        <h3>Nos envie uma mensagem!</h3>
        <textarea name="mensagem"></textarea>
    </div>
    Nome: <input type="text" name="nome" />
    <br>
    Telefone: <input type="text" name="telefone" />
    <br>
    <footer>
        <button class="button special" onclick="enviar()">Enviar</button>
    </footer>
</form>

1 answer

2

This "Cannot POST /index" error message is because the index route should not be accepting access by the POST method

Here is an example of a route that receives a form post:

let express = require("express"),
  path = require('path'),
  nodeMailer = require('nodemailer'),
  bodyParser = require('body-parser');

let app = express();

app.use(express.static('src'));

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/send-email', function (req, res) {
  let transporter = nodeMailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
          user: '[email protected]',
          pass: 'test'
      }
  });
  let mailOptions = {
      // should be replaced with real recipient's account
      to: '[email protected]',
      subject: 'Assunto do email',
      body: req.body.mensagem
  };
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message %s sent: %s', info.messageId, info.response);
  });
  //Redirecionar
  res.writeHead(301, { Location: 'index.html' });
  res.end();
});

let server = app.listen(8081, function(){
    let port = server.address().port;
    console.log("Server started at http://localhost:%s", port);
});

The fields of your form you can pick up with req.body. You can change this example with your connection settings.

In this case, the form would be as follows::

<form method="POST" action="/send-email">
    <div class="image fit">
        <h3>Nos envie uma mensagem!</h3>
        <textarea name="mensagem"></textarea>
    </div>
    <footer>
        <input type="submit" value="Envoar">
    </footer>
</form>

Browser other questions tagged

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