sendgrid-phpで添付画像を付けてメール送信する方法
phpでメール送信する方法の一つとしてSendGridがあります。
添付ファイルを付けてメール送信する方法についてのメモです。
※ 前提として、composerを使用して、sendgrid-phpをインストールしているものとします
テキストのみのメール
<?php require_once "vendor/autoload.php"; $from = new SendGrid\Email("name", "email@example.com"); $subject = "件名"; $personalization = new SendGrid\Personalization(); $personalization->addTo(new SendGrid\Email(null, "send@example.com")); $personalization->setSubject($subject); $content = new SendGrid\Content("text/plain", "本文"); $mail = new SendGrid\Mail(); $mail->setFrom($from); $mail->addPersonalization($personalization); $mail->setSubject($subject); $mail->addContent($content); $sg = new \SendGrid("sendgridApiKey"); $response = $sg->client ->mail() ->send() ->post($mail);
テキスト+添付画像のメール
<?php require_once "vendor/autoload.php"; $from = new SendGrid\Email("name", "email@example.com"); $subject = "件名"; $personalization = new SendGrid\Personalization(); $personalization->addTo(new SendGrid\Email(null, "send@example.com")); $personalization->setSubject($subject); $content = new SendGrid\Content("text/plain", "本文"); $mail = new SendGrid\Mail(); $mail->setFrom($from); $mail->addPersonalization($personalization); $mail->setSubject($subject); $mail->addContent($content); // 添付ファイル $filePath = "path/to/file"; $attachment = new SendGrid\Attachment(); $handle = fopen($filePath, "rb"); $contents = fread($handle, filesize($filePath)); $attachment->setContent(base64_encode($contents)); $attachment->setFilename("filename.png"); $fileInfo = new FInfo(FILEINFO_MIME_TYPE); $attachment->setType($fileInfo->file($filePath)); $mail->addAttachment($attachment); $sg = new \SendGrid("sendgridApiKey"); $response = $sg->client ->mail() ->send() ->post($mail);
テキストメール送信の処理に対して追加したのは下記コードです。
処理としては、ファイルをバイナリで開いてBase64変換することだけです。
調べると、ファイルパスとファイル名を渡すと送信できるような記述が多くてハマりました。
// 添付ファイル $filePath = "path/to/file"; $attachment = new SendGrid\Attachment(); $handle = fopen($filePath, "rb"); $contents = fread($handle, filesize($filePath)); $attachment->setContent(base64_encode($contents)); $attachment->setFilename("filename.png"); $fileInfo = new FInfo(FILEINFO_MIME_TYPE); $attachment->setType($fileInfo->file($filePath)); $mail->addAttachment($attachment);
その他
テキストメールの改行が無視される
テキストメールを送信したときに、改行が無視されてしまうことがありました。
SendGridのダッシュボードから、テキストメールはそのまま送信するように設定すれば解決しました。
メール送信時のステータスコード確認
上記のソースコードで送信後に下記を実行することでステータスコードを取得できます。
$response->statusCode()
200や202などがメール送信成功時に返ってくるステータスコードの様です。