使用 Mail API 傳送郵件

本指南說明如何使用 Mail API 傳送郵件。

事前準備

將您的寄件者電子郵件註冊為已獲授權的寄件者。詳情請參閱可以傳送電子郵件的人員一節。

傳送郵件

在 PHP 7/8 中,App Engine Mail 函式不再預設為超載,必須明確啟用。這項新行為可讓您重新利用 Mail 函式,以便更符合需求。這項變更還可讓您瞭解目前為所有 Mail 函式呼叫使用的實作方式。

如果您偏好使用原生 PHP mail() 函式透過 App Engine Mail API 傳送郵件,可以在 php.ini 檔案中啟用該函式,步驟如下:

extension = mailparse.so
sendmail_path = "php ./vendor/google/appengine-php-sdk/src/Runtime/SendMail.php -t -i"

或者,您也可以直接呼叫 Mail API:


// Notice that $image_content_id is the optional Content-ID header value of the
// attachment. Must be enclosed by angle brackets (<>)
$image_content_id = '<image-content-id>';

// Pull in the raw file data of the image file to attach it to the message.
$image_data = file_get_contents('image.jpg');

try {
    $message = new Message();
    $message->setSender('from@example.com');
    $message->addTo('to@example.com');
    $message->setSubject('Example email');
    $message->setTextBody('Hello, world!');
    $message->addAttachment('image.jpg', $image_data, $image_content_id);
    $message->send();
    echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
    echo 'There was an error';


如要進一步瞭解 Mail API 的遷移考量,請參閱「存取 PHP 的舊版套裝服務」指南。