Mail API を使用したメールの送受信

このガイドでは、Mail API を使用してメールを送受信する方法について説明します。

始める前に

送信者のメールアドレスを承認済み送信者として登録する必要があります。詳細については、メールを送信できるユーザーをご覧ください。

メールの送信

PHP に組み込まれている mail() 関数では、App Engine Mail API を経由してメールを送信できます。メールの送信に記載されている制限事項に従っている限り、ほとんどの既存のコードで正常に機能します。

または、Mail API を直接呼び出すこともできます。

use google\appengine\api\mail\Message;

// 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';
}

メールの受信

アプリでは受信メールを、次の形式のアドレスで受信するように設定できます。

anything@appid.appspotmail.com

メールを受信するには:

  1. アプリの app.yaml ファイル内で受信メールを有効にします。次の内容を inbound_services に追加します。

    - mail
  2. 構成ファイルでは、メールアドレスを表す URL パスからアプリコード内のハンドラへのマッピングを作成します。パターン /_ah/mail/.+ はすべての受信メールアドレスに一致します。

    - url: /_ah/mail/.+
      script: handle_incoming_email.php
      login: admin
  3. アプリケーション コードで指定したハンドラのコードを実装します。

    php://input から MIME データを読み取り、Mailparse を使用してメールの内容を解析できます。