Nodemailer を使って Gmail からメールを送信する方法

2024-06-30

Nodemailer を使用した Gmail と Node.js のプログラミング

Nodemailer は、Node.js で電子メールを送信するためのライブラリです。Gmail を含む様々な SMTP サーバーと互換性があり、シンプルなメール送信から高度な機能まで、様々なユースケースに対応できます。

前提知識

このチュートリアルを理解するには、以下の知識が必要です。

  • JavaScript
  • Node.js
  • 基本的な Node.js パッケージのインストール方法

Gmail の準備

    Nodemailer のインストール

    npm install nodemailer
    

    基本的なメール送信

    以下のコードは、Nodemailer を使用して Gmail からシンプルなメールを送信する方法を示しています。

    const nodemailer = require('nodemailer');
    
    // 送信元のメール情報
    const transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 587,
      secure: true,
      auth: {
        user: '[email protected]',
        pass: 'your_app_password'
      }
    });
    
    // メール本文
    const mailOptions = {
      from: '"Your Name" <[email protected]>',
      to: '[email protected]',
      subject: 'Subject of your email',
      text: 'This is the text of your email.'
    };
    
    // メール送信
    transporter.sendMail(mailOptions, (err, info) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log('Message sent:', info.messageId);
    });
    

    補足

    • transporter.sendMail() は非同期処理なので、コールバック関数を渡します。
    • mailOptions オブジェクトには、送信元、宛先、件名、本文などのメール情報が含まれます。

    応用例

    • テンプレートを使用したメール送信
    • 添付ファイル付きのメール送信
    • HTML 形式のメール送信
    • エラー処理と再試行

      このチュートリアルは、Nodemailer を使用して Gmail からメールを送信するための基本的な概要を提供しています。より複雑なユースケースについては、Nodemailer のドキュメントとその他のオンラインリソースを参照してください。




      Nodemailer を使用した Gmail 送信のサンプルコード

      const nodemailer = require('nodemailer');
      
      // 送信元のメール情報
      const transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 587,
        secure: true,
        auth: {
          user: '[email protected]', // 実際に使用する Gmail アドレスに置き換えてください
          pass: 'your_app_password' // 生成したアプリパスワードに置き換えてください
        }
      });
      
      // メール本文
      const mailOptions = {
        from: '"Your Name" <[email protected]>', // 送信者名とメールアドレスを記述
        to: '[email protected]', // 宛先メールアドレスを記述
        subject: '件名', // メール件名を記述
        text: '本文' // メール本文を記述
      };
      
      // メール送信
      transporter.sendMail(mailOptions, (err, info) => {
        if (err) {
          console.log(err);
          return;
        }
        console.log('Message sent:', info.messageId);
      });
      

      説明

      1. require('nodemailer'): Nodemailer ライブラリをインポートします。
      2. transporter の作成:
        • host: SMTP サーバーのホスト名 (Gmail の場合は smtp.gmail.com)
        • port: SMTP サーバーのポート番号 (Gmail の場合は 587)
        • secure: TLS/SSL を使用するかどうか (Gmail の場合は true)
        • auth: 認証情報
          • user: Gmail アドレス
          • pass: アプリパスワード
      3. mailOptions の作成:
        • from: 送信者名とメールアドレス
        • to: 宛先メールアドレス
        • subject: メール件名
        • text: メール本文 (HTML 形式の場合は html プロパティを使用)
      4. transporter.sendMail(): 作成したメールオプションを使用してメールを送信します。
        • エラーが発生した場合は err に内容が格納されます。
        • 正常に送信された場合は info.messageId にメッセージ ID が格納されます。

      実行方法

      1. 必要なライブラリをインストールします。
      npm install nodemailer
      
      1. 上記のサンプルコードを index.js などのファイルに保存します。
      2. [email protected]your_app_password を実際の情報に置き換えます。
      3. 以下のコマンドを実行してコードを実行します。
      node index.js
      
      • このコードは、Gmail アカウントで 2 段階認証を有効にして、アプリパスワードを作成していることを前提としています。
      • テンプレートを使用したメール送信、添付ファイル付きのメール送信、HTML 形式のメール送信など、より高度な機能を実装することもできます。



        Nodemailer を使用した Gmail 送信のその他の方法

        メールテンプレートを使用すると、メール本文を動的に生成することができます。これにより、毎回同じ内容のメールを作成する時間を節約できます。

        const nodemailer = require('nodemailer');
        const pug = require('pug'); // テンプレートエンジン
        
        // 送信元のメール情報
        const transporter = nodemailer.createTransport({
          host: 'smtp.gmail.com',
          port: 587,
          secure: true,
          auth: {
            user: '[email protected]',
            pass: 'your_app_password'
          }
        });
        
        // テンプレートファイルを読み込む
        const template = pug.compile('./template.pug');
        
        // メール本文を生成
        const html = template({
          name: 'John Doe',
          order: 12345,
          total: 50.00
        });
        
        // メール送信
        const mailOptions = {
          from: '"Your Name" <[email protected]>',
          to: '[email protected]',
          subject: 'Order confirmation',
          html: html
        };
        
        transporter.sendMail(mailOptions, (err, info) => {
          if (err) {
            console.log(err);
            return;
          }
          console.log('Message sent:', info.messageId);
        });
        

        メールに添付ファイルを送信することもできます。

        const nodemailer = require('nodemailer');
        
        // 送信元のメール情報
        const transporter = nodemailer.createTransport({
          host: 'smtp.gmail.com',
          port: 587,
          secure: true,
          auth: {
            user: '[email protected]',
            pass: 'your_app_password'
          }
        });
        
        // メール本文
        const mailOptions = {
          from: '"Your Name" <[email protected]>',
          to: '[email protected]',
          subject: 'Document attachment',
          text: 'This is the text of your email.',
          attachments: [
            {
              filename: 'document.pdf',
              path: '/path/to/document.pdf'
            }
          ]
        };
        
        // メール送信
        transporter.sendMail(mailOptions, (err, info) => {
          if (err) {
            console.log(err);
            return;
          }
          console.log('Message sent:', info.messageId);
        });
        

        HTML 形式のメールを送信すると、よりリッチなメールを作成することができます。

        const nodemailer = require('nodemailer');
        
        // 送信元のメール情報
        const transporter = nodemailer.createTransport({
          host: 'smtp.gmail.com',
          port: 587,
          secure: true,
          auth: {
            user: '[email protected]',
            pass: 'your_app_password'
          }
        });
        
        // メール本文
        const mailOptions = {
          from: '"Your Name" <[email protected]>',
          to: '[email protected]',
          subject: 'Welcome email',
          html: `
            <h1>Welcome to our website!</h1>
            <p>Thank you for signing up for our newsletter.</p>
            <p>Click here to <a href="https://example.com">confirm your email address</a>.</p>
          `
        };
        
        // メール送信
        transporter.sendMail(mailOptions, (err, info) => {
          if (err) {
            console.log(err);
            return;
          }
          console.log('Message sent:', info.messageId);
        });
        

        メール送信中にエラーが発生した場合、エラーを処理し、再試行することができます。

        const nodemailer = require('nodemailer');
        
        // 送信元のメール情報
        const transporter = nodemailer.createTransport({
          host: 'smtp.gmail.com',
          port: 587,
          secure: true,
          auth: {
            user: '[email protected]',
            pass: 'your_app_password'
          
        

        javascript node.js nodemailer


        jQuery slideUp().remove() 問題:アニメーションが表示されない?その原因と解決方法

        slideUp().remove() を使用すると、要素が削除される前にスライドアップアニメーションが表示されない場合があります。原因:slideUp() はアニメーション完了後にコールバック関数を呼び出すことができますが、remove() は即座に実行されます。そのため、アニメーション完了前に remove() が実行されてしまうと、アニメーションが表示されない問題が発生します。...


        JavaScriptでCSSを動的に追加する方法を徹底解説!初心者でも安心のサンプルコード付き

        styleプロパティを使用するこれは、最も簡単で基本的な方法です。対象要素の style プロパティに、直接CSSプロパティと値を記述することで、スタイルを適用します。className を使用するあらかじめCSSで定義しておいたクラスを、JavaScript で要素に付与することで、スタイルを適用します。...


        includes vs some vs find vs indexOf vs forEach:どれを使うべき?

        includes() メソッドは、配列が指定した要素を含んでいるかどうかを判定します。最も簡潔で分かりやすい方法です。some() メソッドは、配列の要素全てに条件関数を適用し、その結果に真偽値を返します。find() メソッドは、条件に合致する最初の要素を返します。...


        プラットフォームを超えてファイルを扱う:Node.jsで実現するホームディレクトリ操作

        ファイルシステムは、コンピューターのストレージデバイス上のファイルを整理する仕組みです。各ファイルには、その場所を示す一意のパスがあります。ホームディレクトリは、ユーザーの個人ファイルが保存される特別なディレクトリです。プラットフォーム非依存とは、プログラムがどのオペレーティングシステムで実行されても、同じように動作することを意味します。これは、さまざまなオペレーティングシステム間で異なるファイルシステム構造を処理できる必要がある場合に重要です。...


        npmでインストールしたパッケージを綺麗に整理!node_modulesフォルダのクリーンアップ

        このような不要なパッケージは、ディスク容量を占有するだけでなく、プロジェクトのビルドや動作速度を遅くする原因にもなります。そこで、今回は node_modules フォルダをクリーンアップする方法について解説します。npm prune コマンドは、package...


        SQL SQL SQL SQL Amazon で見る



        【2024年最新版】npm install vs. update: Node.js 開発で迷ったらコレ!

        この解説では、npm install と npm update という 2 つの重要なコマンドの違いについて、分かりやすく説明します。npm install は、プロジェクトに必要なパッケージをインストールするコマンドです。パッケージは npm レジストリからダウンロードされます。