### Quick Start Examples Source: https://docs.unosend.co/guides/smtp Provides code examples for integrating Unosend's SMTP service with various programming languages and frameworks. ```APIDOC ## Quick Start Examples ### Nodemailer (Node.js) ```javascript import nodemailer from 'nodemailer'; const transporter = nodemailer.createTransport({ host: 'smtp.unosend.co', port: 587, secure: false, // true for 465, false for 587 auth: { user: 'unosend', pass: 'un_your_api_key', // Your API key }, }); async function sendEmail() { const info = await transporter.sendMail({ from: 'hello@yourdomain.com', to: 'user@example.com', subject: 'Hello from Unosend!', html: '
This is your first email sent with Unosend.
' }) }); const data = await response.json(); console.log('Email sent:', data.id); ``` -------------------------------- ### Unosend CLI Quick Start Commands Source: https://docs.unosend.co/guides/cli A quick guide to essential Unosend CLI commands including initialization, sending emails, managing domains, and checking logs. These commands provide a fast way to interact with the Unosend service. ```bash # Initialize with your API key unosend init # Send an email unosend send -t user@example.com -s "Hello!" --text "Hi there" # View your domains unosend domains list # Check email logs unosend logs ``` -------------------------------- ### Send Email Source: https://docs.unosend.co/quickstart This endpoint allows you to send an email. You need to provide an API key for authentication and a JSON payload containing email details. ```APIDOC ## POST /api/v1/emails ### Description Sends an email using the Unosend API. ### Method POST ### Endpoint https://www.unosend.co/api/v1/emails ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **from** (string) - Required - The sender's email address. - **to** (array of strings) - Required - A list of recipient email addresses. - **subject** (string) - Required - The subject of the email. - **text** (string) - Optional - The plain text content of the email. - **html** (string) - Optional - The HTML content of the email. ### Request Example ```json { "from": "hello@yourdomain.com", "to": ["recipient@example.com"], "subject": "Test Email", "text": "This is a test email.", "html": "This is a test email.
" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the sent email. - **from** (string) - The sender's email address. - **to** (array of strings) - A list of recipient email addresses. - **status** (string) - The current status of the email (e.g., "queued"). - **created_at** (string) - The timestamp when the email was created. #### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "from": "hello@yourdomain.com", "to": ["recipient@example.com"], "status": "queued", "created_at": "2024-01-15T10:30:00.000Z" } ``` ``` -------------------------------- ### Send Email via Unosend REST API (Go) Source: https://docs.unosend.co/quickstart This Go program illustrates how to send an email using the Unosend REST API. It constructs the JSON payload and makes an HTTP POST request, requiring your API key. ```go package main import ( "bytes" "encoding/json" "net/http" ) func main() { payload := map[string]interface{}{ "from": "hello@yourdomain.com", "to": []string{"recipient@example.com"}, "subject": "Hello from Unosend!", "html": "This is your first email sent with Unosend.
", } body, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", "https://www.unosend.co/api/v1/emails", bytes.NewBuffer(body)) req.Header.Set("Authorization", "Bearer un_your_api_key") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` -------------------------------- ### Verify Domain API Source: https://docs.unosend.co/quickstart This endpoint is used to verify the ownership of a previously added domain by checking for the presence of the required DNS records. ```APIDOC ## POST /api/v1/domains/{domain_id}/verify ### Description Verifies the DNS records for a previously added domain. ### Method POST ### Endpoint https://www.unosend.co/api/v1/domains/{domain_id}/verify ### Parameters #### Path Parameters - **domain_id** (string) - Required - The unique identifier of the domain to verify. #### Headers - **Authorization** (string) - Required - Bearer token with your API key (e.g., `Bearer un_your_api_key`) ### Response #### Success Response (200) - **status** (string) - The verification status of the domain (e.g., `verified`). #### Response Example ```json { "status": "verified" } ``` ``` -------------------------------- ### Add DMARC TXT Record for Monitoring Source: https://docs.unosend.co/guides/dmarc This snippet shows the necessary DNS TXT record to start with a DMARC monitoring policy (`p=none`). This allows you to collect data on email authentication without impacting delivery. Replace `dmarc@yourdomain.com` with your actual reporting email address. ```text v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com ``` -------------------------------- ### Install Unosend CLI Source: https://docs.unosend.co/guides/cli Installs the Unosend CLI globally using npm. If permission issues arise, it's recommended to use 'sudo' or a Node version manager like nvm. ```bash sudo npm install -g unosend ``` -------------------------------- ### Unosend API Pagination Example Source: https://docs.unosend.co/api-reference/introduction Example of how to use limit and offset query parameters for paginating list endpoints in the Unosend API. 'limit' specifies items per page, and 'offset' skips items. ```bash GET /v1/emails?limit=20&offset=40 ``` -------------------------------- ### Send Email via Unosend SMTP (Node.js) Source: https://docs.unosend.co/integrations/smtp This Node.js example uses the 'nodemailer' library to connect to Unosend's SMTP server and send an HTML email. Ensure you have 'nodemailer' installed (`npm install nodemailer`). Replace placeholders for API key and email addresses. ```javascript const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ host: 'smtp.unosend.co', port: 587, secure: false, // Use STARTTLS auth: { user: 'unosend', pass: 'un_YOUR_API_KEY_HERE' } }); async function sendEmail() { const info = await transporter.sendMail({ from: 'you@yourdomain.com', to: 'recipient@example.com', subject: 'Hello from Unosend!', html: 'Your email was sent via Unosend SMTP.
' }); console.log('Message sent:', info.messageId); } sendEmail(); ``` -------------------------------- ### Enable Email Tracking with Unosend (Node.js, Python, PHP, Ruby) Source: https://docs.unosend.co/guides/smtp These examples show how to configure email sending to enable open and click tracking with Unosend. Specific headers like 'X-Unosend-Track-Opens', 'X-Unosend-Track-Clicks', and 'X-Unosend-Tags' are used. Ensure you have the necessary libraries installed for each language. ```javascript const info = await transporter.sendMail({ from: 'hello@yourdomain.com', to: 'user@example.com', subject: 'Newsletter', html: 'Click here
', headers: { 'X-Unosend-Track-Opens': 'true', 'X-Unosend-Track-Clicks': 'true', 'X-Unosend-Tags': 'newsletter,january' } }); ``` ```python msg = MIMEMultipart() msg['From'] = 'hello@yourdomain.com' msg['To'] = 'user@example.com' msg['Subject'] = 'Newsletter' msg['X-Unosend-Track-Opens'] = 'true' msg['X-Unosend-Track-Clicks'] = 'true' msg['X-Unosend-Tags'] = 'newsletter,january' body = 'Click here
' msg.attach(MIMEText(body, 'html')) ``` ```php use Illuminate\Support\Facades\Mail; use Illuminate\Mail\Message; Mail::send([], [], function (Message $message) { $message->to('user@example.com') ->subject('Newsletter') ->html('Your email was sent via Unosend SMTP.
' end end mail.deliver! puts 'Email sent successfully!' ``` -------------------------------- ### Install Unosend CLI Source: https://docs.unosend.co/guides/cli Install the Unosend CLI globally using npm, yarn, or pnpm. This command makes the 'unosend' command available in your terminal for immediate use. ```bash npm install -g unosend ``` ```bash yarn global add unosend ``` ```bash pnpm add -g unosend ``` -------------------------------- ### Verify Sending Domain via cURL Source: https://docs.unosend.co/quickstart This cURL command is used to verify a sending domain after adding the necessary DNS records. It requires the domain ID obtained from the domain creation step and your API key for authentication. ```bash curl -X POST https://www.unosend.co/api/v1/domains/{domain_id}/verify \ -H "Authorization: Bearer un_your_api_key" ``` -------------------------------- ### Retrieve Suppression by ID using cURL Source: https://docs.unosend.co/api-reference/suppressions/get-suppression This example demonstrates how to fetch suppression details using the cURL command-line tool. It requires the suppression ID and an API key for authorization. ```bash curl https://www.unosend.co/api/v1/suppressions/550e8400-e29b-41d4-a716-446655440000 \ -H "Authorization: Bearer un_your_api_key" ``` -------------------------------- ### DNS CNAME Record Configuration Example Source: https://docs.unosend.co/guides/tracking This example shows how to configure a CNAME record in your domain's DNS settings to enable link branding. It maps a subdomain (e.g., 'track') to Unosend's tracking domain. ```dns track.example.com. IN CNAME track.unosend.co. ``` -------------------------------- ### List Email Templates using cURL Source: https://docs.unosend.co/api-reference/templates This code example shows how to retrieve a list of all created email templates using the Unosend API with cURL. It requires an authorization header and makes a GET request to the /v1/templates endpoint. ```bash curl https://www.unosend.co/api/v1/templates \ -H "Authorization: Bearer un_your_api_key" ``` -------------------------------- ### Send Email via Unosend REST API (Ruby) Source: https://docs.unosend.co/quickstart This Ruby script demonstrates sending an email via the Unosend REST API using the Net::HTTP library. It requires your API key and sets the necessary headers and JSON body. ```ruby require 'net/http' require 'json' require 'uri' uri = URI('https://www.unosend.co/api/v1/emails') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer un_your_api_key' request['Content-Type'] = 'application/json' request.body = { from: 'hello@yourdomain.com', to: ['recipient@example.com'], subject: 'Hello from Unosend!', html: 'This is your first email sent with Unosend.
' }.to_json response = http.request(request) puts response.body ``` -------------------------------- ### HTML Template Example with Variables Source: https://docs.unosend.co/api-reference/templates An example of an HTML template structure that utilizes Unosend's variable syntax. Variables are enclosed in double curly braces, such as {{first_name}}, and will be dynamically replaced with provided data when an email is sent. ```htmlYour order #{{order_id}} has been shipped.
Track it here: Track Order
``` -------------------------------- ### Recommended Final DMARC TXT Record for Rejection Policy Source: https://docs.unosend.co/guides/dmarc This snippet represents the recommended DMARC TXT record for a strict rejection policy (`p=reject`). This provides maximum protection by blocking emails that fail DMARC authentication. Ensure you have monitored for 1-2 weeks with `p=none` before implementing this. ```text v=DMARC1; p=reject; rua=mailto:dmarc@yourdomain.com; pct=100 ``` -------------------------------- ### Send Email via Unosend REST API (C#) Source: https://docs.unosend.co/quickstart This C# example demonstrates sending an email using the Unosend REST API with HttpClient. It defines the email payload as an anonymous object and sets the necessary headers. ```csharp using System.Net.Http; using System.Text; using System.Text.Json; var client = new HttpClient(); var payload = new { from = "hello@yourdomain.com", to = new[] { "recipient@example.com" }, subject = "Hello from Unosend!", html = "This is your first email sent with Unosend.
" }; ``` -------------------------------- ### Add Domain API Response Source: https://docs.unosend.co/guides/domain-verification Example JSON response after successfully adding a domain to Unosend. It includes the domain's ID, name, status, and the necessary DNS records (TXT and CNAME) for verification and SPF/DKIM setup. ```json { "id": "dom_xxxxxxxxxxxxxxxx", "domain": "yourdomain.com", "status": "pending", "dns_records": [ { "type": "TXT", "name": "_unosend", "value": "v=unosend1 k=abc123..." }, { "type": "TXT", "name": "@", "value": "v=spf1 include:_spf.unosend.co ~all" }, { "type": "CNAME", "name": "unosend._domainkey", "value": "dkim.unosend.co" } ], "created_at": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Initialize Unosend CLI Source: https://docs.unosend.co/guides/cli Initialize the Unosend CLI by setting up your API key. This command prompts for your API key, which is then stored locally for future use. ```bash unosend init ``` -------------------------------- ### Example Get Suppression Response (JSON) Source: https://docs.unosend.co/api-reference/suppressions Example JSON response when retrieving details for a specific suppressed email. Includes comprehensive information such as ID, email, reason, source, detailed metadata, and creation timestamp. ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "email": "bounced@example.com", "reason": "hard_bounce", "source_email_id": "email_abc123", "metadata": { "bounce_type": "Permanent", "bounce_subtype": "NoEmail", "diagnostic_code": "550 5.1.1 User unknown" }, "created_at": "2024-01-15T10:30:00.000Z" } ``` -------------------------------- ### Get Help with Unosend CLI Commands Source: https://docs.unosend.co/guides/cli Provides general help for the Unosend CLI and specific help for individual commands like 'send' or 'domains'. ```bash # General help unosend --help # Command-specific help unosend send --help unosend domains --help ``` -------------------------------- ### Send Email via Unosend SMTP (Go) Source: https://docs.unosend.co/integrations/smtp This Go example uses the standard 'net/smtp' package to send an HTML email via Unosend's SMTP server. It demonstrates basic SMTP authentication and message construction. Replace the API key and email addresses. ```go package main import ( "net/smtp" "fmt" ) func main() { // SMTP settings host := "smtp.unosend.co" port := "587" user := "unosend" pass := "un_YOUR_API_KEY_HERE" // Email content from := "you@yourdomain.com" to := []string{"recipient@example.com"} msg := []byte("To: recipient@example.com\r\n" + "Subject: Hello from Unosend!\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "\r\n" + "Your email was sent via Unosend SMTP.
\r\n") // Authentication auth := smtp.PlainAuth("", user, pass, host) // Send email err := smtp.SendMail(host+":"+port, auth, from, to, msg) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Email sent successfully!") } ``` -------------------------------- ### List API Keys using cURL, JavaScript, and Python Source: https://docs.unosend.co/api-reference/api-keys/list-keys This snippet demonstrates how to list all API keys in your Unosend account. It includes examples for making the request using cURL, JavaScript (with fetch API), and Python (with the requests library). The response will contain a list of API keys, but their full values are omitted for security. ```bash curl https://www.unosend.co/api/v1/api-keys \ -H "Authorization: Bearer un_xxxxxxxxxx" ``` ```javascript await fetch('https://www.unosend.co/api/v1/api-keys', { headers: { 'Authorization': 'Bearer un_xxxxxxxxxx' } }); ``` ```python import requests requests.get('https://www.unosend.co/api/v1/api-keys', headers={'Authorization': 'Bearer un_xxxxxxxxxx'} ) ``` -------------------------------- ### Add Domain API Source: https://docs.unosend.co/quickstart This endpoint allows you to add a new sending domain to your Unosend account. You will need to provide your API key for authentication and specify the domain name. ```APIDOC ## POST /api/v1/domains ### Description Adds a new sending domain to your Unosend account. ### Method POST ### Endpoint https://www.unosend.co/api/v1/domains ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token with your API key (e.g., `Bearer un_your_api_key`) - **Content-Type** (string) - Required - `application/json` #### Request Body - **domain** (string) - Required - The domain name to add (e.g., `yourdomain.com`) ### Request Example ```json { "domain": "yourdomain.com" } ``` ### Response #### Success Response (200) - **domain_id** (string) - The unique identifier for the added domain. - **dns_records** (array) - An array of DNS records that need to be added to your domain provider for verification. #### Response Example ```json { "domain_id": "d_xxxxxxxxxxxxxxxxx", "dns_records": [ { "type": "TXT", "name": "_unspsc.yourdomain.com", "value": "unspsc=d_xxxxxxxxxxxxxxxxx" }, { "type": "MX", "name": "yourdomain.com", "value": "mx.unosend.com" } ] } ``` ``` -------------------------------- ### Send Email API Source: https://docs.unosend.co/quickstart This endpoint allows you to send an email using the Unosend REST API. It requires an API key for authorization and accepts email details in JSON format. ```APIDOC ## POST /api/v1/emails ### Description Send an email using the Unosend REST API. ### Method POST ### Endpoint https://www.unosend.co/api/v1/emails ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer un_your_api_key`) - **Content-Type** (string) - Required - `application/json` #### Request Body - **from** (string) - Required - The sender's email address (e.g., `hello@yourdomain.com`) - **to** (array of strings) - Required - A list of recipient email addresses (e.g., `["recipient@example.com"]`) - **subject** (string) - Required - The subject line of the email - **html** (string) - Required - The HTML content of the email ### Request Example ```json { "from": "hello@yourdomain.com", "to": ["recipient@example.com"], "subject": "Hello from Unosend!", "html": "This is your first email sent with Unosend.
" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the sent email. #### Response Example ```json { "id": "email_abc123xyz" } ``` ``` -------------------------------- ### Email Template Variable Syntax Examples Source: https://docs.unosend.co/guides/templates Illustrates different ways to use variables within Unosend email templates, including basic placeholders, default values, conditional logic, and loops for dynamic content generation. ```html Hello, {{first_name}}! Your email is: {{email}} ``` ```html Hello, {{first_name | default: "there"}}! Your plan: {{plan | default: "Free"}} ``` ```html {{#if is_premium}}No items yet. Start shopping!
{{/if}} ``` ```html| {{name}} | {{quantity}} | {{price}} |
Total: {{total}}
``` -------------------------------- ### Verify Domain API Response Source: https://docs.unosend.co/guides/domain-verification Example JSON response after a domain has been successfully verified. It shows the domain ID, name, and the updated status indicating successful verification along with the timestamp. ```json { "id": "dom_xxxxxxxxxxxxxxxx", "domain": "yourdomain.com", "status": "verified", "verified_at": "2024-01-15T10:35:00Z" } ``` -------------------------------- ### Send Email via Unosend API (Multiple Languages) Source: https://docs.unosend.co/api-reference/emails/send-email Demonstrates how to send an email using the Unosend API by making a POST request. This includes examples for cURL, JavaScript, Python, Go, PHP, and Ruby. The request requires an Authorization header and a JSON payload containing sender, recipient, subject, HTML content, and tracking options. ```bash curl -X POST https://www.unosend.co/api/v1/emails \ -H "Authorization: Bearer un_xxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "from": "hello@yourdomain.com", "to": ["user@example.com"], "subject": "Hello World", "html": "Thanks for signing up.
", "tracking": { "open": true, "click": false } }' ``` ```javascript await fetch('https://www.unosend.co/api/v1/emails', { method: 'POST', headers: { 'Authorization': 'Bearer un_xxxxxxxxxx', 'Content-Type': 'application/json' }, body: JSON.stringify({ from: 'hello@yourdomain.com', to: ['user@example.com'], subject: 'Hello World', html: 'Thanks for signing up.
', tracking: { open: true, click: false } }) }); ``` ```python import requests requests.post('https://www.unosend.co/api/v1/emails', headers={'Authorization': 'Bearer un_xxxxxxxxxx'}, json={ 'from': 'hello@yourdomain.com', 'to': ['user@example.com'], 'subject': 'Hello World', 'html': 'Thanks for signing up.
', 'tracking': { 'open': True, 'click': False } } ) ``` ```go payload := map[string]interface{}{ "from": "hello@yourdomain.com", "to": []string{"user@example.com"}, "subject": "Hello World", "html": "Thanks for signing up.
", "tracking": map[string]bool{ "open": true, "click": false, }, } body, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", "https://www.unosend.co/api/v1/emails", bytes.NewBuffer(body)) req.Header.Set("Authorization", "Bearer un_xxxxxxxxxx") req.Header.Set("Content-Type", "application/json") ``` ```php $ch = curl_init('https://www.unosend.co/api/v1/emails'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer un_xxxxxxxxxx', 'Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode([ 'from' => 'hello@yourdomain.com', 'to' => ['user@example.com'], 'subject' => 'Hello World', 'html' => 'Thanks for signing up.
', 'tracking' => [ 'open' => true, 'click' => false ] ]) ]); curl_exec($ch); ``` ```ruby require 'net/http' require 'json' uri = URI('https://www.unosend.co/api/v1/emails') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri) request['Authorization'] = 'Bearer un_xxxxxxxxxx' request['Content-Type'] = 'application/json' request.body = { from: 'hello@yourdomain.com', to: ['user@example.com'], subject: 'Hello World', html: 'Thanks for signing up.
' }.to_json http.request(request) ``` -------------------------------- ### Expected Output for DMARC Verification Source: https://docs.unosend.co/guides/dmarc This shows the expected output when successfully querying for a DMARC TXT record configured for monitoring. It confirms the version, policy, and reporting address are correctly set. ```text "v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com" ``` -------------------------------- ### Retrieve Suppression by ID using Python Source: https://docs.unosend.co/api-reference/suppressions/get-suppression This Python example utilizes the `requests` library to fetch suppression details. It demonstrates how to include the API key in the request headers for authentication. ```python import requests response = requests.get( 'https://www.unosend.co/api/v1/suppressions/550e8400-e29b-41d4-a716-446655440000', headers={'Authorization': 'Bearer un_your_api_key'} ) data = response.json() ``` -------------------------------- ### Send First Email using Go Source: https://docs.unosend.co/index This snippet shows how to send a transactional email using Go's standard 'net/http' package. It includes authentication with your API key and defines the email's sender, recipient, subject, and HTML body. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://www.unosend.co/api/v1/emails" apiKey := "un_your_api_key" payload := map[string]interface{}{ "from": "hello@yourdomain.com", "to": []string{"user@example.com"}, "subject": "Welcome to Unosend!", "html": "Welcome to Unosend!
" } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() var result map[string]interface{} err = json.NewDecoder(res.Body).Decode(&result) if err != nil { fmt.Println("Error decoding response:", err) return } fmt.Println(result) } ``` -------------------------------- ### Retrieve Suppression by ID using Node.js Source: https://docs.unosend.co/api-reference/suppressions/get-suppression This Node.js example shows how to retrieve suppression details using the `fetch` API. It includes setting the necessary Authorization header with your API key. ```javascript const response = await fetch( 'https://www.unosend.co/api/v1/suppressions/550e8400-e29b-41d4-a716-446655440000', { headers: { 'Authorization': 'Bearer un_your_api_key' } } ); const data = await response.json(); ``` -------------------------------- ### Webhook Best Practices Source: https://docs.unosend.co/guides/webhooks Recommended guidelines for implementing and managing Unosend webhooks to ensure security, reliability, and efficiency. ```APIDOC ## Best Practices ### Description Follow these best practices when implementing Unosend webhooks: * **Always verify signatures**: Ensure that incoming webhook requests genuinely originate from Unosend to prevent security breaches. * **Return 200 quickly**: Acknowledge receipt of the webhook promptly by returning a 200 OK status. Process the event data asynchronously to avoid timeouts and ensure responsiveness. * **Handle duplicates**: Implement idempotency using unique event IDs to safely process the same webhook multiple times without unintended side effects. * **Log all events**: Maintain detailed logs of all received webhook events for debugging, auditing, and monitoring purposes. * **Use HTTPS**: Always use HTTPS for your webhook endpoint to ensure secure communication between Unosend and your server. ``` -------------------------------- ### Send Email via Unosend REST API (PHP) Source: https://docs.unosend.co/quickstart This PHP code snippet shows how to send an email using the Unosend REST API with cURL. It includes setting the Authorization header and the JSON payload. ```php true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer un_your_api_key', 'Content-Type: application/json' ], CURLOPT_POSTFIELDS => json_encode([ 'from' => 'hello@yourdomain.com', 'to' => ['recipient@example.com'], 'subject' => 'Hello from Unosend!', 'html' => 'This is your first email sent with Unosend.
' ]) ]); $response = curl_exec($ch); curl_close($ch); echo $response; ``` -------------------------------- ### Pagination Source: https://docs.unosend.co/api-reference/introduction List endpoints support pagination using the `limit` and `offset` query parameters to control the number of items returned and the starting point of the results. ```APIDOC ## Pagination List endpoints support pagination using `limit` and `offset` query parameters: ```bash theme={null} GET /v1/emails?limit=20&offset=40 ``` | Parameter | Type | Default | Description | | --------- | ------- | ------- | ---------------------------------- | | `limit` | integer | 20 | Number of items per page (max 100) | | `offset` | integer | 0 | Number of items to skip | ``` -------------------------------- ### Create API Key Source: https://docs.unosend.co/api-reference/api-keys/create-key Create a new API key with specified permissions. The full API key is only returned once upon creation, so store it securely. ```APIDOC ## POST /api/v1/api-keys ### Description Create a new API key. The full API key is only returned once upon creation. Store it securely. ### Method POST ### Endpoint https://www.unosend.co/api/v1/api-keys ### Parameters #### Request Body - **name** (string) - Required - A descriptive name for the API key. - **permission** (string) - Optional - Permission level: `full_access`, `sending_access`, or `read_only`. Defaults to `full_access`. ### Request Example ```json { "name": "Production Server" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the API key. - **name** (string) - The name of the API key. - **key** (string) - The generated API key (only returned on creation). - **created_at** (string) - The timestamp when the API key was created. #### Response Example ```json { "id": "key_123", "name": "Production Server", "key": "un_abc123xyz...", "created_at": "2024-01-15T10:30:00.000Z" } ``` ### Warning The full API key is only returned once upon creation. Store it securely. ``` -------------------------------- ### Send Email via Unosend REST API (cURL) Source: https://docs.unosend.co/quickstart This snippet demonstrates how to send an email using the Unosend REST API via cURL. It requires an API key and specifies sender, recipient, subject, and HTML content. ```bash curl -X POST https://www.unosend.co/api/v1/emails \ -H "Authorization: Bearer un_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "from": "hello@yourdomain.com", "to": ["recipient@example.com"], "subject": "Hello from Unosend!", "html": "This is your first email sent with Unosend.
" }' ``` -------------------------------- ### HTML Link Example With Branding Source: https://docs.unosend.co/guides/tracking This HTML snippet demonstrates a tracking link after implementing link branding, using a custom domain for increased brand trust and recognition. No code changes are required in your emails once set up. ```html Click here ``` -------------------------------- ### Verify DMARC Record with dig Command Source: https://docs.unosend.co/guides/dmarc This command-line snippet demonstrates how to verify your DMARC TXT record using the `dig` utility. It queries the DNS for the `_dmarc` TXT record associated with your domain. The output should match the record you configured. ```bash dig TXT _dmarc.yourdomain.com +short ``` -------------------------------- ### Create a Webhook using cURL Source: https://docs.unosend.co/api-reference/webhooks This snippet demonstrates how to create a new webhook subscription using a cURL command. It specifies the target URL and the events to subscribe to. Requires an API key for authentication. ```bash curl -X POST https://www.unosend.co/api/v1/webhooks \ -H "Authorization: Bearer un_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "url": "https://yourdomain.com/webhooks/unosend", "events": ["email.delivered", "email.opened", "email.clicked", "email.bounced"] }' ``` -------------------------------- ### Send First Email using Python Source: https://docs.unosend.co/index This snippet demonstrates sending a transactional email with Python using the 'requests' library. It requires your API key for authentication and specifies the sender, recipient, subject, and HTML content. ```python import requests url = "https://www.unosend.co/api/v1/emails" headers = { "Authorization": "Bearer un_your_api_key", "Content-Type": "application/json" } data = { "from": "hello@yourdomain.com", "to": ["user@example.com"], "subject": "Welcome to Unosend!", "html": "Welcome to Unosend!
" } response = requests.post(url, headers=headers, json=data) print(response.json()) ``` -------------------------------- ### Send Email via Unosend SMTP (PHP) Source: https://docs.unosend.co/integrations/smtp This PHP example uses the PHPMailer library to send an HTML email via Unosend's SMTP. You need to install PHPMailer via Composer (`composer require phpmailer/phpmailer`). Update the API key and recipient details. ```php isSMTP(); $mail->Host = 'smtp.unosend.co'; $mail->SMTPAuth = true; $mail->Username = 'unosend'; $mail->Password = 'un_YOUR_API_KEY_HERE'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // Recipients $mail->setFrom('you@yourdomain.com', 'Your Name'); $mail->addAddress('recipient@example.com'); // Content $mail->isHTML(true); $mail->Subject = 'Hello from Unosend!'; $mail->Body = 'Your email was sent via Unosend SMTP.
'; $mail->send(); echo 'Email sent successfully!'; } catch (Exception $e) { echo "Email could not be sent. Error: {$mail->ErrorInfo}"; } ``` -------------------------------- ### Send Email with Options (cURL) Source: https://docs.unosend.co/guides/sending-emails This cURL example demonstrates sending an email with advanced options including CC, BCC, reply-to address, custom headers, and tags. It requires an API key and specifies detailed sender and recipient information. ```bash curl -X POST https://www.unosend.co/api/v1/emails \ -H "Authorization: Bearer un_your_api_key" \ -H "Content-Type: application/json" \ -d '{ "from": "John DoeThanks for joining us.
", "text": "Welcome! Thanks for joining us.", "cc": ["manager@yourdomain.com"], "bcc": ["archive@yourdomain.com"], "reply_to": "support@yourdomain.com", "headers": { "X-Custom-Header": "custom-value" }, "tags": { "campaign": "onboarding", "user_type": "new" } }' ``` -------------------------------- ### Add Sending Domain via cURL Source: https://docs.unosend.co/quickstart This cURL command demonstrates how to add a sending domain to your Unosend account. It requires your API key for authorization and specifies the domain to be added in JSON format. The response will contain a domain ID needed for verification. ```bash curl -X POST https://www.unosend.co/api/v1/domains \ -H "Authorization: Bearer un_your_api_key" \ -H "Content-Type: application/json" \ -d '{"domain": "yourdomain.com"}' ```