スキーマチュートリアル
スキーマチュートリアルレッスン14: メール送信を快適に

レッスン14: メール送信を快適に

このチュートリアルレッスンでは、Gato GraphQLのメール送信に関するいくつかの機能を実演します。

メールの送信

メールは、Email Sender エクステンションが提供するミューテーション _sendEmail を使って送信します。

  • メールは messageAs 入力のどのプロパティを使用するかによって、コンテンツタイプ「text」または「HTML」で送信されます
  • from 入力はオプションです。指定しない場合、WordPressに保存されている設定が使用されます
  • _sendEmail は WordPressの wp_mail 関数を実行するため、WordPress でのメール送信に定義された設定(使用するSMTPプロバイダーなど)が使用されます
mutation {
  sendTextEmail: _sendEmail(
    input: {
      from: {
        email: "from@email.com"
        name: "Me myself"
      }
      replyTo: "replyTo@email.com"
 
      to: "target@email.com"
      cc: ["cc1@email.com", "cc2@email.com"]
      bcc: ["bcc1@email.com", "bcc2@email.com", "bcc3@email.com"]
      
      subject: "Email with text content"
      messageAs: {
        text: "Hello world!"
      }
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
  }
  
  sendHTMLEmail: _sendEmail(
    input: {
      to: "target@email.com"
      subject: "Email with HTML content"
      messageAs: {
        html: "<p>Hello world!</p>"
      }
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
  }
}

Markdownを使ったメールの作成

Helper Function Collection エクステンションのフィールド _strConvertMarkdownToHTML は、MarkdownをHTMLに変換します。

このフィールドを使用して、Markdownでメールを作成できます:

query GetEmailData {
  emailMessage: _strConvertMarkdownToHTML(
    text: """
 
We have great news: **Version 1.0 of our plugin will be released soon!**
 
If you'd like to help us beta test it, please complete [this form](https://forms.gle/FpXNromWAsZYC1zB8).
 
_Please reply by 30th June 🙏_
 
Thanks!
 
    """
  )
    @export(as: "emailMessage")
}
 
mutation SendEmail @depends(on: "GetEmailData") {
  _sendEmail(
    input: {
      to: "target@email.com"
      subject: "Great news!"
      messageAs: {
        html: $emailMessage
      }
    }
  ) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
  }
}

メールへの動的データの注入

PHP Functions via Schema エクステンションが提供する関数フィールドを使って、プレースホルダーを含むメッセージテンプレートを作成し、動的データで置換できます:

query GetPostData($postID: ID!) {
  post(by: {id: $postID}) {
    title @export(as: "postTitle")
    excerpt @export(as: "postExcerpt")
    url @export(as: "postLink")
    author {
      name @export(as: "postAuthorName")
      url @export(as: "postAuthorLink")
    }
  }
}
 
query GetEmailData @depends(on: "GetPostData") {
  emailMessageTemplate: _strConvertMarkdownToHTML(
    text: """
 
There is a new post by [{$postAuthorName}]({$postAuthorLink}):
 
**{$postTitle}**: {$postExcerpt}
 
[Read online]({$postLink})
 
    """
  )
  emailMessage: _strReplaceMultiple(
    search: ["{$postAuthorName}", "{$postAuthorLink}", "{$postTitle}", "{$postExcerpt}", "{$postLink}"],
    replaceWith: [$postAuthorName, $postAuthorLink, $postTitle, $postExcerpt, $postLink],
    in: $__emailMessageTemplate
  )
    @export(as: "emailMessage")
  subject: _sprintf(string: "New post created by %s", values: [$postAuthorName])
    @export(as: "emailSubject")
}
 
mutation SendEmail @depends(on: "GetEmailData") {
  _sendEmail(
    input: {
      to: "target@email.com"
      subject: $emailSubject
      messageAs: {
        html: $emailMessage
      }
    }
  ) {
    status
  }
}

管理者への通知メールの送信

WordPressの wp_options テーブルから管理者ユーザーのメールアドレスを取得し、その値を to フィールドに注入できます:

query ExportData {
  adminEmail: optionValue(name: "admin_email")
    @export(as: "adminEmail")
}
 
mutation SendEmail @depends(on: "ExportData") {
  _sendEmail(
    input: {
      to: $adminEmail
      subject: "Admin notification"
      messageAs: {
        html: "There is a new post on the site, go check!"
      }
    }
  ) {
    status
  }
}

また、Schema Configurationでネストされたミューテーションが有効になっている場合、mutation オペレーション内で管理者のメールアドレスを取得し(Field to Input を使ってミューテーションに注入)することもできます:

mutation SendEmail {
  adminEmail: optionValue(name: "admin_email")
  _sendEmail(
    input: {
      to: $__adminEmail
      subject: "Admin notification"
      messageAs: {
        html: "There is a new post on the site, go check!"
      }
    }
  ) {
    status
  }
}

ユーザーへのパーソナライズされたメールの送信

このGraphQLクエリを機能させるには、エンドポイントに適用されるスキーマ設定ネストされたミューテーションを有効にする必要があります

_sendEmail はグローバルフィールド(より正確にはグローバルミューテーション)であるため、User を含むGraphQLスキーマのあらゆる型に対して実行できます。

このクエリはユーザーの一覧を取得し、それぞれのデータ(名前、メールアドレス、メタとして保存されている残りクレジット数)を取得して、各ユーザーにパーソナライズされたメールを送信します:

mutation {
  users {
    email
    displayName
    credits: metaValue(key: "credits")
    
    # If the user does not have meta entry "credits", use `0` credits
    hasNoCreditsEntry: _isNull(value: $__credits)
    remainingCredits: _if(condition: $__hasNoCreditsEntry, then: 0, else: $__credits)
 
    emailMessageTemplate: _strConvertMarkdownToHTML(
      text: """
 
Hello %s,
 
Your have **%s remaining credits** in your account.
 
Would you like to [buy more](%s)?
 
      """
    )
    emailMessage: _sprintf(
      string: $__emailMessageTemplate,
      values: [
        $__displayName,
        $__remainingCredits,
        "https://mysite.com/buy-credits"
      ]
    )
 
    _sendEmail(
      input: {
        to: $__email
        subject: "Remaining credits alert"
        messageAs: {
          html: $__emailMessage
        }
      }
    ) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
    }
  }
}