SDK Node.js ufficiale per l’API email di toSend.
- Pacchetto:
tosend - Requisiti: Node.js 18+
- Repository: tosend/tosend-node
Installazione
npm install tosend
Avvio rapido
import { ToSend } from 'tosend';
const tosend = new ToSend('tsend_your_api_key');
const response = await tosend.send({
from: { email: 'hello@yourdomain.com', name: 'Your App' },
to: [{ email: 'user@example.com' }],
subject: 'Welcome!',
html: '<h1>Hello!</h1><p>Thanks for signing up.</p>',
});
console.log(response.message_id);
Configurazione
Semplice (solo chiave API)
const tosend = new ToSend('tsend_your_api_key');
Con opzioni
const tosend = new ToSend({
apiKey: 'tsend_your_api_key',
baseUrl: 'https://api.tosend.com', // optional
timeout: 30000, // optional, in milliseconds
});
Invio di un’email
Email di base
const response = await tosend.send({
from: { email: 'hello@yourdomain.com', name: 'Your App' },
to: [
{ email: 'user@example.com' },
{ email: 'another@example.com', name: 'John Doe' },
],
subject: 'Hello!',
html: '<h1>Welcome</h1>',
text: 'Welcome', // optional
});
Con CC, BCC e Reply-To
const response = await tosend.send({
from: { email: 'hello@yourdomain.com' },
to: [{ email: 'user@example.com' }],
cc: [{ email: 'cc@example.com' }],
bcc: [{ email: 'bcc@example.com' }],
reply_to: { email: 'support@yourdomain.com', name: 'Support' },
subject: 'Hello',
html: '<p>Hello World</p>',
});
Con allegati
import * as fs from 'fs';
const response = await tosend.send({
from: { email: 'hello@yourdomain.com' },
to: [{ email: 'user@example.com' }],
subject: 'Your Invoice',
html: '<p>Please find your invoice attached.</p>',
attachments: [
{
type: 'application/pdf',
name: 'invoice.pdf',
content: fs.readFileSync('invoice.pdf').toString('base64'),
},
],
});
Invio in batch
Invia più email in una sola richiesta:
const response = await tosend.batch([
{
from: { email: 'hello@yourdomain.com' },
to: [{ email: 'user1@example.com' }],
subject: 'Hello User 1',
html: '<p>Welcome!</p>',
},
{
from: { email: 'hello@yourdomain.com' },
to: [{ email: 'user2@example.com' }],
subject: 'Hello User 2',
html: '<p>Welcome!</p>',
},
]);
response.results.forEach((result) => {
if (result.status === 'success') {
console.log('Sent:', result.message_id);
} else {
console.log('Failed:', result.message);
}
});
Informazioni sull’account
const info = await tosend.getAccountInfo();
console.log(info.account.status); // 'active'
console.log(info.account.credit_balance); // null = no credit limit
console.log(info.account.limit_per_second);
info.domains.forEach((domain) => {
console.log(domain.domain_name, domain.verification_status);
});
Gestione degli errori
import { ToSend, ToSendError } from 'tosend';
try {
const response = await tosend.send({
from: { email: 'hello@yourdomain.com' },
to: [{ email: 'user@example.com' }],
subject: 'Hello',
html: '<p>Hello</p>',
});
} catch (error) {
if (error instanceof ToSendError) {
console.log('Error:', error.message);
console.log('Code:', error.code);
console.log('Errors:', error.errors);
if (error.isValidationError) {
// Handle validation error (422)
}
if (error.isAuthenticationError) {
// Handle auth error (401/403)
}
if (error.isRateLimitError) {
// Handle rate limit (429)
}
}
}
Admin API
ToSendAdmin è un client separato per l’Admin API. Prende una chiave di amministrazione (tsend_admin_...) e rifiuta una chiave di invio quando crei il client. Ogni chiamata richiede lo scope corrispondente sulla chiave.
import { ToSendAdmin } from 'tosend';
const admin = new ToSendAdmin(process.env.TOSEND_ADMIN_KEY!);
// Act on one of your client teams (sends X-Account-Id)
const client = admin.forAccount(4203);
const domain = await client.createDomain('client.example.com');
const detail = await client.getDomain(domain.id);
console.log(detail.dns_records.dkim); // show these records to your client
// Needs api_keys:write and emails:send
const key = await client.createSendingKey('Client: Acme Corp');
console.log(key.api_key); // returned once, store it now
// Needs emails:send
await client.send({
from: { email: 'hello@client.example.com' },
to: [{ email: 'user@example.com' }],
subject: 'Hi',
html: '<p>Hello</p>',
});
Disponibili anche: getInfo (controlla la chiave ed elenca i suoi scope), listDomains, deleteDomain, listEmails, getEmail, listSuppressions, deleteSuppression, listWebhooks, createWebhook, updateWebhook, deleteWebhook, listSendingKeys, deleteSendingKey, listTeams, createTeam, updateTeam e batch. I metodi di elenco prendono page e per_page e restituiscono { data, total, page, per_page }.
TypeScript
Supporto TypeScript completo, con i tipi esportati:
import {
ToSend,
ToSendError,
SendEmailParams,
SendEmailResponse,
BatchEmailResponse,
AccountInfo,
Address,
Attachment,
} from 'tosend';