1
1

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 3 years have passed since last update.

laravel sendgrid メール送信 ファイル添付、テンプレートも

Last updated at Posted at 2022-02-01

インスコ

composer require "sendgrid/sendgrid"

apikey取得

① sendgrid にログイン
② 左側メニュー Settings > API Keys > Create API Key
③ .env に記載

SENDGRID_API_KEY=SG.youryour

① 送信するだけ

HogesController.php
use SendGrid;
use SendGrid\Mail\Mail;
use \Symfony\Component\HttpFoundation\Response;

class HogesController extends Controller
{
    public static function test(request $request)
    {
        $email = new Mail();
        $email->setFrom('from@from.com', '送信元名');
        $email->setSubject("メールのタイトル");
        $email->addTo("to@to.com");
        $email->addContent("text/plain", "これがコンテンツです");
        
        $sendgrid = new SendGrid(env('SENDGRID_API_KEY'));
        $response = $sendgrid->send($email);
        if ($response->statusCode() == Response::HTTP_ACCEPTED) {
            print_r("送信 できました");
        } else {
            print_r("送信 NG");
        }
    }

}

OK

② ファイルを添付

HogesController.php
    $path = public_path("img/gal.jpg");
    $file_encoded = base64_encode(file_get_contents($path));
    $email->addAttachment(
        $file_encoded,
        mime_content_type($path),//image/jpeg
        "gal.jpg",//送信されるファイル名
        "attachment"//固定
    );

OK

③ テンプレートを利用

HogesController.php
    $data = [
        "hoge" => 'ほげ',
        "name" => 'たろう'
    ];

    $email->addContent(
        "text/plain",// "text/html"//plain にしないとblade.phpの改行が有効ならない
        strval(
            view(
                'emails/test',//view/emails/test.blade.php
                compact('data')
            )
        )
    );
/view/emails/test.blade.php
テストメールテンプレート
変数{{ $data['hoge'] }}も{{ $data['name'] }}も渡せます

OK

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?