如何在Node项目中使用AWS发送电子邮件

时间:2019-04-24 09:27:56

标签: node.js

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

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

当前,我可以读取HTML文件以填充电子邮件正文,然后发送电子邮件,但是我需要用req.body中发送的数据替换该HTML文件。

这是我到目前为止在 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 吗?

1 个答案:

答案 0 :(得分:0)

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

如果您有任何疑问,我很乐意回答

import edu.princeton.cs.algs4.Queue;

public class QuickSort {

    /**
     * Returns a new queue that contains the given queues catenated together.
     * <p>
     * The items in q2 will be catenated after all of the items in q1.
     *
     * @param q1 A Queue of items
     * @param q2 A Queue of items
     * @return A Queue containing the items of
     * q1 followed by the items of q2.
     */
    private static <Item extends Comparable> Queue<Item> catenate(Queue<Item> q1, Queue<Item> q2) {
        Queue<Item> catenated = new Queue<Item>();
        for (Item item : q1) {
            catenated.enqueue(item);
        }
        for (Item item : q2) {
            catenated.enqueue(item);
        }
        return catenated;
    }

    /**
     * Returns a random item from the given queue.
     *
     * @param items A Queue of items
     * @return A random item from items
     */
    private static <Item extends Comparable> Item getRandomItem(Queue<Item> items) {
        int pivotIndex = (int) (Math.random() * items.size());
        Item pivot = null;
        // Walk through the queue to find the item at the given index.
        for (Item item : items) {
            if (pivotIndex == 0) {
                pivot = item;
                break;
            }
            pivotIndex--;
        }
        return pivot;
    }

    /**
     * Partitions the given unsorted queue by pivoting on the given item.
     *
     * @param unsorted A Queue of unsorted items
     * @param pivot    The item to pivot on
     * @param less     An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are less than the given pivot.
     * @param equal    An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are equal to the given pivot.
     * @param greater  An empty Queue. When the function completes, this queue will contain
     *                 all of the items in unsorted that are greater than the given pivot.
     */
    private static <Item extends Comparable> void partition(
            Queue<Item> unsorted, Item pivot,
            Queue<Item> less, Queue<Item> equal, Queue<Item> greater) {
        Queue<Item> out = unsorted;

        while(!unsorted.isEmpty()){
            Item t = out.dequeue();
            if (t.compareTo(pivot) > 0){
                greater.enqueue(t);
            }else if(t.compareTo(pivot) == 0){
                equal.enqueue(t);
            }else less.enqueue(t);
        }
        quickSort(less);
        quickSort(greater);
       out = catenate(catenate(less,equal), greater);
    }





    /**
     * Returns a Queue that contains the given items sorted from least to greatest.
     *
     * @param items  A Queue of possibly unsorted items
     * @return       A Queue of sorted items
     */
    public static <Item extends Comparable> Queue<Item> quickSort(
            Queue<Item> items) {
        if (items.size() <= 1){
            return items;
        }
       Item ran = getRandomItem(items);
        Queue<Item> less = new Queue<>();
        Queue<Item> more = new Queue<>();
        Queue<Item> equal = new Queue<>();
        partition(items, ran, less, equal, more);
        return items;
    }

    public static void main(String[] args){
        Queue<Integer> non = new Queue<>();
        non.enqueue(108);
        non.enqueue(180);
        non.enqueue(10);
        non.enqueue(810);

        non = quickSort(non);
        System.out.println(non.toString());
    }
}