@emailjs/browser

中文文档
5.0.3发布于 2026/10/10BSD-3-ClauseTypeScriptESM + CJS零依赖近 30 天下载 55.2万

Official EmailJS SDK for browsers

原始使用文档
文档目录20 节
  1. Target Environment Notice
  2. Why EmailJS?
  3. What is EmailJS?
  4. Core Architectural Benefits
  5. Installation and Setup
  6. Modern Bundlers (Vite, Next.js, Webpack, Rollup)
  7. Browser Direct Script Integration (CDN)
  8. Code Examples
  9. 1. Modern Async/Await Workflow
  10. 2. Form Submission (sendForm)
  11. 3. Vanilla JavaScript Website Integration Example
  12. Advanced Configuration
  13. Main Options
  14. BlockList Settings
  15. LimitRate Settings
  16. Custom Storage Provider Interface
  17. Configuration Code Examples
  18. Setting Global Security and Rate Limits
  19. Overriding Settings Locally
  20. Useful Links

Official EmailJS SDK for Web Browsers

The official client-side TypeScript and JavaScript SDK for EmailJS.com customers.

Send emails directly from your code in the simplest and most secure way.

codecov npm version

  • 100% Code Coverage: Every single line of code, condition, and error handler in this SDK is fully covered by automated test suites to ensure absolute production readiness and zero regression issues.
  • Zero External Dependencies: Built with zero overhead to keep your bundle footprint as lightweight as possible.

Target Environment Notice

This package is designed exclusively for web browsers and client-side web environments. If you are building for a different platform, please use the corresponding dedicated SDK:

Why EmailJS?

What is EmailJS?

EmailJS is an Email Orchestration Layer and a Unified API hub designed to seamlessly integrate with your existing infrastructure. By leveraging your preferred email services—from personal Gmail accounts and standard SMTP servers to enterprise transactional providers like SendGrid, Mailgun, Resend or AWS SES—EmailJS centralizes and optimizes your entire email workflow through a single, powerful interface.

Core Architectural Benefits

  • Instant Provider Hot-Swapping: If your primary delivery service suffers an outage or an unexpected account block, your application remains online. With EmailJS, you can instantly route your production traffic to a fallback provider (e.g., from SendGrid to AWS SES) with a single click in your dashboard—requiring zero code adjustments and zero re-deployments. You can also route dynamically on the fly by passing a different serviceID directly in your API request.
  • Bypass the "Migration Tax": If you ever need to change your email provider, you don't have to rewrite your integration logic, recreate HTML templates, or re-map variables. Integrate EmailJS once, and change underlying providers seamlessly.
  • Zero Backend Overhead: Eliminate the need to build, maintain, and secure a custom backend service or proxy just to safely route outgoing emails.
  • Universal Ecosystem Support: Works seamlessly across any stack. Use our official client/server SDKs—or connect any application on any platform using our universal REST API with Rust, Python, PHP, C#, Go, or any other language.

Installation and Setup

Modern Bundlers (Vite, Next.js, Webpack, Rollup)

Install the SDK using your preferred package manager:

npm install @emailjs/browser
# yarn add @emailjs/browser
# pnpm add @emailjs/browser
# bun add @emailjs/browser

Browser Direct Script Integration (CDN)

For applications without a build step, websites running on CMS platforms (like WordPress, Webflow, Shopify), or vanilla JavaScript environments, add the SDK directly via CDN:

<script
  type="text/javascript"
  src="https://cdn.jsdelivr.net/npm/@emailjs/browser@5/dist/email.min.js"
></script>

Code Examples

1. Modern Async/Await Workflow

Designed for components in React, Vue, Angular, Svelte, Next.js, Nuxt, etc.

import emailjs, { EmailJSResponseStatus } from '@emailjs/browser';

const templateParams = {
  name: 'James',
  notes: 'Check this out!',
};

try {
  const response = await emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams, {
    publicKey: 'YOUR_PUBLIC_KEY',
  });
  console.log('SUCCESS!', response.status, response.text);
} catch (error) {
  if (error instanceof EmailJSResponseStatus) {
    console.error('EmailJS Error:', error.status, error.text);
    return;
  }
  console.error('Unexpected Error:', error);
}

2. Form Submission (sendForm)

Automatically captures input fields from an HTML form element and delivers the payload securely.

import emailjs from '@emailjs/browser';

emailjs
  .sendForm(
    'YOUR_SERVICE_ID',
    'YOUR_TEMPLATE_ID',
    document.querySelector('#myForm'), // Can be a direct form reference (preferred), or a string selector
    {
      publicKey: 'YOUR_PUBLIC_KEY',
    },
  )
  .then((response) => {
    console.log('SUCCESS!', response.status, response.text);
  })
  .catch((error) => {
    console.error('FAILED...', error);
  });

