nodemailer / smtp-server

Create custom SMTP servers on the fly
Other
862 stars 146 forks source link

Email gets sent but not received #145

Open GinoCH15 opened 4 years ago

GinoCH15 commented 4 years ago
let transporter = nodemailer.createTransport({
  service: 'SendGrid',
  auth: {
    user: process.env.SENDGRID_USER,
    pass: process.env.SENDGRID_PASSWORD
  }
});
exports.postUserCreate = async (req, res) => {
  try {
    if (!validator.isEmail(req.body.email)){
      req.flash('errors', { msg: 'El correo no es válido.' });
      return res.redirect('back');
    }
    req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false });
    if(req.body.password.length<4){
      req.flash('errors', { msg: 'Las contraseñas deben ser al menos de 04 caracteres.' });
      return res.redirect('back');
    }
    if(req.body.password!=req.body.confirmPassword){
      req.flash('errors', { msg: 'Las contraseñas no coinciden.' });
      return res.redirect('back');
    }
    const existingUser = await User.findOne({ email: req.body.email });
    if(existingUser){
      req.flash('errors', { msg: 'Ya existe un usuario con el correo que desea registrar' });
      return res.redirect('back');
    }
    let newUser = new User({
      email : req.body.email,
      password : req.body.password,
      type : req.body.typeuser,
      profile: {
        name: req.body.name,
        lastName: req.body.lastName,
        phone: req.body.phone,
        dni: req.body.dni,
        address: req.body.address,
        picture: req.body.picture
    }
    })
    await newUser.save();
    console.log(`newUser-->${newUser}`)
    const mailOptions = {
      to: newUser.email,
      from: "no-reply@cussto.pe",
      subject: 'Bienvenido a Cussto',
      text: `¡Hola! Acabamos de crear tu cuenta en Cussto \n
      Usuario: ${newUser.email}\n
      Contraseña : ${newUser.password}\n
      Acceso: http://${req.headers.host}/login \n\n` 
    };
    await transporter.sendMail(mailOptions)
      .then(() => {
        console.log(`Mail enviado`);
        console.log(`mailOptions-->${mailOptions.to}`);
        req.flash('success', { msg: 'Usuario creado exitosamente' });
        return res.redirect('/admin/usuarios');
      });
  } catch (err) {
    console.log(err);
    req.flash('errors', { msg: 'Ups! Hubo un error' });
    return res.redirect('back');
  }
}

the output is:

newUser-->{
  profile: {
    name: 'adsa',
    style: 1,
    notch: 1,
    lastName: 'Cerda Hinostroza',
    phone: 997177826,
    dni: '9831231'
  },
  status: 0,
  type: 0,
  isConfirmed: 0,
  tokens: [],
  _id: 5ea9c05e9f5e8854ccb7acbb,
  email: 'williansd555@gmail.com',
  password: '$2a$10$vITVZYJWau6Ate3kW1RScuoqWn2uOGrChxcEPdo1VSW9/WRT3cpd.',
  createdAt: 2020-04-29T17:58:54.285Z,
  updatedAt: 2020-04-29T17:58:54.285Z,
  __v: 0
}
Mail enviado
mailOptions-->williansd555@gmail.com