aws

AWS SES(Amazone Simple Email Service)

C/H 2019. 4. 12. 17:26

AWS SES

SES 설정

code

npm i aws-sdk
npm i express-validator
npm i express
npm i joi
npm i log4js
# mail.validation.js
module.exports = {
  to: {
    exists: true
  },
  cc: {
    exists: false
  },
  bcc: {
    exists: false
  },
  subject: {
    exists: true
  },
  text: {
    exists: true
  }
};
const express = require('express');
const router = express.Router();

const { checkSchema, validationResult } = require('express-validator/check');
const schema = require('./mail.validation');
const logger = require('../../modules/logger');

const AWS = require('aws-sdk');
AWS.config.loadFromPath(__dirname+'/config.json');

const charset = "UTF-8";

var send = function(req, res, next){
  try{
    var ses = new aws.SES(); // Create a new SES object. 
    var params = { // Specify the parameters to pass to the API.
      Source: req.body.form||req.query.from||'INFO <info@domain.com>', 
      Destination: { 
        ToAddresses: [
          req.body.to||req.query.to||null
        ],
      },
      Message: {
        Subject: {
          Data: req.body.subject||req.query.subject||null,
          Charset: charset
        },
        Body: {
          Text: {
            Data: req.body.text||req.query.text||null,
            Charset: charset 
          },
          Html: {
            Data: req.body.html||req.query.html||null,
            Charset: charset
          }
        }
      },
      ConfigurationSetName: 'ConfigSet'
    };

    ses.sendEmail(params, function(err, data) { //Try to send the email.
      if(err) { // If something goes wrong, print an error message.
        var result = {ok:false, params: params, errors: err};
        logger.email.error(result);
        return res.status(422).json(result);
      }

      var result = {ok:false, params: params, data: data};
      logger.mail.info(result);
      return res.status(200).json(result);
    });
  }catch(e){
    var result = {ok:false, params: params, errors:  err.array?err.array():err||null};
    logger.mail.error(result);
    return res.status(422).json(result);
  }
};


router.get('/', checkSchema(schema), send);
router.post('/', checkSchema(schema), send);

module.exports = router;
반응형