# How to integrate Resend email service with Functions

import DocButton from '~/components/webkit/DocButton.vue';

This guide demonstrates how to integrate Resend email service with Azion Functions to send transactional emails directly from the edge. This integration provides fast, reliable email delivery with optimal performance and global reach.

:::tip
This demonstration shows how to leverage Functions for email operations while maintaining security and performance standards at the edge.
:::

## Requirements

Before you begin, ensure you have:

- An [Azion account](https://console.azion.com/)
- A [Resend account](https://resend.com/) with API access
- [Azion CLI](/en/documentation/products/azion-cli/overview/) installed and configured
- [Node.js](https://nodejs.org/) version 18 or higher

## Code

This is an example of how to use Resend with Azion Functions to send transactional emails. The complete code example you can find in this [GitHub repository](https://github.com/egermano/edge-functions-examples/tree/main/packages/resend).

```typescript
import { Hono } from "hono";
import { fire } from "hono/service-worker";


const app = new Hono();

const RESEND_API_KEY = process.env.RESEND_API_KEY!;
const EMAIL_TO = "your.email@azion.com";

app.get("/", async (c) => {
  const res = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${RESEND_API_KEY}`,
    },
    body: JSON.stringify({
      from: "onboarding@resend.dev",
      to: EMAIL_TO,
      subject: "hello world",
      html: "<strong>it works!</strong>",
    }),
  });

  const data: any = await res.json();

  return c.json(data);
});

fire(app);
```

## Deploying to Azion

### Step 1: Authenticate with Azion

1. Log in to your Azion account via CLI:

```bash
azion login
```

2. Follow the authentication prompts to connect your CLI with your Azion account.

### Step 2: Create a new Applications

1. Initialize a new Application:

```bash
azion init
```

2. Select the template Hono Boilerplate to use for your email application.

3. Follow the prompts to configure your new Application.

### Step 3: Create a secret for the Resend API key

For security, store your Resend API key as a secret:

```bash
azion create secret RESEND_API_KEY
```

When prompted, enter your Resend API key. This ensures your sensitive data is encrypted and secure.

### Step 4: Deploy the Function

Deploy your email application to Azion's edge network:

```bash
azion deploy
```

The deployment process will:

- Upload your Function code
- Configure the application
- Set up the necessary routing rules
- Configure environment variables and secrets
- Provide you with a unique domain

### Step 4: Access your application

After deployment, you'll receive a domain like `https://xxxxxxx.map.azionedge.net`. Your email application will be available at this URL within a few minutes after DNS propagation.

## Understanding the implementation

### Email sending process

The Resend Function typically handles:

1. **Request validation**: Checking email parameters and authentication
2. **Email composition**: Building email content with templates
3. **API integration**: Communicating with Resend's API
4. **Response handling**: Processing API responses and errors
5. **Logging**: Recording email sending activities

### Key benefits

- **Performance**: Email processing at the edge reduces latency
- **Reliability**: Resend's robust infrastructure ensures delivery
- **Scalability**: Automatically scales with demand
- **Global reach**: Edge locations provide worldwide coverage
- **Cost efficiency**: Optimized email delivery costs

## Testing your email application

### Step 1: Test email sending functionality

1. Navigate to your deployed application
2. Use the email form to send test emails
3. Verify emails are delivered to recipients
4. Check email formatting and content

### Step 2: Test error handling

1. **Invalid email addresses**: Test with malformed email addresses
2. **Rate limiting**: Test with rapid successive requests
3. **Authentication failures**: Test with invalid API keys
4. **Network issues**: Test error handling for API failures

### Step 3: Performance testing

1. **Response time**: Measure email sending response times
2. **Concurrent requests**: Test multiple simultaneous email sends
3. **Error rates**: Monitor success and failure rates

## Common use cases

- **Welcome emails**: Send onboarding emails to new users
- **Password resets**: Handle password reset email notifications
- **Order confirmations**: Send transactional emails for purchases
- **Notification emails**: Send alerts and updates to users
- **Contact forms**: Handle form submissions with email notifications

## Email templates and customization

### Using HTML templates

Create dynamic email templates with placeholders:

```html
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Our Service</title>
</head>
<body>
    <h1>Welcome, {{name}}!</h1>
    <p>Thank you for joining {{company}}. We're excited to have you on board.</p>
    <p>Your account is now active and ready to use.</p>
</body>
</html>
```

### Template variables

Replace placeholders with dynamic content:

```javascript
const emailTemplate = html.replace('{{name}}', userData.name)
                         .replace('{{company}}', 'Your Company');
```

## Troubleshooting

### Common issues and solutions

- **Email delivery failures**: Check API key validity and domain configuration
- **Rate limiting**: Implement proper request throttling
- **Template rendering**: Verify template syntax and variable substitution
- **Authentication errors**: Ensure API key is correctly configured as a secret

### Error handling best practices

1. **Detailed logging**: Log all email sending attempts and results
2. **Retry mechanisms**: Implement retry logic for temporary failures
3. **Efficient degradation**: Handle API downtime appropriately
4. **User feedback**: Provide clear status messages to users

## Security considerations

### API key management

- **Use secrets**: Always store API keys as Azion secrets
- **Rotate regularly**: Periodically rotate your API keys
- **Monitor usage**: Track API key usage and access patterns
- **Limit permissions**: Use API keys with minimal required permissions

### Input validation

- **Email validation**: Validate email addresses before sending
- **Content sanitization**: Clean and validate email content
- **Rate limiting**: Implement rate limiting to prevent abuse
- **Authentication**: Add proper authentication to your email endpoints

## Advanced features

### Batch email sending

Implement batch email functionality for newsletter and marketing campaigns:

```javascript
async function sendBatchEmails(recipients, template) {
    const batchSize = 100;
    for (let i = 0; i < recipients.length; i += batchSize) {
        const batch = recipients.slice(i, i + batchSize);
        await processBatch(batch, template);
    }
}
```

### Email tracking

Add tracking capabilities to monitor email engagement:

- **Open tracking**: Track when emails are opened
- **Click tracking**: Monitor link clicks in emails
- **Bounce handling**: Handle bounced emails appropriately
- **Unsubscribe management**: Process unsubscribe requests

## Next steps

- Explore advanced email templating techniques
- Implement email analytics and tracking
- Add email scheduling and delayed sending
- Integrate with other Azion products like Object Storage
- Monitor email delivery performance and optimize accordingly

---

<DocButton href="https://resend.com/docs" label="Resend API Documentation" size="medium" />
<DocButton href="/en/documentation/products/build/applications/functions/" label="Learn more about Functions" size="medium" />