2
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 1 year has passed since last update.

Nodejsでgmailからメールを送信する

Last updated at Posted at 2023-11-08

gmailからメールを送信する方法について記載

Node ver

v14.18.2

1.プロジェクトを作成

GCPにログインして適当なプロジェクトを作成、

2.GmailAPIの有効化

APIのライブラリを開いてGmailAPIを有効化する
https://console.cloud.google.com/apis/library

3.認証情報を作成

認証情報画面を開く
https://console.cloud.google.com/apis/api/gmail.googleapis.com/

「+認証情報を作成」をクリック
「同意画面を設定を クリック」

User Type:外部を選択し、作成ボタンを押す

アプリ登録の編集画面で各情報を入力

スコープを追加または削除から、
「.../auth/gmail.send」を選択し、追加、保存

4.認証情報を作成 OAuth クライアント ID

認証情報を作成、からOAuth クライアント IDを作成する
以下のように選択
アプリケーション:デスクトップアプリ
名前:任意

クライアントを 作成したら、ポップアップ画面左下、
「JSONをダウンロード」からcredencialをダウンロードする、名前をcredentials.jsonにしておく

5.ローカル環境でソースコードを作成

Nodejsに以下のパッケージをインストール

npm install googleapis nodemailer

以下のコードを実行
setSendMail()の箇所は送る内容を書き換えてください。
credentials.jsonは上記で作成したクライアント IDのjson、
token.jsonは認証が通ると生成されます。

const MailComposer = require('nodemailer/lib/mail-composer');
const { Buffer } = require('node:buffer');
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const credentials = require ( "./credentials.json" );
const tokens = require ( "./_token.json" );

const SCOPES = [
    'https://www.googleapis.com/auth/gmail.send'
];

const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

async function loadSavedCredentialsIfExist() {
    try {
        const content = await fs.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
    } catch (err) {
        return null;
    }
}

async function saveCredentials(client) {
    const content = await fs.readFile(CREDENTIALS_PATH);
    const keys = JSON.parse(content);
    const key = keys.installed || keys.web;
    const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
    });
    await fs.writeFile(TOKEN_PATH, payload);
}

async function authorize() {
    let client = await loadSavedCredentialsIfExist();
    if (client) {
        return client;
    }
    client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
    });
    if (client.credentials) {
        await saveCredentials(client);
    }
    return client;
}

async function createMail(subject, to, text){
    const mail = await new MailComposer({
        to,
        text,
        subject,
        textEncoding: "base64",
    }).compile().build()
    const raw = Buffer.from(mail)
        .toString("base64")
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "")
    return raw
}

function setSendMail(auth) {
    const gmail = google.gmail({version: 'v1', auth});
    sendMail(gmail,
        "題名",
        "test_taro@gmail.com",
        "本文")
}

async function sendMail (gmail,subject, to, text){
    const raw = await createMail(subject, to, text)
    await gmail.users.messages.send({
        userId: "me",
        requestBody: {
            raw,
        },
    })
}

authorize().then(setSendMail).catch(console.error);

以上

参考:
https://qiita.com/muuuuuwa/items/822c6cffedb9b3c27e21

2
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
2
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?