Next.jsで、email を送信する例 (メール送信)

4 min read読了の目安(約4000字

概要:

前のnodemailerの関連で、Next.jsでメール送信の内容となります


環境

  • Next.js : 10.0.0
  • node 14
  • npm / nodemailer

前の参考ページ

https://zenn.dev/knaka0209/articles/ac0e552abe1a8b

参考のコード

https://gist.github.com/kuc-arc-f/a951d022cf436d97267e2a577adb0d71

pages/api/send_mail.js

  • next.config.js 等からprocess.env で必要な変数を読込む例です
send_mail.js
"use strict";
const nodemailer = require("nodemailer");

//
export default async (req, res) => {
  try{
    var data = req.body
//console.log( "from=", process.env.SEND_MAIL_ADDRESS)
//console.log( data.title )
    var receiverEmailAddress = data.to_mail
    let transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: process.env.SMTP_PORT,
      secure: process.env.SMTP_SECURE,
      auth: {
        user: process.env.SMTP_AUTH_USER,
        pass: process.env.SMTP_AUTH_PASS,
      },
    });
    let info = await transporter.sendMail({
      from: process.env.SEND_MAIL_ADDRESS,
      to: receiverEmailAddress,
      subject: data.title,
      text: data.content,
    });
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));     
    res.json({})
  } catch (err) {
    console.log(err);
    res.status(500).send();    
  } 
};

  • 送信画面、

pages/mail.js

mail.js
export default class extends React.Component {
  static async getInitialProps(ctx) {
//console.log("BASE_URL=", BASE_URL)
    var url = process.env.BASE_URL + '/api/token_get'
    const res = await fetch(url)
    const json = await res.json()
    return {
      data: "",
      items: [],
      csrf: json.csrf,
    }
  }
  constructor(props){
    super(props)
//console.log(props )
  }
  clickHandler(){
console.log("#clickHandler" )
    this.proc_test()
  }
  async proc_test(){
    try {
      var elemTo = document.getElementById('to_mail_address');
      var elemTitle = document.getElementById('mail_title');
      var elemContent = document.getElementById('mail_content');
      var item = {
        to_mail : elemTo.value,
        title: elemTitle.value,
        content: elemContent.value,
      }
//console.log(item)
      const res = await fetch(process.env.BASE_URL + '/api/send_mail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', },
        body: JSON.stringify(item),
      });
      if (res.status === 200) {
        var json = await res.json()
        alert("Success, send mail")
console.log(json)
//        Router.push('/tasks');
      } else {
        throw new Error(await res.text());
      }
    } catch (error) {
      alert("Error, proc_test")
      console.error(error);
    }    
  }   
  render(){
    return (
    <Layout>
      <div className="body_main_wrap">
        <div className="container">
        <h1>Test - mail send</h1>
        <hr />
        <div className="row">
          <div className="col-sm-9 form-group">
            <label>To mail:</label>
            <input type="text" className="form-control" 
            name="to_mail_address" id="to_mail_address"
            defaultValue="hoge@test.com" />
          </div>
        </div>
        <div className="row">
          <div className="col-sm-6 form-group">
            <label>Title:</label>
            <input type="text" className="form-control"
            name="mail_title" id="mail_title" 
            defaultValue="title-1234"/>
          </div>          
        </div>
        <div className="form-group">
          <label>Mail Body:</label>
          <textarea type="text" name="mail_content" id="mail_content"
            className="form-control" rows="8" 
            defaultValue="mail-body-1234" ></textarea>
        </div>

        <hr />
        <button onClick={this.clickHandler.bind(this)}>Test-Mail
        </button>
        </div>
      </div>
    </Layout>
    )
  }
}


メール送信画面

  • タイトル、本文を記入して。送信します

....