npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@redonvn/hotmail-mail-sdk

v0.1.0

Published

TypeScript SDK chuẩn hóa cho Hotmail / Outlook / Microsoft Mail API (OAuth2 Token Rotation, Graph API sendMail & SMTP XOAUTH2)

Readme

@redonvn/hotmail-mail-sdk

Bộ TypeScript SDK hoàn chỉnh, mạnh mẽ và chuẩn hóa dành cho Microsoft Hotmail, Outlook và Live Mail qua Microsoft OAuth 2.0 & Graph API v1.0, hỗ trợ toàn diện cơ chế Token Rotation (Xoay vòng Refresh Token), Quản lý Thread / Hội thoại, Gửi / Nhận Email, File đính kèm lớn (Upload Session), Thư mục & Rules, Webhook Realtime và tích hợp chuẩn SMTP XOAUTH2.

TypeScript License: MIT Node.js


🌟 Tính Năng Toàn Diện Của SDK

  1. Quản lý Token Xoay Vòng (Token Rotation):
    • Microsoft cấp refresh_token mới sau mỗi lần đổi token. SDK tự động bắt token xoay vòng và cung cấp hook onTokenRefresh để lưu ngay vào Database.
    • Tự động làm mới access_token khi hết hạn hoặc khi nhận mã lỗi 401.
  2. Quản lý Email & Luồng Hội Thoại (Messages & Threads):
    • Gửi email: Hỗ trợ HTML, Text, CC, BCC, Reply-To, Mức độ ưu tiên (importance), File đính kèm.
    • Mail gửi đi & Mail nhắn đến: listSent(), listReceived(), tìm kiếm từ khóa, phân trang, lọc OData.
    • Chuỗi hội thoại (Threads): getConversationThread(conversationId) gom tất cả email trong một cuộc trò chuyện theo trình tự thời gian.
    • Tương tác email: Trả lời (reply, replyAll), Chuyển tiếp (forward), Đánh dấu đã đọc (markAsRead), Gắn cờ (flagMessage), Di chuyển (moveMessage), Sao chép (copyMessage).
  3. Quản lý Thư nháp (Drafts):
    • Tạo thư nháp (createDraft), Cập nhật thư nháp (updateDraft), Bấm gửi thư nháp (sendDraft).
  4. File đính kèm lớn (Upload Session):
    • Hỗ trợ file nhỏ (< 3MB) trực tiếp qua Base64/Buffer.
    • Hỗ trợ file dung lượng lớn (3MB - 150MB) bằng cơ chế chia nhỏ chunk 320 KiB tự động (uploadLargeAttachment).
  5. Đồng bộ thông minh (Delta Sync):
    • getDeltaMessages() chỉ lấy về những email mới đến, bị sửa hoặc bị xóa kể từ lần kiểm tra trước (trả kèm link @odata.deltaLink). Thích hợp 100% cho Bot và CronJob.
  6. Thư mục hòm thư & Quy tắc tự động (Folders & Inbox Rules):
    • CRUD thư mục hòm thư (listFolders, createFolder, updateFolder, deleteFolder).
    • CRUD quy tắc phân loại thư tự động (listRules, createRule, deleteRule).
  7. Webhook Thông báo Thời gian thực (Push Subscriptions):
    • Đăng ký nhận thông báo realtime (createSubscription, renewSubscription, deleteSubscription).
    • Tích hợp sẵn helper xử lý Handshake (handleValidationHandshake) và xác thực an toàn clientState.
  8. Tương thích ngược với SMTP XOAUTH2 (Cổng 587):
    • Sinh cấu hình transporter 100% tương thích với nodemailer hoặc sinh chuỗi SASL XOAUTH2 Base64.
  9. Zero Dependencies:
    • Chạy trực tiếp trên Node 18+, Bun, Next.js, Cloudflare Workers, Edge Runtime.

📦 Cài Đặt

npm install @redonvn/hotmail-mail-sdk
# hoặc
pnpm add @redonvn/hotmail-mail-sdk
# hoặc
yarn add @redonvn/hotmail-mail-sdk

🚀 Hướng Dẫn Sử Dụng Chi Tiết

1. Khởi tạo Client

Định dạng tài khoản thường gặp: email | password | refresh_token | client_id | recovery_email

import { HotmailClient } from '@redonvn/hotmail-mail-sdk';

const client = new HotmailClient({
  userEmail: '[email protected]',
  refreshToken: 'M.C518_BL2...', // Refresh Token của bạn
  clientId: '9e5f94bc-e8a4-4e73-b8be-63364c29d753', // Mặc định nếu không truyền
  
  // Hook bắt buộc nên có: Lưu Refresh Token mới khi Microsoft xoay vòng token
  onTokenRefresh: async (tokens) => {
    console.log('Access token mới:', tokens.accessToken);
    console.log('Refresh token mới xoay vòng:', tokens.refreshToken);
    console.log('Thời điểm hết hạn:', tokens.expiresAt);
    
    // Cập nhật tokens.refreshToken vào Database của bạn!
    // await db.accounts.update({ email: '...' }, { refreshToken: tokens.refreshToken });
  }
});

