LoginSignup
6
3

More than 5 years have passed since last update.

【AWS】【SES】【PHP】SESで添付ファイル付きメールを送信

Posted at

SesClientを利用して。sendEmailでは出来ないようなので。

$client = SesClient::factory([
                                 'key'     => 'aws key',
                                 'secret'  => 'aws secret',
                                 'version' => 'latest',
                                 'region'  => '', // us-east-1など
                             ]);

$to = "xxx@xxx";
$from = "xxx@xxx";

$subject = "テストメール件名です";
$body = "テストメール\n本文です";

$message = createRawMessage($to, $from, $subject, $body, ["attach.pdf", "attach.jpg"]);

$result = $client->sendRawEmail([
                                    'Source'       => $from,
                                    'Destinations' => [$to],
                                    'RawMessage'   => [
                                        'Data' => base64_encode($message),
                                    ],
                                ]);



function createRawMessage($to, $source, $subject, $body, $filepaths)
{

    $charset = 'ISO-2022-JP';
    $finfo = finfo_open(FILEINFO_MIME_TYPE);

    $boundaryStr = uniqid(rand()); //バウンダリ文字列
    $subject = str_replace("\r", "", mb_encode_mimeheader($subject));
    $body = mb_convert_encoding($body, $charset);

    $message = "To: " . $to . "\n";
    $message .= "From: " . $source . "\n";
    $message .= "Subject: " . $subject = str_replace("\r", "", $subject) . "\n";
    $message .= "MIME-Version: 1.0\n";
    $message .= 'Content-Type: multipart/mixed; boundary="' . $boundaryStr . '"';
    $message .= "\n\n";
    $message .= "--" . $boundaryStr . "\n";
    $message .= 'Content-Type: text/plain; charset=' . $charset;
    $message .= "\n";
    $message .= "Content-Transfer-Encoding: 7bit\n";
    $message .= "Content-Disposition: inline\n";
    $message .= "\n";
    $message .= $body;
    $message .= "\n";
    foreach ($filepaths as $filepath) {
        $message .= "\n";
        $path_parts = pathinfo($filepath);
        $filename = $path_parts['basename'];
        $mimetype = finfo_file($finfo, $filename);
        $message .= "--" . $boundaryStr . "\n";
        $message .= 'Content-Type: ' . $mimetype . '; name="' . $filename . '"';
        $message .= "\n";
        $message .= "Content-Transfer-Encoding: base64\n";
        $message .= 'Content-Disposition: attachment; filename="' . $filename . '"';
        $message .= "\n\n";
        $message .= base64_encode(file_get_contents($filepath));
        $message .= "\n";
    }
    return $message;

}

謝辞 参考URL
https://www.codeproject.com/articles/786596/how-to-use-amazon-ses-to-send-email-from-php

6
3
2

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
6
3