Cómo enviar un correo electrónico a través de la API: PHP, Node
YourTrend
API de correo electrónico y SMTP Campañas Automatizaciones SMS Web push Mensajeros Bandeja de entrada unificada Correo seguro Analítica
ENUKRUDEESFRITPLPTHIZH
Iniciar sesión Comenzar gratis
API & SMTP

Cómo enviar un correo electrónico a través de la API: PHP, Node, Python, Go

Respuesta corta

Publicar en /api/v1/messages con una clave Bearer — ejemplos de curl y cuatro-SDK en funcionamiento con manejo de errores.

Cómo enviar un correo electrónico a través de la API

To send an email through the YourTrend API, make a POST request to https://yourtrend.online/api/v1/messages with an Authorization: Bearer YOUR_API_KEY header and a JSON body containing from, to, subject and html. The server responds 202 Accepted, queues the message and signs it with DKIM. Below are working examples in curl and four SDKs.

Obtén una clave API y verifica tu dominio

Crea una clave en el panel bajo "Claves API" — cada clave tiene alcances como messages:send. Solo puedes enviar desde una dirección en un dominio verificado: agrega el dominio, publica SPF, DKIM y DMARC, y espera el estado de verificado. Consulta la documentación y verifica un dominio de forma gratuita en el laboratorio de entregabilidad.

Inicio rápido: curl

curl -X POST https://yourtrend.online/api/v1/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "noreply@yourdomain.com",
    "to": "user@example.com",
    "subject": "¡Bienvenido!",
    "html": "<h1>Hola</h1><p>Gracias por registrarte.</p>",
    "stream": "transactional"
  }'

Una respuesta exitosa es HTTP 202:

{
  "data": {
    "id": "9b1c7e2a-1f3d-4b8a-9c11-4a2f6e8d0c33",
    "status": "en cola",
    "stream": "transactional",
    "from": "noreply@yourdomain.com",
    "to": "user@example.com",
    "subject": "¡Bienvenido!"
  }
}

PHP

Descarga el SDK de un solo archivo desde /sdk/yourtrend.php — sin dependencias, solo la extensión cURL.

<?php
require 'yourtrend.php';

$yt  = new YourTrend('YOUR_API_KEY');
$res = $yt->sendEmail(
    'noreply@yourdomain.com',
    'user@example.com',
    '¡Bienvenido!',
    '<h1>Hola</h1>'
);

if ($res['status'] === 202) {
    echo 'En cola: ' . $res['data']['data']['id'];
} else {
    echo 'Error: ' . ($res['data']['error']['message'] ?? 'desconocido');
}

Node.js

El SDK /sdk/yourtrend.js utiliza el fetch incorporado (Node 18+) y no necesita paquetes externos.

const YourTrend = require('./yourtrend');
const yt = new YourTrend('YOUR_API_KEY');

const { status, data } = await yt.sendEmail(
  'noreply@yourdomain.com',
  'user@example.com',
  '¡Bienvenido!',
  '<h1>Hola</h1>'
);

if (status === 202) console.log('En cola:', data.data.id);
else console.error('Error:', data.error?.message);

Python

El /sdk/yourtrend.py SDK es una biblioteca estándar pura (urllib) — nada que instalar.

from yourtrend import YourTrend

yt = YourTrend('YOUR_API_KEY')
res = yt.send_email(
    'noreply@yourdomain.com',
    'user@example.com',
    '¡Bienvenido!',
    '<h1>¡Hola!</h1>',
)

if res['status'] == 202:
    print('En cola:', res['data']['data']['id'])
else:
    print('Error:', res['data']['error']['message'])

Ir

paquete principal

import (
    "fmt"
    "log"
    "yourtrend"
)

func main() {
    c := yourtrend.New("YOUR_API_KEY")
    resp, err := c.SendEmail(
        "noreply@yourdomain.com",
        "user@example.com",
        "¡Bienvenido!",
        "<h1>¡Hola!</h1>",
    )
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    fmt.Println("HTTP", resp.StatusCode) // 202 = aceptado
}

Campos adicionales

El cuerpo de la solicitud acepta más que los cuatro básicos:

  • texto — una alternativa de texto plano (recomendada junto a html).
  • cc, bcc, reply_to — arreglos de direcciones o una cadena separada por comas.
  • stream — transactional or bulk: splitting streams protects your IP reputation.
  • attachments — an array of {filename, content, content_type} objects, with content base64-encoded.
  • template_id + variables — send a stored template with merge substitutions.
  • send_at — an ISO-8601 timestamp for scheduled delivery.

Idempotency and test mode

Add an Idempotency-Key: <uuid> header — on a retry of the same request (say, after a timeout) YourTrend returns the first response instead of sending a duplicate. The X-Test-Mode: true header runs the request without real delivery and without consuming quota — handy in CI.

Handling errors

Every API error arrives in one envelope:

{
  "error": {
    "code": "quota_exceeded",
    "message": "Daily sending limit reached.",
    "request_id": "0f9d…"
  }
}

Check the HTTP status, not just the body. Common codes: 401 — bad key; 422 — validation error (an errors field lists the problem per field); 429 — rate limited, retry with exponential backoff; 402/quota_exceeded — plan quota exhausted. For bulk jobs use POST /api/v1/messages/batch (up to 1000 messages, a 207 response with a per-message status).

Want a wrapper for your stack? The YourTrend SDKs for PHP, Node, Python and Go are one dependency-free file each — copy them straight into your project. The full list of endpoints and fields lives in the API documentation, and volume tiers are on the pricing page.

Checking status and webhooks

Once queued, you can read a message's status with GET /api/v1/messages/{id} — the response carries status (queued, sent, delivered, bounced, complained) plus open and complaint counts. Polling the API per message is wasteful, so wire up webhooks for delivery events: YourTrend sends a POST to your URL on delivered, opened, clicked, bounced and complained. Each call is HMAC-signed in a header — verify the signature to reject forgeries, and reply 2xx within a few seconds; on failure the webhook is retried with growing backoff (a retry queue). This is how you build robust failure handling: hard bounces go to the suppression list, complaints get an immediate reaction, and your own analytics fill up without manual polling. The full list of event types and the payload shape are in the documentation, and sending tiers are on the pricing page.

Términos explicados en el glosario: SPF · DKIM · DMARC · Hard bounce
En esta página ← Todos los artículos
¿Fue útil?

Un clic. Nos dice qué escribir a continuación.

No hay calificaciones aún — la tuya sería la primera.

Comentarios

Los comentarios se leen antes de aparecer.
  1. No hay comentarios aún. Inicia la conversación.
Ponerlo en práctica

Comienza a enviar en minutos

Esta página fue encontrada buscando por

Consultas de búsqueda reales que traen personas aquí — las resaltadas abren la página correspondiente.