2. Gửi Email (Microsoft Graph API)

await client.send({
  to: '[email protected]',
  subject: 'Thông báo kích hoạt tài khoản thành công',
  html: `
    <h2>Xin chào Quý khách!</h2>
    <p>Tài khoản của bạn đã được kích hoạt thành công trên hệ thống.</p>
  `,
  cc: ['[email protected]'],
  importance: 'high',
  attachments: [
    {
      filename: 'hop-dong.pdf',
      content: pdfBuffer, // Buffer hoặc chuỗi Base64
      contentType: 'application/pdf',
    }
  ],
});

3. Lấy Danh Sách Mail Đến, Mail Gửi Đi & Chuỗi Hội Thoại (Threads)

// 1. Lấy danh sách email nhắn đến (Inbox)
const inbox = await client.mail.listReceived({
  top: 10,
  select: ['id', 'subject', 'from', 'receivedDateTime', 'conversationId', 'bodyPreview'],
});

// 2. Lấy danh sách email đã gửi đi (Sent Items)
const sent = await client.mail.listSent({
  top: 10,
  select: ['id', 'subject', 'toRecipients', 'sentDateTime', 'conversationId'],
});

// 3. Lấy toàn bộ các email trong cùng 1 Thread (Chuỗi hội thoại)
const thread = await client.mail.getConversationThread('AAQkAD...conversationId...');
for (const mail of thread) {
  console.log(`[${mail.receivedDateTime}] ${mail.from?.emailAddress.address}: ${mail.bodyPreview}`);
}

4. Tương Tác Email (Reply, Forward, Đánh dấu đọc, Di chuyển)

// 1. Trả lời thư (Reply) - Tự động giữ nguyên Thread & Subject Re:
await client.mail.reply({
  messageId: 'AAMkAD...',
  comment: 'Tôi đã nhận được thông tin và đang xử lý.',
});

// 2. Chuyển tiếp thư (Forward)
await client.mail.forward({
  messageId: 'AAMkAD...',
  to: '[email protected]',
  comment: 'Chuyển tiếp để đối tác kiểm tra.',
});

// 3. Đánh dấu đã đọc / chưa đọc
await client.mail.markAsRead('AAMkAD...', true);

// 4. Gắn cờ (Flag) theo dõi
await client.mail.flagMessage('AAMkAD...', 'flagged');

// 5. Di chuyển sang thư mục khác (Ví dụ: Thư mục 'Archive' hoặc ID thư mục tùy chọn)
await client.mail.moveMessage('AAMkAD...', 'archive');

5. Quản Lý Thư Nháp (Drafts)

// 1. Soạn và lưu nháp
const draft = await client.mail.createDraft({
  to: '[email protected]',
  subject: 'Báo giá sơ bộ',
  html: '<p>Chi tiết báo giá đính kèm...</p>',
});
console.log('Đã tạo thư nháp có ID:', draft.id);

// 2. Cập nhật lại thư nháp
await client.mail.updateDraft(draft.id, {
  subject: 'Báo giá sơ bộ (Đã cập nhật chiết khấu)',
});

// 3. Bấm gửi thư nháp đi
await client.mail.sendDraft(draft.id);

6. Tải Lên File Đính Kèm Dung Lượng Lớn (> 3MB đến 150MB)

import fs from 'fs';

// Tạo thư nháp trước
const draft = await client.mail.createDraft({
  to: '[email protected]',
  subject: 'File dung lượng lớn',
  text: 'Vui lòng xem file nặng đính kèm.',
});

// Tải file lớn lên theo từng chunk 320 KiB
const bigFileBuffer = fs.readFileSync('video-demo.mp4');
await client.mail.uploadLargeAttachment({
  messageId: draft.id,
  filename: 'video-demo.mp4',
  content: bigFileBuffer,
  contentType: 'video/mp4',
});

// Gửi thư đi
await client.mail.sendDraft(draft.id);

7. Đồng Bộ Thay Đổi Hòm Thư (Delta Sync) Cho Bot / Worker

// Lần 1: Lấy danh sách hiện tại & lưu deltaLink
const initial = await client.mail.getDeltaMessages('inbox');
const nextDeltaLink = initial['@odata.deltaLink'];

// Lần 2 (Chạy định kỳ): Chỉ nhận về những email MỚI hoặc BỊ ĐỔI TRẠNG THÁI
const changes = await client.mail.getDeltaMessages('inbox', nextDeltaLink);
for (const change of changes.value) {
  console.log('Phát hiện thay đổi:', change.subject);
}

