使用 nodemailer 发送邮件

sending mail with nodemailer

每当我 运行 代码时,我都会收到错误消息“错误:从未在 SMTPConnection._formatError 收到问候语......”

function automatedMailSender(req,res){

var mailOptions = {
    from: "abc <abc@test.com>", // sender address
    to: 'nit@test.com', // list of receivers
    subject: 'Hello ', // Subject line
    text: 'Hello world ?', // plain text body
    html: '<b>Hello world ?</b>' // html body
 };


var mailer=nodemailer.createTransport({
    host: 'mail.test.com',
    port: 465,
    secure: false, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'mymail@test.com',
        pass: '1234'
    }
});

mailer.sendMail(mailOptions, (error, response)=>{
    if(error){
        console.log('mail not sent \n',error);
    }
    else{
        console.log("Message sent: " ,response.message);
    }   
 });
}

我在代码中做错了什么。

尝试类似的方法,它非常适合我:

//Create reusable transporter object using the default SMTP transport 
var transporter = nodemailer.createTransport(
'smtps://USERNAME%40gmail.com:PASSWORD@smtp.gmail.com');

// setup e-mail data 
var mailOptions = {
        from: '"Michel " <recipe@example.com>', // sender address 
        to: 'bernard@example.com', // list of receivers 
        subject: 'Hello', // Subject line 
        text: 'Bonjour!' // plaintext body 
      };

// send mail with defined transport object

transporter.sendMail(mailOptions, function(error, info){
      if(error){
        return console.log(error);
      }
      console.log('Message sent: ' + info.response);
});

如果还是不行你有一个小教程here

如果您使用 Gmail 发送邮件,请试试这个。

Allow less secure apps to connect to Gmail.

tls:{
        rejectUnauthorized:false
    }

通过在 mailer 变量中使用上述代码修复了它。 谢谢大家

答案就在你的代码中

port: 465,
secure: false, // secure:true for port 465, secure:false for port 587

"secure" 的值对于端口 465 应该是正确的

这是由于未经授权用户的 SMTP 安全性,因此要解决此问题,您需要设置 rejectUnauthorized:false

希望对您有所帮助。

var mailer=nodemailer.createTransport({
    host: 'mail.test.com',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    transportMethod: 'SMTP',
    auth: {
        user: 'mymail@test.com',
        pass: '1234'
    }
});

secure 的值对于端口 465 应为真并使用 transportMethod: 'SMTP'

const express = require('express');
const router = express.Router();
const { Email } = require('../models/email.model');
const { User } = require('../models/user.model');
const nodemailer = require('nodemailer');




//post email 
router.post('/send', async (req, res) => {

    if (req.query) {
        var query = {}
        if (req.query.lastname) { query.lastname = req.query.lastname }
        if (req.query.firstname) { query.firstname = req.query.firstname }
        if (req.query.email) { query.email = req.query.email }
        if (req.query.isactive) { query.isActive = req.query.isactive }
        if (req.query.isgain) { query.isGain = req.query.isgain }
    }

    const email = new Email({
        title: req.body.title,
        subject: req.body.subject,
        text: req.body.context,
        description: req.body.description
    });



    if (req.body.title && req.body.subject && req.body.context) {

        const user_db = await User.find(query)
        const user_db_email = user_db.map(x => x.email)

        var smtpTransport = nodemailer.createTransport({
            host: 'smtp.gmail.com',
            port: 465,
            secure: true,
            auth: { user: 'ghiles@gmail.com', pass: 'g' },
            tls: { rejectUnauthorized: false }, // do not fail on invalid certs 
        });

        var mailOptions = {
            to: user_db_email,
            from: 'fatb@gmail.com',
            subject: req.body.subject,
            text: req.body.context
        };

        email.save().then(() => {

            smtpTransport.sendMail(mailOptions)
                .then(() =>  res.status(200).json(email))
                .catch(() => res.status(500).json({ success: false, message: `erreur dans l'envoi de mail` }))

        }).catch(() => res.status(200).json({  success: false, message: `erreur dans le serveur` }))

    } else {
        res.status(400).json({ success: false, message: `Veuillez renseigner le titre et l'objet et le contexte du mail` })
    }





module.exports = router; 
host: 'smtp.host.com',
port: 587,     // 587 or 25 or 2525
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
    user: 'mymail@test.com',
    pass: '1234'
}

试试这个。为 smtp 添加前缀并更改端口。