{"id":14028,"library":"smtpapi","title":"SendGrid X-SMTPAPI Headers for Node.js","description":"The `smtpapi` library is an official Twilio SendGrid Node.js module designed to programmatically construct X-SMTPAPI headers. These headers enable advanced email features such as scheduled sends, substitutions, categories, unique arguments, and recipient lists for emails sent via SendGrid's SMTP API or older V2 Mail Send API. The current stable version is 1.4.7. The package has a maintenance-focused release cadence, with recent updates primarily consisting of chore and documentation improvements rather than new features. While functional, it's crucial to note that newer SendGrid V3 Mail Send API integrations typically utilize `custom_args` directly within the API request body, which differs from the X-SMTPAPI header approach this library facilitates. This library serves as a dedicated tool for those using the SMTP or V2 API methods that rely on the X-SMTPAPI header format.","status":"maintenance","version":"1.4.7","language":"javascript","source_language":"en","source_url":"git://github.com/sendgrid/smtpapi-nodejs","tags":["javascript","smtpapi","x-smtpapi","smtp","sendgrid","headers","email"],"install":[{"cmd":"npm install smtpapi","lang":"bash","label":"npm"},{"cmd":"yarn add smtpapi","lang":"bash","label":"yarn"},{"cmd":"pnpm add smtpapi","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This library is primarily CommonJS (CJS). Direct ES module (ESM) `import` syntax will not work without Node.js interoperability configuration or dynamic `import()` for CJS modules.","wrong":"import Smtpapi from 'smtpapi';","symbol":"smtpapi (Constructor)","correct":"const Smtpapi = require('smtpapi');"},{"note":"The `smtpapi` export is a constructor function and must be instantiated using the `new` keyword.","wrong":"const header = Smtpapi();","symbol":"Smtpapi instance","correct":"const header = new Smtpapi();"},{"note":"The method `jsonString()` is used to retrieve the fully formatted JSON string suitable for the `X-SMTPAPI` header. There is no direct `json()` method that returns a raw JavaScript object.","wrong":"const headerObject = header.json();","symbol":"Generated JSON string","correct":"const headerString = header.jsonString();"}],"quickstart":{"code":"const Smtpapi = require('smtpapi');\n\n// Create a new SMTPAPI header instance\nconst header = new Smtpapi();\n\n// Add multiple recipients to the 'to' field\nheader.addTo('recipient1@example.com');\nheader.addTo('recipient2@example.com');\n\n// Set unique arguments for email tracking and analytics\nheader.setUniqueArgs({\n  userId: 'user_xyz_123',\n  transactionType: 'order_confirmation',\n  orderId: 'ORD-2026-04-15-A'\n});\n\n// Add categories to categorize emails in SendGrid's analytics\nheader.addCategory('Transactional');\nheader.addCategory('UserNotifications');\n\n// Set substitutions for personalized content in the email body (mail merge)\n// Placeholder values (e.g., -name-, -item-) will be replaced per recipient.\nheader.setSubstitutions(\n  '-name-', ['Alice Smith', 'Bob Johnson']\n);\nheader.setSubstitutions(\n  '-item-', ['Product A', 'Service B']\n);\n\n// Optionally set filters to enable or disable SendGrid App features\n// This example enables click tracking for these emails.\nheader.setFilter('clicktrack', 'enable', 1);\n\nconsole.log('Generated X-SMTPAPI Header JSON string:');\nconst xSmtpapiHeader = header.jsonString();\nconsole.log(xSmtpapiHeader);\n\n// --- Conceptual usage with an SMTP client (e.g., Nodemailer) --- \n// Note: This part is for context and requires a separate SMTP transport setup.\n/*\nconst nodemailer = require('nodemailer');\n\nasync function sendEmailWithSmtpapi() {\n  // Ensure your SENDGRID_USERNAME and SENDGRID_PASSWORD environment variables are set\n  const transporter = nodemailer.createTransport({\n    host: 'smtp.sendgrid.net',\n    port: 587,\n    secure: false, // Use TLS implicitly via STARTTLS\n    auth: {\n      user: process.env.SENDGRID_USERNAME ?? 'YOUR_SENDGRID_USERNAME',\n      pass: process.env.SENDGRID_PASSWORD ?? 'YOUR_SENDGRID_PASSWORD'\n    }\n  });\n\n  const mailOptions = {\n    from: 'sender@yourdomain.com',\n    // 'to' field here is often a placeholder; actual recipients are in X-SMTPAPI\n    to: 'placeholder@example.com', \n    subject: 'Your Order Confirmation for -item-, -name-!',\n    text: 'Hello -name-! Your order for -item- has been confirmed.',\n    html: '<b>Hello -name-!</b> Your order for <i>-item-</i> has been confirmed.',\n    headers: {\n      'X-SMTPAPI': xSmtpapiHeader\n    }\n  };\n\n  try {\n    let info = await transporter.sendMail(mailOptions);\n    console.log('Message sent: %s', info.messageId);\n  } catch (error) {\n    console.error('Error sending email:', error);\n  }\n}\n\nsendEmailWithSmtpapi();\n*/","lang":"javascript","description":"Demonstrates how to initialize the `smtpapi` header, add recipients, unique arguments, categories, and substitutions, then retrieve the complete JSON string for inclusion in an email's X-SMTPAPI header."},"warnings":[{"fix":"For new projects or integrations with SendGrid's V3 Mail Send API, consult the official `@sendgrid/mail` Node.js SDK documentation for how to pass `custom_args`, `categories`, and other parameters directly in the mail send request body. Only use this library when explicitly sending email via SendGrid's SMTP endpoint or V2 Mail Send API.","message":"This library is designed to generate X-SMTPAPI headers, which are primarily used with SendGrid's SMTP API and older V2 Mail Send API. For modern integrations using SendGrid's V3 Mail Send API, advanced features (like custom arguments, categories, etc.) are typically passed directly in the JSON payload of the API request, not via X-SMTPAPI headers. Using this library with direct V3 API calls might lead to parameters being ignored or unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your project is configured for CommonJS if you wish to use `require()`. If you must use it within an ESM project, use dynamic `import()`: `const SmtpapiModule = await import('smtpapi'); const Smtpapi = SmtpapiModule.default;`.","message":"The `smtpapi` library is distributed as a CommonJS (CJS) module. Directly importing it using ES module (ESM) syntax (e.g., `import Smtpapi from 'smtpapi';`) in a Node.js project configured for ESM will result in a `ReferenceError`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always use a currently supported Node.js Long Term Support (LTS) release for development and production environments. While this library is likely compatible with newer Node.js versions due to its simplicity, it's not officially stated to support them beyond v16.","message":"The project lists official support for Node.js versions ranging from 4 up to 16. Developing or deploying with extremely old Node.js versions (e.g., 4, 6, 8, 10) is highly discouraged due to known security vulnerabilities, lack of long-term support, and absence of modern JavaScript features. While the library itself is simple, running it on an outdated runtime poses risks.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'1.4.7':62 'advanc':29 'api':50,56,99,108,137 'approach':119 'arg':104 'argument':39 'bodi':110 'cadenc':71 'categori':37 'chore':78 'consist':76 'construct':21 'crucial':90 'current':58 'custom':103 'dedic':128 'design':18 'differ':112 'direct':105 'document':80 'email':30,44,156 'enabl':28 'facilit':122 'featur':31,85 'focus':69 'format':147 'function':87 'header':5,25,27,118,146,155 'improv':81 'integr':100 'javascript':148 'librari':10,121,124 'list':42 'mail':54,97 'mainten':68 'maintenance-focus':67 'method':138 'modul':17 'new':84 'newer':94 'node.js':7,16 'note':92 'offici':13 'older':52 'packag':64 'primarili':75 'programmat':20 'rather':82 'recent':73 'recipi':41 'releas':70 'reli':140 'request':109 'schedul':34 'send':35,55,98 'sendgrid':1,15,47,95,154 'sent':45 'serv':125 'smtp':49,134,153 'smtpapi':4,9,24,117,145,149,152 'stabl':59 'substitut':36 'tool':129 'twilio':14 'typic':101 'uniqu':38 'updat':74 'use':132 'util':102 'v2':53,136 'v3':96 'version':60 'via':46 'within':106 'x':3,23,116,144,151 'x-smtpapi':2,22,115,143,150","created_at":"2026-04-20T01:57:33.860295+00:00","updated_at":"2026-04-20T01:57:33.860295+00:00","problems":[{"fix":"If your project is ESM, either convert the file using `smtpapi` to CommonJS (e.g., change extension to `.cjs` or remove `\"type\": \"module\"` from `package.json`), or use dynamic `import()`: `const SmtpapiModule = await import('smtpapi'); const Smtpapi = SmtpapiModule.default;`.","cause":"Attempting to use `require()` to import `smtpapi` within a JavaScript file that Node.js interprets as an ES module (e.g., due to `\"type\": \"module\"` in `package.json` or a `.mjs` file extension).","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Always instantiate the `Smtpapi` object with `new`: `const header = new Smtpapi();`. If using dynamic `import()` in an ESM context, remember to access the default export: `const SmtpapiModule = await import('smtpapi'); const Smtpapi = SmtpapiModule.default; const header = new Smtpapi();`.","cause":"The `smtpapi` export is a class/constructor. This error occurs if you try to call it as a regular function (e.g., `Smtpapi()`) instead of instantiating it with `new` (e.g., `new Smtpapi()`), or if it's incorrectly imported in an ESM context.","error":"TypeError: Smtpapi is not a constructor"},{"fix":"Ensure all values passed to `setUniqueArgs()` (and similar methods that operate on JSON fields within X-SMTPAPI) are explicitly converted to strings. For example, `{ id: 123 }` should be `{ id: '123' }`.","cause":"Methods like `setUniqueArgs()` expect all values in the provided object to be strings, as per the X-SMTPAPI specification.","error":"Error: Data must be a string. Unique arguments only accept string values."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.4.12","cli_name":"","cli_version":null,"type":"library","homepage":"https://sendgrid.com","github":"https://github.com/sendgrid/smtpapi-nodejs","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/smtpapi","openapi_spec":null,"status_page":null,"smithery":null,"categories":["communication"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}