1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nodemailerにて引数の引き渡しをする。

Posted at

 はじめに

申し込みなどがあった場合に、入力された情報をそのまま反映させてメールを送る実装が試したら、
とても詰まったのでここに残します。

設定

申し込み画面から申し込みがあった場合、
自動的に申込み者と、管理者に入力情報が記載されたメールを送る。

開発環境

  • Node.js 11.15.0

使ったライブラリ

  • nodemailer

  • mutache
    htmlなど静的ページに変数を引き渡せるライブラリ。
    jQueryなどで利用するみたい。

  • fs
    node.jsお馴染みのファイル関連ライブリ。
    HTMLの読み込みに利用しました。

  • dotenv
    今回の主題では無いですが、パスワードを環境変数で管理するために
    利用しています。

使ったメールツール

  • outlook
const nodemailer = require('nodemailer');
const dotenv = require('dotenv');
const Mustache = require('mustache');
const fs = require('fs');

dotenv.config({ path: '.env' })

// メールのセキュリティ設定。
// 送信に利用するメールの情報を記載。

const transporter = nodemailer.createTransport({
  host: 'smtp-mail.outlook.com',
  port: 587,
  tls: {
    ciphers: 'SSLv3',
  },
  auth: {
    user: 'hoge@sample.jp',
    pass: process.env.EMAIL_PASS,
  },
});

const readFileContent = (file) => {
  return new Promise((resolve, reject) => {
    fs.readFile(
      file,
      {
        encoding: 'utf8',
      },
      (error, data) => {
        if (error !== null) {
          reject(error);
          return;
        }
        resolve(data);
      },
    );
  });
};

const applicationEmail = async (number, name) => {
  const template = await 
// PATHは相対ではなく絶対パス。JSでは無いため。
// promise を利用しているのでasync/awaitが必要。
handleFile.readFileContent('./email/hello.html');
 //公式のより簡略させる書き方。
  Mustache.parse(template);
  const noticeData = {
    number,
    name,
  };
  const renderApplicationEmail = Mustache.render(template, noticeData);
  //スコープ外で値を引き渡す用
  return renderApplicationEmail;
};

const noticeEmail = async (number, name, eMail) => {
  const template = await handleFile.readFileContent('./email/notice.html');
  Mustache.parse(template);
  const applicationData = {
    number,
    name,
    eMail,
  };
  const renderNoticeEmail = Mustache.render(template, applicationData);
  return renderNoticeEmail;
};

// メールを送信する関数
const sendCompletionMail = async (number, name, eMail) => {
  try {
    const applicationCompleted = await applicationEmail(number, name);
    transporter.sendMail({
      from: 'hoge@sample.jp',
      to: eMail,
      subject: 'お申し込みありがとうございます。',
      html: applicationCompleted,
    });
    const noticeApplication = await noticeEmail(serialNumber, companyName, familyName, eMail, telephone);
    transporter.sendMail({
      from: 'hoge@sample.jp',
      to: 'poke@sample.jp',
      subject: '申込通知。',
      html: noticeApplication,
    });
    console.log('send successful');
  } catch (error) {
    console.log('Error', error);
  }
};


  sendCompletionMail();



hello.html

<!DOCTYPE HTML>
<html>
<body>
  <p>
    Dear {{name}},
  </p>
  <p>
    Thank you for purchasing our product.
  </p>
</body>
</html>

notice.html

<!DOCTYPE HTML>
<html>
<body>
  <p>
     {{name}} applied.
  </p>
  <p>
    Take contact to {{email}}
  </p>
</body>
</html>

わざわざ
applicationEmail()という関数を作らなくとも、
sendCompletionMail内に書き込み、
html: renderApplicationEmail
にしても良いですが、複数定義の場合は可読性を優先して書きました。

 参考

 参考

https://nodemailer.com/message/
https://github.com/janl/mustache.js/
https://nodejs.org/api/fs.html

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?