Engineering•3 min read

How to Send Transactional Emails from Serverless Functions with Piisend

Learn how to integrate Piisend's transactional email API with serverless platforms like AWS Lambda and Google Cloud Functions. This guide covers secure setup and efficient email delivery from your serverless email API.

How to Send Transactional Emails from Serverless Functions with Piisend

Section 1

Why Use Serverless Functions for Transactional Emails?

Serverless functions offer a powerful and cost-effective way to handle event-driven tasks, making them ideal for sending transactional emails. By leveraging a serverless email API like Piisend, developers can build highly scalable and resilient email sending workflows without managing underlying infrastructure. This approach simplifies operations, reduces costs, and allows you to focus on your application's core logic, ensuring your transactional email lambda or cloud function executes only when needed.

bash
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": "<strong>Welcome!</strong> Thank you for signing up.",
8 "text": "Welcome! Thank you for signing up."
9 }'

Section 2

Integrating Piisend with AWS Lambda for Email Sending

AWS Lambda provides a flexible environment for executing code in response to events. To send emails from a Lambda function, you'll typically use a Python or Node.js runtime. Securely store your Piisend API key as an environment variable within your Lambda configuration. This ensures your transactional email lambda function can authenticate with Piisend's API to reliably send email from serverless environments.

python
1import os
2import json
3import requests
4
5def lambda_handler(event, context):
6 api_key = os.environ.get("PIISEND_API_KEY")
7 if not api_key:
8 return {
9 "statusCode": 500,
10 "body": json.dumps({"message": "API key not configured"})
11 }
12
13 payload = {
14 "to": ["recipient@example.com"],
15 "subject": "Your AWS Lambda Transactional Email",
16 "html": "<strong>Hello from AWS Lambda!</strong> Your order is confirmed.",
17 "text": "Hello from AWS Lambda! Your order is confirmed."
18 }
19
20 headers = {
21 "Authorization": f"Bearer {api_key}",
22 "Content-Type": "application/json"
23 }
24
25 try:
26 response = requests.post(
27 "https://api.piisend.com/api/v1/emails",
28 headers=headers,
29 json=payload
30 )
31 response.raise_for_status()
32 return {
33 "statusCode": 200,
34 "body": json.dumps({"message": "Email sent successfully", "response": response.json()})
35 }
36 except requests.exceptions.RequestException as e:
37 return {
38 "statusCode": 500,
39 "body": json.dumps({"message": f"Failed to send email: {str(e)}"})
40 }

Section 3

Sending Emails via Google Cloud Functions

Google Cloud Functions offer a similar serverless experience, often preferred by developers in the Google Cloud ecosystem. When setting up your cloud functions email sender, ensure your Piisend API key is stored securely, typically using Google Secret Manager and accessed via environment variables. This JavaScript example demonstrates how to invoke the Piisend API to send a transactional email from a Cloud Function.

javascript
1const fetch = require('node-fetch');
2
3exports.sendEmailFromCloudFunction = async (req, res) => {
4 const apiKey = process.env.PIISEND_API_KEY;
5 if (!apiKey) {
6 res.status(500).send('API key not configured.');
7 return;
8 }
9
10 const payload = {
11 to: ['recipient@example.com'],
12 subject: 'Your Google Cloud Function Email',
13 html: '<strong>Hello from Google Cloud Functions!</strong> Here is your OTP.',
14 text: 'Hello from Google Cloud Functions! Here is your OTP.'
15 };
16
17 try {
18 const response = await fetch(
19 'https://api.piisend.com/api/v1/emails',
20 {
21 method: 'POST',
22 headers: {
23 'Authorization': `Bearer ${apiKey}`,
24 'Content-Type': 'application/json'
25 },
26 body: JSON.stringify(payload)
27 }
28 );
29
30 if (!response.ok) {
31 const errorData = await response.json();
32 throw new Error(`API error: ${response.status} - ${JSON.stringify(errorData)}`);
33 }
34
35 const data = await response.json();
36 res.status(200).send({ message: 'Email sent successfully', response: data });
37 } catch (error) {
38 console.error('Error sending email:', error);
39 res.status(500).send(`Failed to send email: ${error.message}`);
40 }
41};

Section 4

Serverless Email Best Practices

When implementing serverless email best practices, always prioritize security by using environment variables or secret management services for API keys. Implement robust error handling and retry mechanisms, especially for network requests to the email API. Consider using an Idempotency-Key header with Piisend to prevent duplicate email sends if a function is retried. Monitoring your function logs and Piisend's delivery logs is crucial for debugging and ensuring high deliverability for your azure functions email or other cloud function setups.

Start sending

Ship transactional email in minutes

Create an API key, verify a domain, and send your first message with Piisend.