
Imap Smtp Email
- 1.8k installs
- Updated February 8, 2026
- boomsystel-code/openclaw-workspace
imap-smtp-email is an agent skill for reading and sending email via IMAP and SMTP CLI scripts across major providers.
About
The imap-smtp-email skill provides IMAP and SMTP email automation via Node.js CLI scripts for reading, searching, marking, and sending mail. Configuration uses .env with IMAP_HOST, SMTP_HOST, TLS settings, and credentials for Gmail, Outlook, 163.com, 126.com, QQ Mail, and other standard servers. IMAP commands include check, fetch, download attachments, search with unseen and date filters, mark-read, and list-mailboxes. SMTP commands cover send with HTML, attachments, CC and BCC, plus connection test. Security notes require app passwords for Gmail, authorization codes for 163.com, and .env in gitignore. Use when agents need programmatic inbox checks, email search, or outbound SMTP sending.
- IMAP check, fetch, search, mark-read, and attachment download commands.
- SMTP send with HTML, attachments, CC, BCC, and connection test.
- Provider table for Gmail, Outlook, 163, 126, QQ, and yeah.net.
- Env-based config: IMAP_HOST, SMTP_PORT, TLS, and credential vars.
- 163.com requires authorization code; Gmail needs app password with 2FA.
Imap Smtp Email by the numbers
- 1,846 all-time installs (skills.sh)
- +4 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #262 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
imap-smtp-email capabilities & compatibility
- Capabilities
- imap inbox check and search · attachment download · smtp send with html and attachments · multi provider configuration
- Pricing
- Bring your own API key
What imap-smtp-email says it does
Read and send email via IMAP/SMTP. Check for new/unread messages, fetch content, search mailboxes
For 163.com: use authorization code (授权码), not account password
npx skills add https://github.com/boomsystel-code/openclaw-workspace --skill imap-smtp-emailAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.8k |
|---|---|
| Last updated | February 8, 2026 |
| Repository | boomsystel-code/openclaw-workspace ↗ |
How do I check inbox, search mail, or send email with attachments via IMAP and SMTP?
Read, search, send, and manage email via IMAP and SMTP CLI scripts for Gmail, Outlook, and 163 providers.
Who is it for?
Developers automating email read, search, mark-read, and send workflows for Gmail, Outlook, or 163.
Skip if: Skip for OAuth-only email APIs or marketing campaign platforms without IMAP SMTP access.
When should I use this skill?
User mentions IMAP SMTP email, check unread mail, send email attachment, or mailbox search.
What you get
Working IMAP inbox checks, filtered searches, and SMTP sends using configured provider credentials.
- Inbox fetch output
- Mailbox search results
- Sent SMTP replies
By the numbers
- 8+ named mailbox providers including Gmail and Outlook
- 3 IMAP npm scripts: check, fetch, search
Files
IMAP/SMTP Email Tool
Read, search, and manage email via IMAP protocol. Send email via SMTP. Supports Gmail, Outlook, 163.com, vip.163.com, 126.com, vip.126.com, 188.com, vip.188.com, and any standard IMAP/SMTP server.
Configuration
Create .env in the skill folder or set environment variables:
# IMAP Configuration (receiving email)
IMAP_HOST=imap.gmail.com # Server hostname
IMAP_PORT=993 # Server port
IMAP_USER=your@email.com
IMAP_PASS=your_password
IMAP_TLS=true # Use TLS/SSL connection
IMAP_REJECT_UNAUTHORIZED=true # Set to false for self-signed certs
IMAP_MAILBOX=INBOX # Default mailbox
# SMTP Configuration (sending email)
SMTP_HOST=smtp.gmail.com # SMTP server hostname
SMTP_PORT=587 # SMTP port (587 for STARTTLS, 465 for SSL)
SMTP_SECURE=false # true for SSL (465), false for STARTTLS (587)
SMTP_USER=your@gmail.com # Your email address
SMTP_PASS=your_password # Your password or app password
SMTP_FROM=your@gmail.com # Default sender email (optional)
SMTP_REJECT_UNAUTHORIZED=true # Set to false for self-signed certsCommon Email Servers
| Provider | IMAP Host | IMAP Port | SMTP Host | SMTP Port |
|---|---|---|---|---|
| 163.com | imap.163.com | 993 | smtp.163.com | 465 |
| vip.163.com | imap.vip.163.com | 993 | smtp.vip.163.com | 465 |
| 126.com | imap.126.com | 993 | smtp.126.com | 465 |
| vip.126.com | imap.vip.126.com | 993 | smtp.vip.126.com | 465 |
| 188.com | imap.188.com | 993 | smtp.188.com | 465 |
| vip.188.com | imap.vip.188.com | 993 | smtp.vip.188.com | 465 |
| yeah.net | imap.yeah.net | 993 | smtp.yeah.net | 465 |
| Gmail | imap.gmail.com | 993 | smtp.gmail.com | 587 |
| Outlook | outlook.office365.com | 993 | smtp.office365.com | 587 |
| QQ Mail | imap.qq.com | 993 | smtp.qq.com | 587 |
Important for 163.com:
- Use authorization code (授权码), not account password
- Enable IMAP/SMTP in web settings first
IMAP Commands (Receiving Email)
check
Check for new/unread emails.
node scripts/imap.js check [--limit 10] [--mailbox INBOX] [--recent 2h]Options:
--limit <n>: Max results (default: 10)--mailbox <name>: Mailbox to check (default: INBOX)--recent <time>: Only show emails from last X time (e.g., 30m, 2h, 7d)
fetch
Fetch full email content by UID.
node scripts/imap.js fetch <uid> [--mailbox INBOX]download
Download all attachments from an email, or a specific attachment.
node scripts/imap.js download <uid> [--mailbox INBOX] [--dir <path>] [--file <filename>]Options:
--mailbox <name>: Mailbox (default: INBOX)--dir <path>: Output directory (default: current directory)--file <filename>: Download only the specified attachment (default: download all)
search
Search emails with filters.
node scripts/imap.js search [options]
Options:
--unseen Only unread messages
--seen Only read messages
--from <email> From address contains
--subject <text> Subject contains
--recent <time> From last X time (e.g., 30m, 2h, 7d)
--since <date> After date (YYYY-MM-DD)
--before <date> Before date (YYYY-MM-DD)
--limit <n> Max results (default: 20)
--mailbox <name> Mailbox to search (default: INBOX)mark-read / mark-unread
Mark message(s) as read or unread.
node scripts/imap.js mark-read <uid> [uid2 uid3...]
node scripts/imap.js mark-unread <uid> [uid2 uid3...]list-mailboxes
List all available mailboxes/folders.
node scripts/imap.js list-mailboxesSMTP Commands (Sending Email)
send
Send email via SMTP.
node scripts/smtp.js send --to <email> --subject <text> [options]Required:
--to <email>: Recipient (comma-separated for multiple)--subject <text>: Email subject, or--subject-file <file>
Optional:
--body <text>: Plain text body--html: Send body as HTML--body-file <file>: Read body from file--html-file <file>: Read HTML from file--cc <email>: CC recipients--bcc <email>: BCC recipients--attach <file>: Attachments (comma-separated)--from <email>: Override default sender
Examples:
# Simple text email
node scripts/smtp.js send --to recipient@example.com --subject "Hello" --body "World"
# HTML email
node scripts/smtp.js send --to recipient@example.com --subject "Newsletter" --html --body "<h1>Welcome</h1>"
# Email with attachment
node scripts/smtp.js send --to recipient@example.com --subject "Report" --body "Please find attached" --attach report.pdf
# Multiple recipients
node scripts/smtp.js send --to "a@example.com,b@example.com" --cc "c@example.com" --subject "Update" --body "Team update"test
Test SMTP connection by sending a test email to yourself.
node scripts/smtp.js testDependencies
npm installSecurity Notes
- Store credentials in
.env(add to.gitignore) - For Gmail: use App Password if 2FA is enabled
- For 163.com: use authorization code (授权码), not account password
Troubleshooting
Connection timeout:
- Verify server is running and accessible
- Check host/port configuration
Authentication failed:
- Verify username (usually full email address)
- Check password is correct
- For 163.com: use authorization code, not account password
- For Gmail: use App Password if 2FA enabled
TLS/SSL errors:
- Match
IMAP_TLS/SMTP_SECUREsetting to server requirements - For self-signed certs: set
IMAP_REJECT_UNAUTHORIZED=falseorSMTP_REJECT_UNAUTHORIZED=false
{
"ownerId": "kn70j4ejnwqjpykvwwvgymmdcd8055qp",
"slug": "imap-smtp-email",
"version": "0.0.2",
"publishedAt": 1770100563279
}{
"version": 1,
"registry": "https://clawhub.ai",
"slug": "imap-smtp-email",
"installedVersion": "0.0.2",
"installedAt": 1770468570002
}
{
"name": "imap-smtp-email-skill",
"version": "1.0.0",
"description": "IMAP/SMTP email tool for Claude. Works with Gmail, Outlook, 163.com, vip.163.com, 126.com, vip.126.com, 188.com, vip.188.com, and any standard IMAP/SMTP server.",
"main": "scripts/imap.js",
"scripts": {
"check": "node scripts/imap.js check",
"fetch": "node scripts/imap.js fetch",
"search": "node scripts/imap.js search"
},
"dependencies": {
"dotenv": "^16.6.1",
"imap": "^0.8.19",
"imap-simple": "^5.1.0",
"mailparser": "^3.9.3",
"nodemailer": "^7.0.13"
},
"keywords": [
"imap",
"smtp",
"email",
"163.com",
"126.com",
"188.com",
"gmail",
"outlook",
"skill"
],
"author": "NetEase",
"license": "MIT"
}
IMAP/SMTP Email Skill
Read and send email via IMAP/SMTP protocol. Works with any IMAP/SMTP server including Gmail, Outlook, 163.com, vip.163.com, 126.com, vip.126.com, 188.com, and vip.188.com.
Quick Setup
1. Create `.env` file with your credentials:
# IMAP Configuration (receiving email)
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
IMAP_USER=your@gmail.com
IMAP_PASS=your_app_password
IMAP_TLS=true
IMAP_MAILBOX=INBOX
# SMTP Configuration (sending email)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your@gmail.com
SMTP_PASS=your_app_password
SMTP_FROM=your@gmail.com2. Install dependencies:
npm install3. Test the connection:
node scripts/imap.js check
node scripts/smtp.js testIMAP Commands (Receiving Email)
Check for new emails
node scripts/imap.js check --limit 10
node scripts/imap.js check --recent 2h # Last 2 hours
node scripts/imap.js check --recent 30m # Last 30 minutesFetch specific email
node scripts/imap.js fetch <uid>Search emails
node scripts/imap.js search --unseen
node scripts/imap.js search --from "sender@example.com"
node scripts/imap.js search --subject "important"
node scripts/imap.js search --recent 24hMark as read/unread
node scripts/imap.js mark-read <uid>
node scripts/imap.js mark-unread <uid>List mailboxes
node scripts/imap.js list-mailboxesSMTP Commands (Sending Email)
Test SMTP connection
node scripts/smtp.js testSend email
# Simple text email
node scripts/smtp.js send --to recipient@example.com --subject "Hello" --body "World"
# HTML email
node scripts/smtp.js send --to recipient@example.com --subject "Newsletter" --html --body "<h1>Welcome</h1>"
# Email with attachment
node scripts/smtp.js send --to recipient@example.com --subject "Report" --body "Please find attached" --attach report.pdf
# Multiple recipients
node scripts/smtp.js send --to "a@example.com,b@example.com" --cc "c@example.com" --subject "Update" --body "Team update"Common Email Servers
| Provider | IMAP Host | IMAP Port | SMTP Host | SMTP Port |
|---|---|---|---|---|
| 163.com | imap.163.com | 993 | smtp.163.com | 465 |
| vip.163.com | imap.vip.163.com | 993 | smtp.vip.163.com | 465 |
| 126.com | imap.126.com | 993 | smtp.126.com | 465 |
| vip.126.com | imap.vip.126.com | 993 | smtp.vip.126.com | 465 |
| 188.com | imap.188.com | 993 | smtp.188.com | 465 |
| vip.188.com | imap.vip.188.com | 993 | smtp.vip.188.com | 465 |
| yeah.net | imap.yeah.net | 993 | smtp.yeah.net | 465 |
| Gmail | imap.gmail.com | 993 | smtp.gmail.com | 587 |
| Outlook | outlook.office365.com | 993 | smtp.office365.com | 587 |
| QQ Mail | imap.qq.com | 993 | smtp.qq.com | 587 |
Important for 163.com:
- Use authorization code (授权码), not account password
- Enable IMAP/SMTP in web settings first
Configuration Options
IMAP:
IMAP_HOST- Server hostnameIMAP_PORT- Server portIMAP_USER- Your email addressIMAP_PASS- Your password or app-specific passwordIMAP_TLS- Use TLS (true for SSL, false for STARTTLS)IMAP_REJECT_UNAUTHORIZED- Accept self-signed certsIMAP_MAILBOX- Default mailbox (INBOX)
SMTP:
SMTP_HOST- Server hostnameSMTP_PORT- Server port (587 for STARTTLS, 465 for SSL)SMTP_SECURE- true for SSL (465), false for STARTTLS (587)SMTP_USER- Your email addressSMTP_PASS- Your password or app-specific passwordSMTP_FROM- Default sender email (optional)SMTP_REJECT_UNAUTHORIZED- Accept self-signed certs
Troubleshooting
Connection errors:
- Verify IMAP/SMTP server is running and accessible
- Check host/port settings in
.env
Authentication failed:
- For Gmail: Use App Password (not account password if 2FA enabled)
- For 163.com: Use authorization code (授权码), not account password
TLS/SSL errors:
- For self-signed certs: Set
IMAP_REJECT_UNAUTHORIZED=falseorSMTP_REJECT_UNAUTHORIZED=false
Files
SKILL.md- Skill documentationscripts/imap.js- IMAP CLI toolscripts/smtp.js- SMTP CLI toolpackage.json- Node.js dependencies.env- Your credentials (create manually)
#!/usr/bin/env node
/**
* IMAP Email CLI
* Works with any standard IMAP server (Gmail, ProtonMail Bridge, Fastmail, etc.)
* Supports IMAP ID extension (RFC 2971) for 163.com and other servers
*/
const Imap = require('imap');
const { simpleParser } = require('mailparser');
const path = require('path');
const fs = require('fs');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
// IMAP ID information for 163.com compatibility
const IMAP_ID = {
name: 'moltbot',
version: '0.0.1',
vendor: 'netease',
'support-email': 'kefu@188.com'
};
const DEFAULT_MAILBOX = process.env.IMAP_MAILBOX || 'INBOX';
// Parse command-line arguments
function parseArgs() {
const args = process.argv.slice(2);
const command = args[0];
const options = {};
const positional = [];
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('--')) {
const key = arg.slice(2);
const value = args[i + 1];
options[key] = value || true;
if (value && !value.startsWith('--')) i++;
} else {
positional.push(arg);
}
}
return { command, options, positional };
}
// Create IMAP connection config
function createImapConfig() {
return {
user: process.env.IMAP_USER,
password: process.env.IMAP_PASS,
host: process.env.IMAP_HOST || '127.0.0.1',
port: parseInt(process.env.IMAP_PORT) || 1143,
tls: process.env.IMAP_TLS === 'true',
tlsOptions: {
rejectUnauthorized: process.env.IMAP_REJECT_UNAUTHORIZED !== 'false',
},
connTimeout: 10000,
authTimeout: 10000,
};
}
// Connect to IMAP server with ID support
async function connect() {
const config = createImapConfig();
if (!config.user || !config.password) {
throw new Error('Missing IMAP_USER or IMAP_PASS environment variables');
}
return new Promise((resolve, reject) => {
const imap = new Imap(config);
imap.once('ready', () => {
// Send IMAP ID command for 163.com compatibility
if (typeof imap.id === 'function') {
imap.id(IMAP_ID, (err) => {
if (err) {
console.warn('Warning: IMAP ID command failed:', err.message);
}
resolve(imap);
});
} else {
// ID not supported, continue without it
resolve(imap);
}
});
imap.once('error', (err) => {
reject(new Error(`IMAP connection failed: ${err.message}`));
});
imap.connect();
});
}
// Open mailbox and return promise
function openBox(imap, mailbox, readOnly = false) {
return new Promise((resolve, reject) => {
imap.openBox(mailbox, readOnly, (err, box) => {
if (err) reject(err);
else resolve(box);
});
});
}
// Search for messages
function searchMessages(imap, criteria, fetchOptions) {
return new Promise((resolve, reject) => {
imap.search(criteria, (err, results) => {
if (err) {
reject(err);
return;
}
if (!results || results.length === 0) {
resolve([]);
return;
}
const fetch = imap.fetch(results, fetchOptions);
const messages = [];
fetch.on('message', (msg) => {
const parts = [];
msg.on('body', (stream, info) => {
let buffer = '';
stream.on('data', (chunk) => {
buffer += chunk.toString('utf8');
});
stream.once('end', () => {
parts.push({ which: info.which, body: buffer });
});
});
msg.once('attributes', (attrs) => {
parts.forEach((part) => {
part.attributes = attrs;
});
});
msg.once('end', () => {
if (parts.length > 0) {
messages.push(parts[0]);
}
});
});
fetch.once('error', (err) => {
reject(err);
});
fetch.once('end', () => {
resolve(messages);
});
});
});
}
// Parse email from raw buffer
async function parseEmail(bodyStr, includeAttachments = false) {
const parsed = await simpleParser(bodyStr);
return {
from: parsed.from?.text || 'Unknown',
to: parsed.to?.text,
subject: parsed.subject || '(no subject)',
date: parsed.date,
text: parsed.text,
html: parsed.html,
snippet: parsed.text
? parsed.text.slice(0, 200)
: (parsed.html ? parsed.html.slice(0, 200).replace(/<[^>]*>/g, '') : ''),
attachments: parsed.attachments?.map((a) => ({
filename: a.filename,
contentType: a.contentType,
size: a.size,
content: includeAttachments ? a.content : undefined,
cid: a.cid,
})),
};
}
// Check for new/unread emails
async function checkEmails(mailbox = DEFAULT_MAILBOX, limit = 10, recentTime = null, unreadOnly = false) {
const imap = await connect();
try {
await openBox(imap, mailbox);
// Build search criteria
const searchCriteria = unreadOnly ? ['UNSEEN'] : ['ALL'];
if (recentTime) {
const sinceDate = parseRelativeTime(recentTime);
searchCriteria.push(['SINCE', sinceDate]);
}
// Fetch messages sorted by date (newest first)
const fetchOptions = {
bodies: [''],
markSeen: false,
};
const messages = await searchMessages(imap, searchCriteria, fetchOptions);
// Sort by date (newest first) - parse from message attributes
const sortedMessages = messages.sort((a, b) => {
const dateA = a.attributes.date ? new Date(a.attributes.date) : new Date(0);
const dateB = b.attributes.date ? new Date(b.attributes.date) : new Date(0);
return dateB - dateA;
}).slice(0, limit);
const results = [];
for (const item of sortedMessages) {
const bodyStr = item.body;
const parsed = await parseEmail(bodyStr);
results.push({
uid: item.attributes.uid,
...parsed,
flags: item.attributes.flags,
});
}
return results;
} finally {
imap.end();
}
}
// Fetch full email by UID
async function fetchEmail(uid, mailbox = DEFAULT_MAILBOX) {
const imap = await connect();
try {
await openBox(imap, mailbox);
const searchCriteria = [['UID', uid]];
const fetchOptions = {
bodies: [''],
markSeen: false,
};
const messages = await searchMessages(imap, searchCriteria, fetchOptions);
if (messages.length === 0) {
throw new Error(`Message UID ${uid} not found`);
}
const item = messages[0];
const parsed = await parseEmail(item.body);
return {
uid: item.attributes.uid,
...parsed,
flags: item.attributes.flags,
};
} finally {
imap.end();
}
}
// Download attachments from email
async function downloadAttachments(uid, mailbox = DEFAULT_MAILBOX, outputDir = '.', specificFilename = null) {
const imap = await connect();
try {
await openBox(imap, mailbox);
const searchCriteria = [['UID', uid]];
const fetchOptions = {
bodies: [''],
markSeen: false,
};
const messages = await searchMessages(imap, searchCriteria, fetchOptions);
if (messages.length === 0) {
throw new Error(`Message UID ${uid} not found`);
}
const item = messages[0];
const parsed = await parseEmail(item.body, true);
if (!parsed.attachments || parsed.attachments.length === 0) {
return {
uid,
downloaded: [],
message: 'No attachments found',
};
}
// Create output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const downloaded = [];
for (const attachment of parsed.attachments) {
// If specificFilename is provided, only download matching attachment
if (specificFilename && attachment.filename !== specificFilename) {
continue;
}
if (attachment.content) {
const filePath = path.join(outputDir, attachment.filename);
fs.writeFileSync(filePath, attachment.content);
downloaded.push({
filename: attachment.filename,
path: filePath,
size: attachment.size,
});
}
}
// If specific file was requested but not found
if (specificFilename && downloaded.length === 0) {
const availableFiles = parsed.attachments.map(a => a.filename).join(', ');
return {
uid,
downloaded: [],
message: `File "${specificFilename}" not found. Available attachments: ${availableFiles}`,
};
}
return {
uid,
downloaded,
message: `Downloaded ${downloaded.length} attachment(s)`,
};
} finally {
imap.end();
}
}
// Parse relative time (e.g., "2h", "30m", "7d") to Date
function parseRelativeTime(timeStr) {
const match = timeStr.match(/^(\d+)(m|h|d)$/);
if (!match) {
throw new Error('Invalid time format. Use: 30m, 2h, 7d');
}
const value = parseInt(match[1]);
const unit = match[2];
const now = new Date();
switch (unit) {
case 'm': // minutes
return new Date(now.getTime() - value * 60 * 1000);
case 'h': // hours
return new Date(now.getTime() - value * 60 * 60 * 1000);
case 'd': // days
return new Date(now.getTime() - value * 24 * 60 * 60 * 1000);
default:
throw new Error('Unknown time unit');
}
}
// Search emails with criteria
async function searchEmails(options) {
const imap = await connect();
try {
const mailbox = options.mailbox || DEFAULT_MAILBOX;
await openBox(imap, mailbox);
const criteria = [];
if (options.unseen) criteria.push('UNSEEN');
if (options.seen) criteria.push('SEEN');
if (options.from) criteria.push(['FROM', options.from]);
if (options.subject) criteria.push(['SUBJECT', options.subject]);
// Handle relative time (--recent 2h)
if (options.recent) {
const sinceDate = parseRelativeTime(options.recent);
criteria.push(['SINCE', sinceDate]);
} else {
// Handle absolute dates
if (options.since) criteria.push(['SINCE', options.since]);
if (options.before) criteria.push(['BEFORE', options.before]);
}
// Default to all if no criteria
if (criteria.length === 0) criteria.push('ALL');
const fetchOptions = {
bodies: [''],
markSeen: false,
};
const messages = await searchMessages(imap, criteria, fetchOptions);
const limit = parseInt(options.limit) || 20;
const results = [];
// Sort by date (newest first)
const sortedMessages = messages.sort((a, b) => {
const dateA = a.attributes.date ? new Date(a.attributes.date) : new Date(0);
const dateB = b.attributes.date ? new Date(b.attributes.date) : new Date(0);
return dateB - dateA;
}).slice(0, limit);
for (const item of sortedMessages) {
const parsed = await parseEmail(item.body);
results.push({
uid: item.attributes.uid,
...parsed,
flags: item.attributes.flags,
});
}
return results;
} finally {
imap.end();
}
}
// Mark message(s) as read
async function markAsRead(uids, mailbox = DEFAULT_MAILBOX) {
const imap = await connect();
try {
await openBox(imap, mailbox);
return new Promise((resolve, reject) => {
imap.addFlags(uids, '\\Seen', (err) => {
if (err) reject(err);
else resolve({ success: true, uids, action: 'marked as read' });
});
});
} finally {
imap.end();
}
}
// Mark message(s) as unread
async function markAsUnread(uids, mailbox = DEFAULT_MAILBOX) {
const imap = await connect();
try {
await openBox(imap, mailbox);
return new Promise((resolve, reject) => {
imap.delFlags(uids, '\\Seen', (err) => {
if (err) reject(err);
else resolve({ success: true, uids, action: 'marked as unread' });
});
});
} finally {
imap.end();
}
}
// List all mailboxes
async function listMailboxes() {
const imap = await connect();
try {
return new Promise((resolve, reject) => {
imap.getBoxes((err, boxes) => {
if (err) reject(err);
else resolve(formatMailboxTree(boxes));
});
});
} finally {
imap.end();
}
}
// Format mailbox tree recursively
function formatMailboxTree(boxes, prefix = '') {
const result = [];
for (const [name, info] of Object.entries(boxes)) {
const fullName = prefix ? `${prefix}${info.delimiter}${name}` : name;
result.push({
name: fullName,
delimiter: info.delimiter,
attributes: info.attribs,
});
if (info.children) {
result.push(...formatMailboxTree(info.children, fullName));
}
}
return result;
}
// Main CLI handler
async function main() {
const { command, options, positional } = parseArgs();
try {
let result;
switch (command) {
case 'check':
result = await checkEmails(
options.mailbox || DEFAULT_MAILBOX,
parseInt(options.limit) || 10,
options.recent || null,
options.unseen === 'true' // if --unseen is set, only get unread messages
);
break;
case 'fetch':
if (!positional[0]) {
throw new Error('UID required: node imap.js fetch <uid>');
}
result = await fetchEmail(positional[0], options.mailbox);
break;
case 'download':
if (!positional[0]) {
throw new Error('UID required: node imap.js download <uid>');
}
result = await downloadAttachments(positional[0], options.mailbox, options.dir || '.', options.file || null);
break;
case 'search':
result = await searchEmails(options);
break;
case 'mark-read':
if (positional.length === 0) {
throw new Error('UID(s) required: node imap.js mark-read <uid> [uid2...]');
}
result = await markAsRead(positional, options.mailbox);
break;
case 'mark-unread':
if (positional.length === 0) {
throw new Error('UID(s) required: node imap.js mark-unread <uid> [uid2...]');
}
result = await markAsUnread(positional, options.mailbox);
break;
case 'list-mailboxes':
result = await listMailboxes();
break;
default:
console.error('Unknown command:', command);
console.error('Available commands: check, fetch, download, search, mark-read, mark-unread, list-mailboxes');
process.exit(1);
}
console.log(JSON.stringify(result, null, 2));
} catch (err) {
console.error('Error:', err.message);
process.exit(1);
}
}
main();
#!/usr/bin/env node
/**
* SMTP Email CLI
* Send email via SMTP protocol. Works with Gmail, Outlook, 163.com, and any standard SMTP server.
* Supports attachments, HTML content, and multiple recipients.
*/
const nodemailer = require('nodemailer');
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
// Parse command-line arguments
function parseArgs() {
const args = process.argv.slice(2);
const command = args[0];
const options = {};
const positional = [];
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (arg.startsWith('--')) {
const key = arg.slice(2);
const value = args[i + 1];
options[key] = value || true;
if (value && !value.startsWith('--')) i++;
} else {
positional.push(arg);
}
}
return { command, options, positional };
}
// Create SMTP transporter
function createTransporter() {
const config = {
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT) || 587,
secure: process.env.SMTP_SECURE === 'true', // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
tls: {
rejectUnauthorized: process.env.SMTP_REJECT_UNAUTHORIZED !== 'false',
},
};
if (!config.host || !config.auth.user || !config.auth.pass) {
throw new Error('Missing SMTP configuration. Please set SMTP_HOST, SMTP_USER, and SMTP_PASS in .env');
}
return nodemailer.createTransport(config);
}
// Send email
async function sendEmail(options) {
const transporter = createTransporter();
// Verify connection
try {
await transporter.verify();
console.error('SMTP server is ready to send');
} catch (err) {
throw new Error(`SMTP connection failed: ${err.message}`);
}
const mailOptions = {
from: options.from || process.env.SMTP_FROM || process.env.SMTP_USER,
to: options.to,
cc: options.cc || undefined,
bcc: options.bcc || undefined,
subject: options.subject || '(no subject)',
text: options.text || undefined,
html: options.html || undefined,
attachments: options.attachments || [],
};
// If neither text nor html provided, use default text
if (!mailOptions.text && !mailOptions.html) {
mailOptions.text = options.body || '';
}
const info = await transporter.sendMail(mailOptions);
return {
success: true,
messageId: info.messageId,
response: info.response,
to: mailOptions.to,
};
}
// Read file content for attachments
function readAttachment(filePath) {
const fs = require('fs');
if (!fs.existsSync(filePath)) {
throw new Error(`Attachment file not found: ${filePath}`);
}
return {
filename: path.basename(filePath),
path: path.resolve(filePath),
};
}
// Send email with file content
async function sendEmailWithContent(options) {
// Handle attachments
if (options.attach) {
const attachFiles = options.attach.split(',').map(f => f.trim());
options.attachments = attachFiles.map(f => readAttachment(f));
}
return await sendEmail(options);
}
// Test SMTP connection
async function testConnection() {
const transporter = createTransporter();
try {
await transporter.verify();
const info = await transporter.sendMail({
from: process.env.SMTP_FROM || process.env.SMTP_USER,
to: process.env.SMTP_USER, // Send to self
subject: 'SMTP Connection Test',
text: 'This is a test email from the IMAP/SMTP email skill.',
html: '<p>This is a <strong>test email</strong> from the IMAP/SMTP email skill.</p>',
});
return {
success: true,
message: 'SMTP connection successful',
messageId: info.messageId,
};
} catch (err) {
throw new Error(`SMTP test failed: ${err.message}`);
}
}
// Main CLI handler
async function main() {
const { command, options, positional } = parseArgs();
try {
let result;
switch (command) {
case 'send':
if (!options.to) {
throw new Error('Missing required option: --to <email>');
}
if (!options.subject && !options['subject-file']) {
throw new Error('Missing required option: --subject <text> or --subject-file <file>');
}
// Read subject from file if specified
if (options['subject-file']) {
const fs = require('fs');
options.subject = fs.readFileSync(options['subject-file'], 'utf8').trim();
}
// Read body from file if specified
if (options['body-file']) {
const fs = require('fs');
const content = fs.readFileSync(options['body-file'], 'utf8');
if (options['body-file'].endsWith('.html') || options.html) {
options.html = content;
} else {
options.text = content;
}
} else if (options['html-file']) {
const fs = require('fs');
options.html = fs.readFileSync(options['html-file'], 'utf8');
} else if (options.body) {
options.text = options.body;
}
result = await sendEmailWithContent(options);
break;
case 'test':
result = await testConnection();
break;
default:
console.error('Unknown command:', command);
console.error('Available commands: send, test');
console.error('\nUsage:');
console.error(' send --to <email> --subject <text> [--body <text>] [--html] [--cc <email>] [--bcc <email>] [--attach <file>]');
console.error(' send --to <email> --subject <text> --body-file <file> [--html-file <file>] [--attach <file>]');
console.error(' test Test SMTP connection');
process.exit(1);
}
console.log(JSON.stringify(result, null, 2));
} catch (err) {
console.error('Error:', err.message);
process.exit(1);
}
}
main();
#!/bin/bash
# IMAP/SMTP Email Skill Setup Helper
echo "================================"
echo " IMAP/SMTP Email Skill Setup"
echo "================================"
echo ""
echo "This script will help you create a .env file with your email credentials."
echo ""
# Prompt for email provider
echo "Select your email provider:"
echo " 1) Gmail"
echo " 2) Outlook"
echo " 3) 163.com"
echo " 4) vip.163.com"
echo " 5) 126.com"
echo " 6) vip.126.com"
echo " 7) 188.com"
echo " 8) vip.188.com"
echo " 9) yeah.net"
echo " 10) QQ Mail"
echo " 11) Custom"
echo ""
read -p "Enter choice (1-11): " PROVIDER_CHOICE
case $PROVIDER_CHOICE in
1)
IMAP_HOST="imap.gmail.com"
IMAP_PORT="993"
SMTP_HOST="smtp.gmail.com"
SMTP_PORT="587"
SMTP_SECURE="false"
IMAP_TLS="true"
;;
2)
IMAP_HOST="outlook.office365.com"
IMAP_PORT="993"
SMTP_HOST="smtp.office365.com"
SMTP_PORT="587"
SMTP_SECURE="false"
IMAP_TLS="true"
;;
3)
IMAP_HOST="imap.163.com"
IMAP_PORT="993"
SMTP_HOST="smtp.163.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
4)
IMAP_HOST="imap.vip.163.com"
IMAP_PORT="993"
SMTP_HOST="smtp.vip.163.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
5)
IMAP_HOST="imap.126.com"
IMAP_PORT="993"
SMTP_HOST="smtp.126.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
6)
IMAP_HOST="imap.vip.126.com"
IMAP_PORT="993"
SMTP_HOST="smtp.vip.126.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
7)
IMAP_HOST="imap.188.com"
IMAP_PORT="993"
SMTP_HOST="smtp.188.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
8)
IMAP_HOST="imap.vip.188.com"
IMAP_PORT="993"
SMTP_HOST="smtp.vip.188.com"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
9)
IMAP_HOST="imap.yeah.net"
IMAP_PORT="993"
SMTP_HOST="smtp.yeah.net"
SMTP_PORT="465"
SMTP_SECURE="true"
IMAP_TLS="true"
;;
10)
IMAP_HOST="imap.qq.com"
IMAP_PORT="993"
SMTP_HOST="smtp.qq.com"
SMTP_PORT="587"
SMTP_SECURE="false"
IMAP_TLS="true"
;;
11)
read -p "IMAP Host: " IMAP_HOST
read -p "IMAP Port: " IMAP_PORT
read -p "SMTP Host: " SMTP_HOST
read -p "SMTP Port: " SMTP_PORT
read -p "Use TLS for IMAP? (true/false): " IMAP_TLS
read -p "Use SSL for SMTP? (true/false): " SMTP_SECURE
;;
*)
echo "Invalid choice"
exit 1
;;
esac
echo ""
read -p "Email address: " EMAIL
read -s -p "Password / App Password / Authorization Code: " PASSWORD
echo ""
if [ -z "$REJECT_UNAUTHORIZED" ]; then
read -p "Accept self-signed certificates? (y/n): " ACCEPT_CERT
if [ "$ACCEPT_CERT" = "y" ]; then
REJECT_UNAUTHORIZED="false"
else
REJECT_UNAUTHORIZED="true"
fi
fi
# Create .env file
cat > .env << EOF
# IMAP Configuration
IMAP_HOST=$IMAP_HOST
IMAP_PORT=$IMAP_PORT
IMAP_USER=$EMAIL
IMAP_PASS=$PASSWORD
IMAP_TLS=$IMAP_TLS
IMAP_REJECT_UNAUTHORIZED=$REJECT_UNAUTHORIZED
IMAP_MAILBOX=INBOX
# SMTP Configuration
SMTP_HOST=$SMTP_HOST
SMTP_PORT=$SMTP_PORT
SMTP_SECURE=$SMTP_SECURE
SMTP_USER=$EMAIL
SMTP_PASS=$PASSWORD
SMTP_FROM=$EMAIL
SMTP_REJECT_UNAUTHORIZED=$REJECT_UNAUTHORIZED
EOF
echo ""
echo "✅ Created .env file"
echo ""
echo "Testing connections..."
echo ""
# Test IMAP connection
echo "Testing IMAP..."
if node scripts/imap.js list-mailboxes >/dev/null 2>&1; then
echo "✅ IMAP connection successful!"
else
echo "❌ IMAP connection test failed"
echo " Please check your credentials and settings"
fi
# Test SMTP connection
echo ""
echo "Testing SMTP..."
if node scripts/smtp.js test >/dev/null 2>&1; then
echo "✅ SMTP connection successful!"
else
echo "❌ SMTP connection test failed"
echo " Please check your credentials and settings"
fi
echo ""
echo "Setup complete! Try:"
echo " node scripts/imap.js check"
echo " node scripts/smtp.js send --to recipient@example.com --subject Test --body 'Hello World'"
Related skills
How it compares
Use this for agent mailbox read and reply; use a transactional email API skill for outbound product email at scale.
FAQ
Which providers are supported?
Any standard IMAP SMTP server including Gmail, Outlook, 163.com, 126.com, QQ Mail, and yeah.net.
How is email configured?
Set IMAP and SMTP host, port, user, password, and TLS flags in a .env file in the skill folder.
Is imap-smtp-email safe to install?
Review the Security Audits panel on this page before installing in production.