3. Vanilla JavaScript Website Integration Example

If you are loading the SDK via a <script> tag on a standard layout.

<button id="sendBtn">Send Email</button>

<script
  type="text/javascript"
  src="https://cdn.jsdelivr.net/npm/@emailjs/browser@5/dist/email.min.js"
></script>
<script type="text/javascript">
  document.getElementById('sendBtn').addEventListener('click', function () {
    const templateParams = {
      name: 'James',
      message: 'Hello from vanilla JS!',
    };

    emailjs
      .send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams, {
        publicKey: 'YOUR_PUBLIC_KEY',
      })
      .then(
        function (response) {
          console.log('SUCCESS!', response.status, response.text);
        },
        function (error) {
          console.log('FAILED...', error);
        },
      );
  });
</script>

Advanced Configuration

Options can be defined globally using the init() method or overridden locally as the fourth parameter of execution functions (send, sendForm). Local options take higher priority over global configurations.

Main Options

PropertyTypeDefaultDescription
publicKeystring—Required. Your EmailJS account public credential.
blockHeadlessbooleanfalseWhen true, automatically rejects execution with error 451 if the request originates from a headless browser.
blockListBlockList—Settings to evaluate and drop requests matching forbidden values.
limitRateLimitRate—Throttling and rate-limiting rules.
storageProviderStorageProvider—Custom key-value storage engine interface.

BlockList Settings

Drops any method calls if a tracked variable contains or matches blocked strings. Returns error 403 when triggered.

PropertyTypeDescription
liststring[]Array of forbidden string terms or target values to block.
watchVariablestringThe object key or variable path name inside the payload to monitor.

LimitRate Settings

Enforces request rate limiting. Returns error 429 when limits are exceeded.

PropertyTypeDefaultDescription
idstringpage pathScope identifier. Can be overridden with a custom ID per user, page, group, or system.
throttlenumber—Minimum time gap (in milliseconds) required between consecutive requests.

Custom Storage Provider Interface

By default, the SDK uses native localStorage if available. You can supply a custom async engine matching the following contract:

interface StorageProvider {
  get: (key: string) => Promise<string | null | undefined>;
  set: (key: string, value: string) => Promise<void>;
  remove: (key: string) => Promise<void>;
}

Configuration Code Examples

Setting Global Security and Rate Limits

import emailjs from '@emailjs/browser';

emailjs.init({
  publicKey: 'YOUR_PUBLIC_KEY',
  blockHeadless: true,
  blockList: {
    watchVariable: 'user_email',
    list: ['[email protected]', '[email protected]'],
  },
  limitRate: {
    throttle: 10000, // 10 seconds cooldown window
  },
});

Overriding Settings Locally

import emailjs from '@emailjs/browser';

const payload = {
  userEmail: '[email protected]',
  message: 'Hello!',
};

await emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', payload, {
  publicKey: 'YOUR_PUBLIC_KEY',
  blockList: {
    watchVariable: 'userEmail', // Custom path evaluation for this request
  },
  limitRate: {
    throttle: 0, // Bypass global rate-limiting rules for this specific call
  },
});

版本与发布记录

@emailjs/browser 共发布 24 个版本,首次发布于 2021/12/30;过去 12 个月发布了 3 个版本。

版本发布日期距今
5.0.3latest2026/10/101 个月前
5.0.22026/10/051 个月前
5.0.12026/10/051 个月前
4.4.12024/07/122 年前
4.3.32024/03/072 年前
4.3.22024/03/072 年前

关于 @emailjs/browser 的常见问题

@emailjs/browser 是什么?

Official EmailJS SDK for browsers

如何安装 @emailjs/browser?

在项目目录运行 npm install @emailjs/browser,或使用 pnpm add / yarn add / bun add。

@emailjs/browser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@emailjs/browser 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@emailjs/browser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@emailjs/browser 可以商用吗?

@emailjs/browser 使用 BSD-3-Clause 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。另外不得用原作者名义为衍生产品背书。以上为概括,不构成法律意见,请以许可原文为准。

@emailjs/browser 的下载量有多少?

根据 npm 官方下载统计,@emailjs/browser 在 2026/10/14 – 2026/11/12 这 30 天内被下载 551,980 次,日均约 18,399 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@emailjs/browser 还在维护吗?

最新版本 5.0.3 发布于 2026/10/10(1 个月前);至今共发布 24 个版本,其中过去 12 个月发布了 3 个;首次发布于 2021/12/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。