Adicionar a Integração SendGrid
SendGrid é um serviço baseado na nuvem para a entrega de e-mails transacionais e de marketing. A conexão desta integração permite que a sua aplicação envie e-mails programaticamente (por exemplo, e-mails de boas-vindas, redefinições de palavra-passe ou notificações).
Passos de Configuração
Seção intitulada “Passos de Configuração”Após selecionar SendGrid da lista de integrações, aparecerá um modal de configuração. Deve fornecer as seguintes credenciais para estabelecer a conexão:
1. Chave API
Seção intitulada “1. Chave API”Este é o token de autenticação gerado dentro da sua conta SendGrid.
- Entrada: Cole a sua chave API SendGrid privada no campo de texto.
- Ajuda: Se não tiver uma, clique na ligação “Onde encontrar a chave API?” fornecida no modal para instruções sobre como gerá-la.
2. Ambiente
Seção intitulada “2. Ambiente”Especifique o contexto do ambiente para esta integração.
- Entrada: Introduza o identificador do ambiente (por exemplo,
Production,Stagingou uma etiqueta de configuração específica) no campo Ambiente.
Finalizar a Conexão
Seção intitulada “Finalizar a Conexão”Assim que os campos estiverem preenchidos:
- Reveja a barra de estado (atualmente mostra Not Connected).
- Clique no botão preto Add no canto inferior direito para guardar as credenciais e ativar a integração.


