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!
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.
First things first – we need to get authenticated. Zoho uses OAuth 2.0, so let's set that up:
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; }
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; }
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}` } }); }
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 }
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; } } } }
Set up webhooks to get real-time updates:
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!