Transactional email API errors and retries
Handle Piisend 4xx/5xx responses, when to retry sends, idempotency keys, and backoff—without double-mailing users on OTP or reset flows.
Section 1
The Criticality of Resilient Email Delivery
Transactional emails, such as password resets, OTP verification emails, and order confirmation emails, are mission-critical. Any failure in sending these can directly impact user experience and business operations. Therefore, building robust error handling and retry mechanisms into your transactional email API integration is not just a best practice, but a necessity for resilient email delivery. This developer guide will walk you through architectural patterns and actionable code examples to make your email sending workflows fault-tolerant.
1curl -X POST https://api.piisend.com/api/v1/emails \2 -H "Authorization: Bearer YOUR_API_KEY" \3 -H "Content-Type: application/json" \4 -d '{5 "to": ["user@example.com"],6 "subject": "Welcome to Piisend!",7 "html": "<p>Hello there!</p>",8 "text": "Hello there!"9 }'Section 2
Understanding Piisend API Error Responses
When interacting with any email API for developers, understanding the various error responses is the first step in effective API error handling. Piisend's API uses standard HTTP status codes to indicate the outcome of a request. A 200 OK means success, while 4xx codes indicate client-side errors (e.g., invalid payload, authentication issues), and 5xx codes point to server-side issues. Always inspect the response body for detailed error messages, which provide context for debugging and implementing specific retry logic.
1{2 "error": {3 "code": "invalid_payload",4 "message": "The 'to' field is required and must be an array of valid email addresses.",5 "details": [6 {7 "field": "to",8 "message": "Value is not a valid email address."9 }10 ]11 }12}Section 3
Implementing Idempotent Retries with Exponential Backoff
Transient network issues or temporary service outages can cause API calls to fail. For these scenarios, implementing a smart email sending retry logic with exponential backoff and jitter is crucial. Exponential backoff increases the delay between retries, preventing overwhelming the API, while jitter adds randomness to avoid synchronized retries. Crucially, use the Idempotency-Key header for all retries. This ensures that if the initial request was processed but the response was lost, subsequent retries with the same key won't result in duplicate emails, making your idempotent email API calls safe and reliable.
1import requests2import time3import uuid4 5def send_email_with_retries(to_email, subject, html_content, text_content, api_key, max_retries=5):6 idempotency_key = str(uuid.uuid4())7 for i in range(max_retries):8 headers = {9 "Authorization": f"Bearer {api_key}",10 "Content-Type": "application/json",11 "Idempotency-Key": idempotency_key12 }13 payload = {14 "to": [to_email],15 "subject": subject,16 "html": html_content,17 "text": text_content18 }19 try:20 response = requests.post(21 "https://api.piisend.com/api/v1/emails",22 headers=headers,23 json=payload24 )25 response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)26 print(f"Email sent successfully to {to_email}!")27 return response.json()28 except requests.exceptions.HTTPError as e:29 print(f"Attempt {i+1} failed: {e.response.status_code} - {e.response.text}")30 if e.response.status_code < 500 and e.response.status_code != 429: # Client error, not retryable (except rate limit)31 print("Non-retryable client error. Aborting.")32 break33 if i < max_retries - 1:34 sleep_time = (2 ** i) + (uuid.uuid4().time_low % 1000) / 1000.0 # Exponential backoff with jitter35 print(f"Retrying in {sleep_time:.2f} seconds...")36 time.sleep(sleep_time)37 except requests.exceptions.RequestException as e:38 print(f"Attempt {i+1} failed due to network error: {e}")39 if i < max_retries - 1:40 sleep_time = (2 ** i) + (uuid.uuid4().time_low % 1000) / 1000.041 print(f"Retrying in {sleep_time:.2f} seconds...")42 time.sleep(sleep_time)43 print(f"Failed to send email to {to_email} after {max_retries} attempts.")44 return None45 46# Example usage:47# send_email_with_retries(48# "recipient@example.com",49# "Your Order Confirmation",50# "<h1>Thanks for your order!</h1>",51# "Thanks for your order!",52# "YOUR_API_KEY"53# )Section 4
Advanced Strategies for Resilient Email Delivery
Beyond basic retries, consider advanced strategies for truly resilient email delivery. Implement circuit breakers to prevent cascading failures when an email service is experiencing prolonged outages. Monitor Piisend's webhook delivery events to track bounces, complaints, and deliveries, allowing you to react to permanent failures (like invalid email addresses) by updating user profiles or implementing bounce suppression. For critical flows, consider a fallback mechanism, such as queuing emails for manual review or switching to a secondary email provider, though this adds complexity. Proactive monitoring of your email API failures is key to maintaining high deliverability and a positive user experience.
1const fetch = require('node-fetch');2const { v4: uuidv4 } = require('uuid');3 4async function sendEmailWithRetries(toEmail, subject, htmlContent, textContent, apiKey, maxRetries = 5) {5 const idempotencyKey = uuidv4();6 for (let i = 0; i < maxRetries; i++) {7 const headers = {8 'Authorization': `Bearer ${apiKey}`,9 'Content-Type': 'application/json',10 'Idempotency-Key': idempotencyKey11 };12 const payload = {13 to: [toEmail],14 subject: subject,15 html: htmlContent,16 text: textContent17 };18 19 try {20 const response = await fetch('https://api.piisend.com/api/v1/emails', {21 method: 'POST',22 headers: headers,23 body: JSON.stringify(payload)24 });25 26 if (response.ok) {27 console.log(`Email sent successfully to ${toEmail}!`);28 return await response.json();29 } else {30 const errorBody = await response.text();31 console.error(`Attempt ${i + 1} failed: ${response.status} - ${errorBody}`);32 33 if (response.status < 500 && response.status !== 429) {34 console.log('Non-retryable client error. Aborting.');35 break;36 }37 38 if (i < maxRetries - 1) {39 const sleepTime = (2 ** i) * 1000 + Math.random() * 1000; // Exponential backoff with jitter40 console.log(`Retrying in ${sleepTime / 1000:.2f} seconds...`);41 await new Promise(resolve => setTimeout(resolve, sleepTime));42 }43 }44 } catch (error) {45 console.error(`Attempt ${i + 1} failed due to network error: ${error.message}`);46 if (i < maxRetries - 1) {47 const sleepTime = (2 ** i) * 1000 + Math.random() * 1000;48 console.log(`Retrying in ${sleepTime / 1000:.2f} seconds...`);49 await new Promise(resolve => setTimeout(resolve, sleepTime));50 }51 }52 }53 console.log(`Failed to send email to ${toEmail} after ${maxRetries} attempts.`);54 return null;55}56 57// Example usage:58// sendEmailWithRetries(59// 'recipient@example.com',60// 'Your Account Update',61// '<h2>Your account details have been updated.</h2>',62// 'Your account details have been updated.',63// 'YOUR_API_KEY'64// );