Nodemailer SMTP在生产服务器上不起作用

时间:2019-05-23 11:48:50

标签: node.js smtp nodemailer dotenv

我在生产时通过nodemailer-SMTP(从另一个主机)发送电子邮件时遇到问题

我将我的API上传到了服务器(Scaleway Dev)上,我正在使用Ubuntu Bionic,并且在测试时发现它没有发送电子邮件(我需要验证用户身份)。

起初,我以为请求没有到达服务器,但是当我尝试登录时,收到“确认密码”响应,我检查了mongoDB数据库,并且用户在那里,但仍然没有确认电子邮件。

我尝试在localhost上检查它,认为它可能是dotenv依赖项,但它在那里工作,有什么用?

我服务器上的

节点版本为 8.10.0 在我的个人计算机上 11.12.0

这些是我的依赖项

    enter code here
    "dependencies": {

    "bcrypt": "^3.0.6",
    "body-parse": "^0.1.0",
    "client-sessions": "^0.8.0",
    "connect": "^3.6.6",
    "cookie-parser": "~1.4.4",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^8.0.0",
    "express": "~4.16.1",
    "express-session": "^1.16.1",
    "express-validator": "^5.3.1",
    "http-errors": "~1.6.3",
    "moment": "^2.24.0",
    "mongoose": "^5.5.8",
    "morgan": "~1.9.1",
    "nodemailer": "^6.1.1",
    "nodemon": "^1.19.0",
    "passport": "^0.4.0",
    "pug": "2.0.0-beta11",
    "randomstring": "^1.1.5",
    "session": "^0.1.0",
    "session-mongoose": "^0.5.2"
}

这些选项由我使用的主机指定

//this is my transporter constant

    const transporter   = nodemailer.createTransport({
    host: '*different host from the server*',
    port: 465,
    secure: true,
    auth: {
        user: my used email(hardcoded),
        pass: process.env.EMAILPASS
    },
    tls: {
        rejectUnauthorized: false
    }
});

//my email options

    let mailOptions ={
                from: '"Company Name <noreply@*different host DNS*>',
                to: req.body.email,
                subject: *subject*
                html: `Email Content with confirmation token`
            }

//emailing the message itself

    transporter.sendMail(mailOptions, (err, info) => {
                if(err){
                    return console.log(err);
                }
                console.log("message sent");
            });

我正在使用此电子邮件生成器(https://generator.email/)处理快速丢弃的电子邮件。保存用户后,邮件开始发送。

我对应该怎么办感到困惑...感谢所有帮助

1 个答案:

答案 0 :(得分:0)

过去我在使用nodemailer时遇到问题。我正在使用mailgun(https://www.mailgun.com/)发送电子邮件。他们每月免费提供10,000封电子邮件。这是与mailgun配合使用的代码:

依赖性:

"express": "4.16.4",
"config": "3.0.1",
"nodemailer": "5.1.1",
"nodemailer-mailgun-transport": "1.4.0"

代码(它包装在快速路由器中):

const config = require('config');
const nodemailer = require('nodemailer');
const mg = require('nodemailer-mailgun-transport');
const express = require('express');
const router = express.Router();

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

    //the data has to be an array. It will send as many emails as the number of items in the array
    var emailsList = ["test@test.com"];
    emailsList[0].name = "Test Name";

    var auth = {
        auth: {
            api_key: config.get('mailgunApiKey'),
            domain: config.get('mailgunDomain')
        }
    };

    transporter = nodemailer.createTransport(mg(auth)),
    EmailTemplate = require('email-templates').EmailTemplate,
    path = require('path'),
    Promise = require('bluebird');

    function sendEmail (obj) {
        return transporter.sendMail(obj);
    }

    function loadTemplate (templateName, contexts) {
        let template = new EmailTemplate(path.join(__dirname, '../templates', templateName));
        return Promise.all(contexts.map((context) => {
            return new Promise((resolve, reject) => {
                template.render(context, (err, result) => {
                    if (err) reject(err);
                    else resolve({
                        email: result,
                        context,
                    });
                });
            });
        }));
    }

    loadTemplate('dailyReferralEmail', emailsList).then((results) => {
        return Promise.all(results.map((result) => {
            sendEmail({
                to: result.context.email,
                from: 'Your Name <your-email@test.com>',
                'h:Reply-To': 'your-email@test.com',
                subject: result.email.subject,
                html: result.email.html,
                text: result.email.text,
            });
        }));
    }).then(() => {

        var response = {
            text: "Email sent"
        }
        JSON.stringify(response);
        res.status(200).send(response);
    });
});

module.exports = router; 

作为模板生成器,我正在使用HBS。因此,您必须在项目的根文件夹中有一个模板文件夹,并带有以下树:

enter image description here

您可以通过{{}}在电子邮件中使用变量。

在html.hbs内部:

<p>Hello {{name}}</p>

内部subject.hbs

Subject of your email

内部text.hbs

Preview text of your email

希望这会有所帮助!