Introduction
Learn the basics of @visulima/email
Last updated:
Introduction
This guide will help you get started with @visulima/email. We'll cover the core concepts and show you how to send your first email.
Core Concepts
@visulima/email is built around a few key concepts:
Mail Instance
The Mail class is the main entry point for sending emails. You create a Mail instance with a provider:
import { createMail } from "@visulima/email";
import { resendProvider } from "@visulima/email/providers/resend";
const mail = createMail(resendProvider({ apiKey: "re_xxx" }));Providers
Providers are responsible for actually sending emails. Each provider implements a common interface, allowing you to switch providers without changing your code.
import { resendProvider } from "@visulima/email/providers/resend";
import { smtpProvider } from "@visulima/email/providers/smtp";
// Use Resend
const resend = resendProvider({ apiKey: "re_xxx" });
// Or use SMTP
const smtp = smtpProvider({
host: "smtp.example.com",
port: 587,
user: "user@example.com",
password: "password",
});Mail Messages
Mail messages are built using the fluent MailMessage API:
import { MailMessage } from "@visulima/email";
const message = new MailMessage().to("user@example.com").from("sender@example.com").subject("Hello").html("<h1>Hello World</h1>");
const result = await mail.send(message);Basic Example
Here's a complete example of sending an email:
import { createMail } from "@visulima/email";
import { resendProvider } from "@visulima/email/providers/resend";
// 1. Create a provider
const resend = resendProvider({
apiKey: process.env.RESEND_API_KEY!,
});
// 2. Create a Mail instance
const mail = createMail(resend);
// Optional: Set default configuration for all emails
mail.setFrom({ email: "noreply@example.com", name: "My App" });
// 3. Build and send a message
import { MailMessage } from "@visulima/email";
const message = new MailMessage()
.to("user@example.com")
// .from() is optional if set via mail.setFrom()
.subject("Welcome!")
.html("<h1>Welcome to our service!</h1>")
.text("Welcome to our service!");
const result = await mail.send(message);
// 4. Handle the result
if (result.success) {
console.log("Email sent successfully:", result.data?.messageId);
} else {
console.error("Failed to send email:", result.error);
}Creating Drafts
You can create draft emails in EML (RFC 822) format without sending them:
import { writeFile } from "fs/promises";
const message = new MailMessage().to("user@example.com").from("sender@example.com").subject("Hello").html("<h1>Hello World</h1>");
// Create a draft in EML format (doesn't send)
const eml = await mail.draft(message);
// Save to file - can be opened by email clients
await writeFile("draft.eml", eml);Next Steps
- Configuration - Configure providers
- Sending Mail - Learn different ways to send emails
- Building Messages - Explore the message builder API