@amindev91/emailjs-sdk
v1.0.0
Published
EmailJS SDK for sending emails from client-side applications
Maintainers
Readme
EmailJS SDK
A powerful JavaScript SDK for sending emails directly from client-side applications without a backend server.
Features
- 🚀 Client-side only - No backend required
- 🔒 Secure - Your email credentials are stored securely
- 📧 Multiple providers - Gmail, Outlook, SendGrid, SMTP
- 🎨 Templates - Create and use reusable email templates with custom subjects
- 👤 Custom sender names - Set custom sender names (e.g., "MyApp" instead of email address)
- 📊 Analytics - Track email delivery and engagement
- 📱 Framework agnostic - Works with React, Vue, Angular, and vanilla JS
Installation
NPM
npm install @emailjs/sdkCDN
<script src="https://cdn.emailjs.com/sdk/1.0.0/emailjs.min.js"></script>ES6 Modules
<script type="module">
import EmailJS from "https://cdn.emailjs.com/sdk/1.0.0/emailjs.esm.js";
</script>Quick Start
1. Initialize EmailJS
import EmailJS from "@emailjs/sdk";
// Initialize with your public key
const emailjs = EmailJS.init({
publicKey: "your_public_key_here",
baseURL: "https://api.emailjs.com", // Optional
timeout: 10000, // Optional
});2. Send an Email
// Send email with template (custom subject and sender name applied automatically)
const result = await emailjs.sendEmail({
serviceId: "service_123",
templateId: "template_456",
to: "[email protected]",
templateParams: {
to_name: "John Doe",
from_name: "Your App",
app_name: "MyApp", // Replaces {{app_name}} in template subject
message: "Hello from EmailJS!",
},
});
if (result.success) {
console.log("Email sent successfully!", result.messageId);
} else {
console.error("Failed to send email:", result.error);
}3. Send Email from Form
<form id="contact-form">
<input type="text" name="to_name" placeholder="Name" required />
<input type="email" name="to_email" placeholder="Email" required />
<textarea name="message" placeholder="Message" required></textarea>
<button type="submit">Send</button>
</form>
<script>
document
.getElementById("contact-form")
.addEventListener("submit", async (e) => {
e.preventDefault();
const result = await emailjs.sendForm(
"service_123",
"template_456",
"#contact-form"
);
if (result.success) {
alert("Message sent successfully!");
} else {
alert("Failed to send message: " + result.error);
}
});
</script>API Reference
EmailJS.init(options)
Initialize EmailJS with configuration options.
Parameters:
options.publicKey(string): Your EmailJS public keyoptions.baseURL(string, optional): API base URL (default: 'https://api.emailjs.com')options.timeout(number, optional): Request timeout in milliseconds (default: 10000)
Returns: EmailJS instance
emailjs.sendEmail(params)
Send an email using a service and optional template.
Parameters:
params.serviceId(string): Email service IDparams.templateId(string, optional): Template IDparams.to(string): Recipient email addressparams.subject(string, optional): Email subject (overrides template subject)params.message(string, optional): Email message (overrides template content)params.templateParams(object, optional): Template parameters for variable replacement
Returns: Promise
emailjs.sendForm(serviceId, templateId, form, publicKey?)
Send an email using form data.
Parameters:
serviceId(string): Email service IDtemplateId(string): Template IDform(HTMLFormElement | string): Form element or selectorpublicKey(string, optional): Public key (if not initialized)
Returns: Promise
emailjs.getServices()
Get available email services.
Returns: Promise<EmailService[]>
emailjs.getTemplates()
Get available templates.
Returns: Promise<Template[]>
emailjs.getPublicTemplates()
Get public templates.
Returns: Promise<Template[]>
emailjs.getLogs(page?, limit?)
Get email logs.
Parameters:
page(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 20)
Returns: Promise<{ logs: EmailLog[], pagination: any }>
emailjs.testService(serviceId, to)
Test email service connection.
Parameters:
serviceId(string): Email service IDto(string): Test email address
Returns: Promise
emailjs.getStats()
Get email statistics.
Returns: Promise
Static Methods
EmailJS.send(serviceId, templateId, templateParams, publicKey)
Send email using static method (backward compatibility).
EmailJS.sendForm(serviceId, templateId, form, publicKey)
Send form using static method (backward compatibility).
Advanced Features
Custom Sender Names
Configure custom sender names for your email services to appear as "MyApp" instead of the email address:
// When setting up your email service, configure a custom sender name
// This will make emails appear as "MyApp <[email protected]>" instead of just "[email protected]"Template Variables
Use dynamic variables in your templates for personalized content:
// Template subject: "Welcome to {{app_name}}!"
// Template content: "Hello {{name}}, welcome to {{app_name}}!"
const result = await emailjs.sendEmail({
serviceId: "service_123",
templateId: "template_456",
to: "[email protected]",
templateParams: {
name: "John Doe",
app_name: "MyApp",
},
});
// Result: Email with subject "Welcome to MyApp!" and personalized contentService Groups and Auto-Failover
Organize your email services into groups with intelligent failover:
// Services are automatically selected based on:
// 1. Service groups with selected services
// 2. Auto-failover settings (ON/OFF per group)
// 3. Service availability and quotas
const result = await emailjs.sendEmail({
templateId: "template_456",
to: "[email protected]",
templateParams: { name: "John" },
// No serviceId needed - automatic selection from groups
});Framework Examples
React
import React, { useState } from "react";
import EmailJS from "@emailjs/sdk";
const ContactForm = () => {
const [emailjs] = useState(() =>
EmailJS.init({
publicKey: "your_public_key_here",
})
);
const [formData, setFormData] = useState({
to_name: "",
to_email: "",
message: "",
});
const handleSubmit = async (e) => {
e.preventDefault();
const result = await emailjs.sendEmail({
serviceId: "service_123",
templateId: "template_456",
to: formData.to_email,
templateParams: formData,
});
if (result.success) {
alert("Message sent!");
} else {
alert("Error: " + result.error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={formData.to_name}
onChange={(e) => setFormData({ ...formData, to_name: e.target.value })}
/>
<input
type="email"
placeholder="Email"
value={formData.to_email}
onChange={(e) => setFormData({ ...formData, to_email: e.target.value })}
/>
<textarea
placeholder="Message"
value={formData.message}
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
/>
<button type="submit">Send</button>
</form>
);
};Vue.js
<template>
<form @submit="handleSubmit">
<input v-model="formData.to_name" placeholder="Name" />
<input v-model="formData.to_email" placeholder="Email" />
<textarea v-model="formData.message" placeholder="Message" />
<button type="submit">Send</button>
</form>
</template>
<script>
import EmailJS from "@emailjs/sdk";
export default {
data() {
return {
emailjs: EmailJS.init({
publicKey: "your_public_key_here",
}),
formData: {
to_name: "",
to_email: "",
message: "",
},
};
},
methods: {
async handleSubmit(e) {
e.preventDefault();
const result = await this.emailjs.sendEmail({
serviceId: "service_123",
templateId: "template_456",
to: this.formData.to_email,
templateParams: this.formData,
});
if (result.success) {
alert("Message sent!");
} else {
alert("Error: " + result.error);
}
},
},
};
</script>Angular
import { Component } from "@angular/core";
import EmailJS from "@emailjs/sdk";
@Component({
selector: "app-contact-form",
template: `
<form (ngSubmit)="handleSubmit($event)">
<input [(ngModel)]="formData.to_name" placeholder="Name" />
<input [(ngModel)]="formData.to_email" placeholder="Email" />
<textarea [(ngModel)]="formData.message" placeholder="Message"></textarea>
<button type="submit">Send</button>
</form>
`,
})
export class ContactFormComponent {
private emailjs = EmailJS.init({
publicKey: "your_public_key_here",
});
formData = {
to_name: "",
to_email: "",
message: "",
};
async handleSubmit(e: Event) {
e.preventDefault();
const result = await this.emailjs.sendEmail({
serviceId: "service_123",
templateId: "template_456",
to: this.formData.to_email,
templateParams: this.formData,
});
if (result.success) {
alert("Message sent!");
} else {
alert("Error: " + result.error);
}
}
}Error Handling
try {
const result = await emailjs.sendEmail({
serviceId: "service_123",
to: "[email protected]",
subject: "Test Email",
message: "Hello World!",
});
if (result.success) {
console.log("Email sent:", result.messageId);
} else {
console.error("Email failed:", result.error);
}
} catch (error) {
console.error("SDK Error:", error.message);
}License
MIT License - see LICENSE file for details.