Referência API de Integração SendGrid
Seção intitulada “Referência API de Integração SendGrid”Configuração do SendGrid
Seção intitulada “Configuração do SendGrid”Configurar Chave API do SendGrid
Seção intitulada “Configurar Chave API do SendGrid”Configura a chave API do SendGrid para um projeto e ambiente específicos.
Mutation:
mutation { sendgrid_configureSendGrid ( apiKey: "SG._api_key_here" )}Envio de E-mails
Seção intitulada “Envio de E-mails”Enviar E-mail Simples
Seção intitulada “Enviar E-mail Simples”Envia um e-mail para um ou mais destinatários.
Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail ( email: { from: { email: "sender@archie.com", name: "Sender Name" }, subject: "Test Email", to: { email: "recipient@gmail.com", name: "Recipient Name" }, content: { type: "text/html", value: "<h1>Hello World</h1><p>This is a test email.</p>" } } ) { messageId success }}Response:
{ "data": { "sendgrid_sendEmail": { "messageId": "sent-1234567890", "success": true } }}Enviar E-mail com CC e BCC
Seção intitulada “Enviar E-mail com CC e BCC”Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail ( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] cc: [ { email: "cc@example.com" name: "CC Recipient" } ] bcc: [ { email: "bcc@example.com" } ] subject: "Email with CC and BCC" content: [ { type: "text/html" value: "<h1>Hello</h1><p>This email has CC and BCC recipients.</p>" } ] } ) { messageId success }}Enviar E-mail com Anexos
Seção intitulada “Enviar E-mail com Anexos”Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] subject: "Email with Attachment" content: [ { type: "text/html" value: "<h1>Hello</h1><p>Please find attached file.</p>" } ] attachments: [ { content: "SGVsbG8gV29ybGQ=" type: "text/plain" filename: "document.txt" disposition: "attachment" } ] } ) { messageId success }}Nota: O campo content nos anexos deve estar codificado em Base64.
Enviar E-mail com Categorias e Etiquetas
Seção intitulada “Enviar E-mail com Categorias e Etiquetas”Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] subject: "Categorized Email" content: [ { type: "text/html" value: "<h1>Hello</h1>" } ] categories: ["transactional", "notification"] tags: ["important", "urgent"] } ) { messageId success }}Enviar E-mail Programado
Seção intitulada “Enviar E-mail Programado”Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] subject: "Scheduled Email" content: [ { type: "text/html" value: "<h1>Hello</h1>" } ] sendAt: "2025-12-25T10:00:00Z" } ) { messageId success }}Enviar E-mail com Argumentos Personalizados
Seção intitulada “Enviar E-mail com Argumentos Personalizados”Mutation:
mutation sendgrid_sendEmail { sendgrid_sendEmail( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] subject: "Email with Custom Args" content: [ { type: "text/html" value: "<h1>Hello</h1>" } ] customArgs: { orderId: "12345" userId: "67890" campaignId: "abc123" } } ) { messageId success }}Envio de E-mails em Massa
Seção intitulada “Envio de E-mails em Massa”Enviar Vários E-mails
Seção intitulada “Enviar Vários E-mails”Mutation:
mutation sendgrid_sendBulkEmail { sendgrid_sendBulkEmail( emails: { emails: [ { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient1@example.com" name: "Recipient 1" } ] subject: "Bulk Email 1" content: [ { type: "text/html" value: "<h1>Email 1</h1>" } ] } { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient2@example.com" name: "Recipient 2" } ] subject: "Bulk Email 2" content: [ { type: "text/html" value: "<h1>Email 2</h1>" } ] } ] } ) { messageIds success }}Response:
{ "data": { "sendgrid_sendBulkEmail": { "messageIds": ["sent-1234567890", "sent-1234567891"], "success": true } }}Enviar E-mails com Modelos
Seção intitulada “Enviar E-mails com Modelos”Enviar E-mail usando Modelo Dinâmico
Seção intitulada “Enviar E-mail usando Modelo Dinâmico”Mutation:
mutation sendgrid_sendTemplate { sendgrid_sendTemplate( email: { from: { email: "sender@example.com" name: "Sender Name" } to: [ { email: "recipient@example.com" name: "Recipient Name" } ] templateId: "d-1234567890abcdef" substitutions: { name: "John Doe" orderNumber: "12345" totalAmount: "$99.99" } } ) { messageId success }}Response:
{ "data": { "sendgrid_sendTemplate": { "messageId": "sent-1234567890", "success": true } }}Gestão de Contactos
Seção intitulada “Gestão de Contactos”Adicionar Contacto
Seção intitulada “Adicionar Contacto”Mutation:
mutation sendgrid_addContact { sendgrid_addContact( contact: { email: "newcontact@example.com" firstName: "John" lastName: "Doe" customFields: { company: "Acme Corp" phone: "+1234567890" position: "Developer" } listIds: ["list-id-1", "list-id-2"] } )}Response:
{ "data": { "sendgrid_addContact": true }}Atualizar Contacto
Seção intitulada “Atualizar Contacto”Mutation:
mutation sendgrid_updateContact { sendgrid_updateContact( contact: { email: "existing@example.com" firstName: "Jane" lastName: "Smith" customFields: { company: "New Company" phone: "+0987654321" } } )}Response:
{ "data": { "sendgrid_updateContact": true }}Eliminar Contacto
Seção intitulada “Eliminar Contacto”Mutation:
mutation sendgrid_deleteContact { sendgrid_deleteContact( email: "contact@example.com" )}Response:
{ "data": { "sendgrid_deleteContact": true }}Analíticas e Estatísticas
Seção intitulada “Analíticas e Estatísticas”Obter Estatísticas de E-mail
Seção intitulada “Obter Estatísticas de E-mail”Query:
query sendgrid_getEmailStats { sendgrid_getEmailStats ( startDate: "2025-01-01" endDate: "2025-01-31" ) { opens clicks bounces spamReports delivered startDate endDate }}Response:
{ "data": { "sendgrid_getEmailStats": { "opens": 150, "clicks": 75, "bounces": 5, "spamReports": 2, "delivered": 1000, "startDate": "2025-01-01T00:00:00Z", "endDate": "2025-01-31T00:00:00Z" } }}Validar E-mail
Seção intitulada “Validar E-mail”Query:
query sendgrid_validateEmail { sendgrid_validateEmail ( email: "test@example.com" ) { valid score local domain reason suggestions }}Response (com SendGrid Premium):
{ "data": { "sendgrid_validateEmail": { "valid": true, "score": 0.95, "local": "test", "domain": "example.com", "reason": "", "suggestions": [] } }}Response (Validação básica - quando o SendGrid Premium não está disponível):
{ "data": { "sendgrid_validateEmail": { "valid": true, "score": 0.8, "local": "test", "domain": "example.com", "reason": "Basic validation (SendGrid premium validation not available)", "suggestions": [] } }}Nota: O endpoint de validação de e-mail do SendGrid (/v3/validations/email) requer permissões especiais e pode não estar disponível em todas as contas. Se a sua chave API não tiver acesso a este endpoint (erro 403), o sistema usará automaticamente validação básica baseada em regex como alternativa.
Exemplos Completos com Variáveis
Seção intitulada “Exemplos Completos com Variáveis”Exemplo com Variáveis GraphQL
Seção intitulada “Exemplo com Variáveis GraphQL”Request:
{ "query": "mutation SendEmail($email: EmailInput!) { sendgrid_sendEmail(email: $email) { messageId success } }", "variables": { "email": { "from": { "email": "sender@example.com", "name": "Sender Name" }, "to": [ { "email": "recipient@example.com", "name": "Recipient Name" } ], "subject": "Test Email", "content": [ { "type": "text/html", "value": "<h1>Hello World</h1>" } ] } }}Gestão de Erros
Seção intitulada “Gestão de Erros”Exemplo de Erro
Seção intitulada “Exemplo de Erro”Request:
{ "query": "mutation { sendgrid_sendEmail(email: { from: { email: \"invalid\" }, to: [], subject: \"Test\", content: [] }) { messageId success } }"}Response Error:
{ "errors": [ { "message": "validation error: at least one recipient is required", "path": ["sendgrid_sendEmail"] } ], "data": null}Erros Comuns
Seção intitulada “Erros Comuns”-
ID do projeto em falta:
{"errors": [{"message": "project ID is required in context"}]} -
Configuração não encontrada:
{"errors": [{"message": "sendgrid configuration not found for project: xxx, environment: master"}]} -
Chave API inválida:
{"errors": [{"message": "sendgrid API error: status 401, body: ..."}]}
Webhooks
Seção intitulada “Webhooks”Endpoint de Webhooks
Seção intitulada “Endpoint de Webhooks”O endpoint de webhooks está disponível em:
- HTTP:
POST http://localhost:8080/webhooks/sendgrid - Lambda:
POST /webhooks/sendgrid
Configuração SendGrid
Seção intitulada “Configuração SendGrid”- Vá a SendGrid Dashboard > Settings > Mail Settings > Event Webhook
- Configure o URL:
https://seu-dominio.com/webhooks/sendgrid - Selecione os eventos que deseja receber
- Configure a chave de verificação na variável de ambiente
WEBHOOK_VERIFICATION_KEY
Eventos Suportados
Seção intitulada “Eventos Suportados”processed: E-mail processadodelivered: E-mail entregueopened: E-mail abertoclicked: Ligação clicadabounce: E-mail devolvidodropped: E-mail descartadospamreport: Reportado como spamunsubscribe: Cancelamento de subscrição