Schema 教程
Schema 教程第14课:轻松发送邮件

第14课:轻松发送邮件

本教程课程演示了 Gato GraphQL 在发送邮件方面的多项功能。

发送邮件

我们通过 Email Sender 扩展提供的 mutation _sendEmail 来发送邮件。

  • 邮件的内容类型为「text」或「HTML」,取决于 messageAs 输入中使用的属性
  • 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,我们也可以直接在 mutation 操作中获取管理员邮件地址(并通过 Field to Input 将其注入到 mutation 中):

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 query 正常工作,应用于端点的 Schema Configuration 需要启用嵌套 Mutation

由于 _sendEmail 是一个全局字段(更准确地说,是全局 mutation),它可以在 GraphQL schema 的任意类型上执行,包括 User

此 query 获取用户列表,取得每位用户的数据(姓名、邮件地址以及存储为元数据的剩余积分),并向每位用户发送个性化邮件:

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
        }
      }
    }
  }
}