LoginSignup
22
20

More than 5 years have passed since last update.

node.js の nodemailer/mailer モジュールで、SMTP認証無しでメールを送る

Last updated at Posted at 2017-08-28

node.js で構築したシステムで、社内のSMTPサーバからメールを送ることになりました。

  • 社内ネットワーク内のSMTPサーバを使用
  • メール送信先も、社内ユーザのみ
  • SMTPサーバは認証無しで送信可能(Port:25)

モジュールはnodemailerを使うことにしたのですが、検索しても出てくるのはgmailやSendGridでの送信例ばかりで、どこも認証ありでの送信例です。
このシンプルな条件での送信設定が意外なほど見つからなかったので、送信サンプルを公開しておきます。

送信例(nodemailer)

以下のコードで送信できました。
弊社環境では、9行目のtls.rejectUnauthorizedの設定が無いとエラーになりました。

mailtest.js
// nodemailerによるメール送信
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
    host: '<メールサーバ>',
    port: 25, // ポート
    use_authentication: false, // 認証しない
    tls: {
        rejectUnauthorized: false // do not fail on invalid certs
    }
});

var mailOptions = {
    from: '<送信元アドレス>',
    to: '<送信先アドレス>',
    subject: 'TEST from nodemailer',
    text: 'TEST MAIL BODY',
};

transporter.sendMail( mailOptions, function( error, info ){
    if( error ){
        return console.log( error );
    } else {
        console.log('Message sent: ' + info.response);
    }
});

送信結果です。

$ node -v
v7.10.0
$ npm ls nodemailer
/home/nakatsu
├─┬ mailer@0.6.7
│ └── nodemailer@0.1.20
└── nodemailer@4.0.1 ### 注:こちらです
$ node mailtest.js
Message sent: 250 ok:  Message 236076747 accepted

送信例(mailer)

よりシンプルなモジュールのmailerでも送信できました。

mailtest.js
// mailerによるメール送信
var email = require('mailer');

email.send({
    ssl: false,
    host : "<メールサーバ>",    // smtp server hostname
    port : "25",               // smtp server port
    domain : "visionarts.com", // domain used by client to identify itself to server
    from: '<送信元アドレス>',
    to: '<送信先アドレス>',
    subject : "TEST from mailer",
    body: 'TEST MAIL BODY',
},
function(err, result){
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});

送信結果です。

$ node -v
v7.10.0
$ npm ls nodemailer
/home/nakatsu
├─┬ mailer@0.6.7 ### 注:こちらです
│ └── nodemailer@0.1.20
└── nodemailer@4.0.1
$ node mailtest.js
True

ただし、こちらのmailerモジュールでは、デフォルトのエンコードがquoted-printableになっています。
UTF-8で長い日本語のメールを送った際に希に文字化けする現象が見られたので、今回はnodemailerを採用しました。
(設定に"encoding"を追加すればいいはずなのですが、"base64"を指定しても正しくエンコードされなかったのでそこは未調査です。)

22
20
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
22
20