스키마 튜토리얼
스키마 튜토리얼레슨 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
        }
      }
    }
  }
}