Lezione 14: Inviare email con piacere
Questa lezione del tutorial dimostra diverse funzionalità di Gato GraphQL per inviare email.
Invio di email
Inviamo email tramite la mutation _sendEmail fornita dall'estensione Email Sender.
- L'email viene inviata con tipo di contenuto "text" o "HTML" a seconda della proprietà dell'input
messageAsutilizzata - L'input
fromè opzionale; se non fornito, vengono utilizzate le impostazioni memorizzate in WordPress _sendEmailesegue la funzione WordPresswp_mail, quindi utilizzerà la configurazione definita per l'invio di email in WordPress (come il provider SMTP da utilizzare)
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
}
}
}
}Composizione dell'email in Markdown
Il campo _strConvertMarkdownToHTML dell'estensione Raccolta di Funzioni di Supporto converte il Markdown in HTML.
Possiamo usare questo campo per comporre l'email in 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
}
}
}
}Iniezione di dati dinamici nell'email
Utilizzando i campi funzione forniti dall'estensione PHP Functions via Schema, possiamo creare un template di messaggio contenente segnaposto e sostituirli con dati dinamici:
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
}
}Invio di un'email di notifica all'amministratore
Possiamo recuperare l'email dell'utente amministratore dalla tabella wp_options di WordPress e iniettare questo valore nel campo 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
}
}In alternativa, se le Mutation annidate sono abilitate nella Schema Configuration, possiamo recuperare l'email dell'amministratore direttamente nell'operazione mutation (e iniettarla nella mutation tramite 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
}
}Invio di un'email personalizzata agli utenti
Affinché questa query GraphQL funzioni, la Configurazione dello schema applicata all'endpoint deve avere le Mutation annidate abilitate
Poiché _sendEmail è un campo globale (o, più precisamente, una mutation globale), può essere eseguito su qualsiasi tipo dello schema GraphQL, incluso User.
Questa query recupera un elenco di utenti, ne ottiene i dati (nome, email e numero di crediti rimanenti, memorizzati come meta) e invia un'email personalizzata a ciascuno di essi:
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
}
}
}
}
}