8. Quản Lý Thư Mục & Quy Tắc Lọc Tự Động (Folders & Inbox Rules)

// Lấy danh sách thư mục
const folders = await client.folders.listFolders();

// Tạo thư mục mới
const newFolder = await client.folders.createFolder({
  displayName: 'Khách Hàng VIP',
});

// Tạo quy tắc tự động: Nếu thư từ domain @vip.com thì chuyển thẳng vào thư mục VIP
await client.folders.createRule({
  displayName: 'Lọc khách VIP',
  sequence: 1,
  isEnabled: true,
  conditions: {
    senderContains: ['vip.com'],
  },
  actions: {
    moveToFolder: newFolder.id,
    markImportance: 'high',
  },
});

9. Đăng Ký Webhook Realtime (Change Notifications)

import { HotmailClient, SubscriptionService } from '@redonvn/hotmail-mail-sdk';

// 1. Đăng ký Webhook với Microsoft Graph
const sub = await client.subscriptions.createSubscription({
  notificationUrl: 'https://api.yourdomain.com/webhook/hotmail',
  resource: "me/mailFolders('inbox')/messages",
  changeType: 'created', // Khi có thư mới đến
  clientState: 'MY_SECRET_STATE_123',
});

// 2. Trong Controller tiếp nhận Webhook (Express / NestJS):
// A. Xử lý Handshake (khi Microsoft gửi GET để xác thực endpoint):
app.get('/webhook/hotmail', (req, res) => {
  const token = req.query.validationToken as string;
  if (token) {
    return res.status(200).send(SubscriptionService.handleValidationHandshake(token));
  }
});

// B. Tiếp nhận thông báo khi có mail mới (POST):
app.post('/webhook/hotmail', (req, res) => {
  const payload = req.body;
  for (const notification of payload.value) {
    if (SubscriptionService.verifyClientState(notification, 'MY_SECRET_STATE_123')) {
      console.log('Có mail mới đến! Message ID:', notification.resourceData.id);
      // Gọi client.mail.getMessage(notification.resourceData.id) để xử lý ngay!
    }
  }
  res.status(202).send();
});

10. Tích Hợp Thư Viện Nodemailer (Giao thức SMTP XOAUTH2)

import nodemailer from 'nodemailer';
import { HotmailClient } from '@redonvn/hotmail-mail-sdk';

const client = new HotmailClient({
  userEmail: '[email protected]',
  refreshToken: 'M.C518_BL2...',
});

// Tự động lấy access token và sinh cấu hình chuẩn cho Nodemailer
const smtpConfig = await client.getSmtpConfig();
const transporter = nodemailer.createTransport(smtpConfig);

await transporter.sendMail({
  from: '"Hỗ Trợ" <[email protected]>',
  to: '[email protected]',
  subject: 'Gửi qua SMTP cổng 587 bằng XOAUTH2',
  text: 'Email thử nghiệm',
});

📑 Bảng Tổng Hợp Sub-Services & Methods

| Sub-Service | Phương Thức | Mô Tả | |---|---|---| | client.auth | refreshToken() | Đổi Refresh Token lấy Access Token mới & bắt Token xoay vòng | | | getValidAccessToken() | Đảm bảo luôn lấy được token hợp lệ, tự refresh trước 60s | | client.mail | send() | Gửi email nhanh (HTML/Text, CC, BCC, file đính kèm) | | | listReceived() | Lấy danh sách email đến (Inbox) | | | listSent() | Lấy danh sách email đã gửi (Sent Items) | | | getConversationThread() | Lấy toàn bộ lịch sử trò chuyện trong 1 Thread | | | reply() / replyAll() | Trả lời email giữ nguyên Thread | | | forward() | Chuyển tiếp email | | | markAsRead() | Đánh dấu đã đọc / chưa đọc | | | flagMessage() | Gắn cờ theo dõi email | | | moveMessage() / copyMessage() | Di chuyển / sao chép email sang thư mục khác | | | createDraft() / sendDraft() | Soạn, sửa và gửi thư nháp | | | uploadLargeAttachment() | Tải lên file đính kèm lớn (tới 150MB) theo chunk 320 KiB | | | getDeltaMessages() | Đồng bộ mail thay đổi / mới đến (Delta Sync) | | client.folders | listFolders() / createFolder() | Quản lý thư mục hòm thư | | | listRules() / createRule() | Quản lý bộ quy tắc lọc thư tự động (Inbox Rules) | | client.subscriptions | createSubscription() | Đăng ký Webhook nhận thông báo tức thời | | | renewSubscription() | Gia hạn thời gian sống của Webhook | | | handleValidationHandshake() | Helper xử lý bắt tay xác thực endpoint Webhook | | client.user | getProfile() | Lấy thông tin tài khoản Microsoft đang xác thực |


📄 License

MIT © Redon