0
0

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.

【Laravel】AWS SESを使ってメールを送信

Last updated at Posted at 2024-04-21

環境

・Laravel10
・Windows11

ドキュメント

SES準備

SESを利用するため、IDを作成。
※今回はメールアドレス使用。

image.png

SESドライバのインストール

SESドライバを使用するために、Amazon AWS SDK for PHPをインストール。

composer require aws/aws-sdk-php

環境設定

.env
MAIL_MAILER=ses
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="送信元のメールアドレス"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=アクセスキー
AWS_SECRET_ACCESS_KEY=シークレットアクセスキー
AWS_DEFAULT_REGION=ap-northeast-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

Mailable作成

メール送信機能を簡単に実装するためのMailableクラスを生成。

php artisan make:mail MailTest

app/Mail配下にファイルが生成される。

実装

MailTest.php
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class MailableObject extends Mailable
{
    private $email;
    /**
     * Create a new message instance.
     */
    public function __construct($email)
    {
        // コントローラーやバッジから受け取る値
        $this->email = $email;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            to: $email,
            subject: 'メール送信テスト'
        );
    }

        public function content()
    {
        return new Content(
            // メール文のテンプレで使うviewファイル
            markdown: 'emails.test_content'
        );
    }
}

view作成

Mailableで指定したemails.test_contentを作成。
※今回はマークダウン形式
image.png

emails/test_content.PHP
# Test email

### Thank you very much for visiting our office yesterday.

メール送信処理

コントローラーやバッジに記述。
※今回はリスナに記述。

これでMailableObjectが呼び出され、メールが送信される

Mail::to('送信先メールアドレス')->send(new MailableObject('Mailableのコンストラクタに渡す値'));

参考記事

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?