m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

nodejsでメール送信(nodemailer)

nodejsでメール送信

今回はlocalhostからリレーで使用するため、localhostで行う。設定ではSMTPでユーザー、パスワードも指定できるがテストなので一番簡単なやつで対応

モジュールインストール

[root@localhost ~]# cd /var/www/tools/node1/
[root@localhost node1]# npm install nodemailer
nodemailer@0.6.0 node_modules/nodemailer
tqq public-address@0.1.0
tqq directmail@0.1.6
tqq he@0.3.6
tqq simplesmtp@0.3.20 (xoauth2@0.1.8, rai@0.1.9)
tqq mailcomposer@0.2.8 (dkim-signer@0.1.0, mime@1.2.9, punycode@1.2.3, follow-redirects@0.0.3, mimelib@0.2.14)
mqq readable-stream@1.1.10 (core-util-is@1.0.1, debuglog@0.0.2, string_decoder@0.10.25)
[root@localhost node1]#

実装

mail_sample.js
// モジュールをロード
var nodemailer = require("nodemailer");

// サーバの設定
var transport = nodemailer.createTransport('SMTP', {
    host: "localhost",
    port: 25
});

// メール情報の作成
var message = {
    from: '送信元のメールアドレス',
    to: '送信先のメールアドレス',
    subject: 'テストメールタイトル',
    text: "本文のメールサンプル"
};

// メール送信
var mail;
try{
    mail = transport.sendMail(message, function(error, success){
        if(error){
            console.log(error);
            return;
        }
        if(success){
            console.log("success sned ok");
        }else{
            console.log("success sned ng");
        }
        //console.log(mail);
        console.log(message);
        message.transport.close();
        return;
    });

}catch(e){
    console.log(e);

}

まとめ

ファイル添付やHTML送信も可能。ただ、サーバからのHTML送信はセキュリティ面でなんか問題になりそうなので対応は必要に応じて考える。