Back

Reading and Writing Data Using the Zoho Mail API

Aug 13, 20246 minute read

Hey there, fellow JavaScript devs! Ready to dive into the world of Zoho Mail API? Let's get our hands dirty with some code and learn how to sync data for a user-facing integration. Buckle up!

Introduction

Zoho Mail API is a powerful tool that lets us interact with users' email data programmatically. Whether you're building a custom email client or integrating email functionality into your app, this API has got you covered. Today, we'll focus on reading and writing data, perfect for creating seamless user experiences.

Authentication

First things first – we need to get authenticated. Zoho uses OAuth 2.0, so let's set that up:

  1. Register your app in the Zoho Developer Console
  2. Get your client ID and secret
  3. Implement the OAuth flow

Here's a quick snippet to manage your tokens:

const axios = require('axios'); async function getAccessToken(refreshToken) { const response = await axios.post('https://accounts.zoho.com/oauth/v2/token', { refresh_token: refreshToken, client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, grant_type: 'refresh_token' }); return response.data.access_token; }

Reading Data

Now that we're authenticated, let's fetch some emails:

async function getEmails(accessToken) { const response = await axios.get('https://mail.zoho.com/api/accounts/1/messages', { headers: { 'Authorization': `Bearer ${accessToken}` }, params: { limit: 10, sortorder: 'desc' } }); return response.data.data; }

Want attachments? No problem:

async function getAttachment(accessToken, accountId, messageId, attachmentId) { const response = await axios.get(`https://mail.zoho.com/api/accounts/${accountId}/messages/${messageId}/attachments/${attachmentId}`, { headers: { 'Authorization': `Bearer ${accessToken}` }, responseType: 'arraybuffer' }); return response.data; }

Writing Data

Sending emails is just as easy:

async function sendEmail(accessToken, to, subject, content) { await axios.post('https://mail.zoho.com/api/accounts/1/messages', { to: [{ address: to }], subject, content }, { headers: { 'Authorization': `Bearer ${accessToken}` } }); }

Syncing Strategies

For efficient syncing, use incremental sync with modified timestamps:

async function syncEmails(accessToken, lastSyncTime) { const response = await axios.get('https://mail.zoho.com/api/accounts/1/messages', { headers: { 'Authorization': `Bearer ${accessToken}` }, params: { lastModifiedTime: lastSyncTime, sortorder: 'asc' } }); // Process new/updated emails // Update lastSyncTime }

Error Handling and Rate Limiting

Always implement retry logic and respect rate limits:

async function apiCall(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.response && error.response.status === 429) { // Rate limited, wait and retry await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } else if (i === maxRetries - 1) { throw error; } } } }

Webhooks for Real-time Updates

Set up webhooks to get real-time updates:

  1. Configure webhook URL in Zoho Developer Console
  2. Create an endpoint to receive webhook payloads
  3. Process incoming data in real-time

Best Practices

  1. Cache frequently accessed data
  2. Use HTTPS for all API calls
  3. Implement proper error handling
  4. Optimize API calls by batching requests when possible

Conclusion

And there you have it! You're now equipped to build awesome integrations with Zoho Mail API. Remember, practice makes perfect, so start coding and see what you can create. Happy hacking!