首页 > 解决方案 > 如何在 Node 项目中使用 AWS 发送电子邮件

问题描述

我的 Angular 应用程序通过 POST 请求向节点服务器(app.js)发送一些数据,然后在响应中返回请求正文。

我现在正在尝试发送一封电子邮件,其中包含在请求正文中发送的这些数据。

目前,我可以读取一个 HTML 文件来填充电子邮件正文,然后发送电子邮件,但我需要用我的req.body.

这是我到目前为止在app.js中的内容:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.post('/postData', bodyParser.json(), (req, res) => {
    res.json(req.body)
    readFile();
    sendEmail();
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))


var AWS = require('aws-sdk');
const fs = require('fs');
var params;

var htmlFileName = '/Users/myName/Desktop/test.html'
AWS.config.loadFromPath('config-aig.json');
const fromEmail = 'myName';
const toEmail = 'myName'
const subject = 'Test Email' + Date()

function sendEmail() {

    // Create the promise and SES service object
    var sendPromise = new AWS.SES({ apiVersion: '2010-12-01'}).sendEmail(params).promise();

    sendPromise.then(
        function (data) {
            console.log('send email success');
        }).catch(
            function (err) {
                console.error('error --> ', err, err.stack);
            });
}


function readFile(callback) {
    return new Promise(
        function (resolve, reject) {
            fs.readFile(htmlFileName, 'utf8',
                function read(err, data) {
                    if (err) {
                        return reject(err)
                    }
                    else {
                        console.log('file read success');
                        return resolve(data);
                    }
                })
        }
    )
}

readFile()
    .then((res) => {
        // Create sendEmail params 
        params = {
            Destination: { /* required */
                ToAddresses: [
                    toEmail,
                ]
            },
            Message: { /* required */
                Body: { /* required */
                    Html: {
                        Charset: "UTF-8",
                        Data: res
                    }
                },
                Subject: {
                    Charset: 'UTF-8',
                    Data: subject
                }
            },
            Source: fromEmail, /* required */
        }
        sendEmail();
    })
    .catch((err) => {
        console.log('File Read Error : ', err)
    }
    )

有人可以告诉我如何用req.body替换我的htmlFileName吗?

标签: node.js

解决方案


我使用 ejs 来模板我的电子邮件这里是我经常用来发送电子邮件的代码!

如果你有问题我很乐意回答

const ejs = require('ejs');
const AWS = require('aws-sdk');
const mailcomposer = require('mailcomposer');

const config_aws = {
    accessKeyId: '',
    secretAccessKey: '',
    region: 'eu-west-1',
    expeditor: '',
    limitExpeditor: 50
};

AWS.config.update(config_aws);

const ses = new AWS.SES();

async function sendAnEmail(
    expeditor,
    subject,
    destinator,
    body,
    destinator_name = null,
    bcc = null,
    callback
) {
    ejs.renderFile(
        `${__dirname}/templates/template.ejs`,
        {
            destinator,
            destinator_name,
            subject,
            body
        },
        (err, html) => {
            if (err) return console.error(err);
            const sesEmailProps = {
                Source: config_aws.expeditor,
                Destination: {
                    ToAddresses: [`${destinator}`]
                },
                Message: {
                    Body: {
                        Html: {
                            Charset: 'UTF-8',
                            Data: html
                        },
                        Text: {
                            Charset: 'UTF-8',
                            Data: html ? html.replace(/<(?:.|\n)*?>/gm, '') : ''
                        }
                    },
                    Subject: {
                        Charset: 'UTF-8',
                        Data: subject
                    }
                }
            };
            if (bcc) {
                sesEmailProps.Destination = {
                    ToAddresses: [`${destinator}`],
                    BccAddresses: bcc // ARRAY LIMIT OF 49
                };
            }
            ses.sendEmail(sesEmailProps, (error, data) => {
                if (error) console.error(error);
                callback(error, data);
            });
        }
    );
}


推荐阅读