惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Application and Cybersecurity Blog
Application and Cybersecurity Blog
B
Blog RSS Feed
M
MIT News - Artificial intelligence
爱范儿
爱范儿
V
V2EX
雷峰网
雷峰网
D
Docker
美团技术团队
N
Netflix TechBlog - Medium
C
Cisco Blogs
T
Threatpost
K
Kaspersky official blog
P
Privacy International News Feed
W
WeLiveSecurity
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
F
Full Disclosure
Forbes - Security
Forbes - Security
V
Vulnerabilities – Threatpost
I
Intezer
有赞技术团队
有赞技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google Online Security Blog
Google Online Security Blog
The Register - Security
The Register - Security
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
人人都是产品经理
人人都是产品经理
SecWiki News
SecWiki News
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
罗磊的独立博客
The Hacker News
The Hacker News
腾讯CDC
S
Security @ Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
WordPress大学
WordPress大学
Recorded Future
Recorded Future
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 【当耐特】
小众软件
小众软件
Hacker News: Ask HN
Hacker News: Ask HN
P
Proofpoint News Feed
TaoSecurity Blog
TaoSecurity Blog
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security Affairs
C
Check Point Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Send and download email attachments with Nylas
Qasim · 2026-06-23 · via DEV Community

Email is how most files still move between people: the signed contract, the PDF invoice, the logo embedded in a newsletter. If your app sends or processes mail, it has to handle attachments, and doing that against each provider means Gmail's attachment encoding, Microsoft Graph's, and raw MIME for IMAP. The Nylas Email API gives you one model for both directions: attach files to outbound messages with the same call you use to send, and pull files off inbound messages with a read-only Attachments API.

This post covers both halves from two angles: the HTTP API for your backend, and the nylas CLI for the terminal. I work on the CLI, so the terminal commands below are the ones I reach for when I'm checking a file came through.

Two APIs: one to attach, one to read

There's a split worth understanding up front. You add attachments through the Messages or Drafts API, as part of sending or saving a message, and you read existing attachments through the dedicated Attachments API. The Attachments API is read-only: it downloads bytes and returns metadata, but it never adds files. That division keeps the model simple, since attaching is part of composing a message and reading is a separate concern.

The size of what you're attaching decides how you encode it on the way out. Small files ride inline in the JSON request, larger ones move to a multipart request, and very large files use a separate upload step. On the way in, every attachment, regardless of how it was sent, is fetched the same way: by its attachment_id together with the message_id it belongs to. Get those two ideas straight and the rest is mechanical.

Attach a small file inline with Base64

For files that keep the whole request under 3 MB, the simplest path is the application/json schema. You pass each attachment in an attachments array with its content_type, filename, and the file bytes as a Base64-encoded content string. The 3 MB ceiling covers the entire HTTP request, not just the file, so it's the right path for a small PDF or image and nothing bigger.

curl --request POST \
  --url "https://api.us.nylas.com/v3/grants/<GRANT_ID>/messages/send" \
  --header "Authorization: Bearer <NYLAS_API_KEY>" \
  --header "Content-Type: application/json" \
  --data '{
    "subject": "Your invoice",
    "body": "The invoice is attached.",
    "to": [{ "email": "client@example.com" }],
    "attachments": [
      {
        "content_type": "application/pdf",
        "filename": "invoice.pdf",
        "content": "<Base64-encoded file content>"
      }
    ]
  }'

The CLI does the Base64 encoding for you. nylas email send --attach ./invoice.pdf reads the file, encodes it, and includes it in the send, and you can pass --attach more than once to send several files. The same --attach flag works on nylas email drafts create, so a draft can carry its attachments before it's ever sent.

Send larger files with multipart or an upload session

Once the request would exceed 3 MB, switch encodings. Above that limit you send the message as a multipart/form-data request instead of JSON, which providers cap at 25 MB for the full message. The attachment fields are the same; only the transport changes. That covers the large majority of real attachments, from multi-megabyte decks to short video clips.

For files beyond 25 MB, there's a separate pre-upload flow that's currently Microsoft-only and handles attachments up to 150 MB. You create an upload session, PUT the file bytes to the returned URL, then reference the resulting attachment by ID in your send. The send large attachments guide walks through that flow. One Microsoft-specific gotcha it covers: Exchange Online defaults to a 35 MB send size, so you raise the mailbox limit toward 150 MB before sending large files, because Nylas accepting the upload doesn't guarantee Exchange will deliver it. The practical ladder is simple: under 3 MB inline, under 25 MB multipart, and the upload session only when you genuinely need very large files on a Microsoft account.

Embed an inline image with a content ID

Not every attachment is a separate download; a logo or a chart in the body of an HTML email is an inline attachment. You mark one by giving the attachment a content_id and referencing that ID from the HTML body with a cid: URL, so <img src="cid:logo123"> renders the attachment whose content_id is logo123 right where you place the tag.

curl --request POST \
  --url "https://api.us.nylas.com/v3/grants/<GRANT_ID>/messages/send" \
  --header "Authorization: Bearer <NYLAS_API_KEY>" \
  --header "Content-Type: application/json" \
  --data '{
    "subject": "Welcome aboard",
    "body": "<p>Welcome!</p><img src=\"cid:logo123\">",
    "to": [{ "email": "newuser@example.com" }],
    "attachments": [
      {
        "content_type": "image/png",
        "filename": "logo.png",
        "content": "<Base64-encoded image>",
        "content_id": "logo123"
      }
    ]
  }'

The difference between an inline image and a regular attachment is the content_id and the cid: reference, which together set the attachment's disposition to inline so the mail client renders it in place rather than listing it as a download. Drop the content_id and the same file becomes a standard attachment the recipient downloads separately. That one field is the whole distinction.

The inline mechanism works on drafts too, through the same attachments array, so a templated welcome email can carry its logo from draft to send. And because an inline image is part of the message rather than a remote URL, it renders even in clients that block remote images for privacy, which is a reason to embed a logo with cid: rather than hotlink it from a server.

Set the right content type

Every attachment needs a content_type, the MIME type that tells the recipient's mail client what the file is and how to handle it. A PDF is application/pdf, a PNG is image/png, and a calendar invite is application/ics. Get it wrong and a client may refuse to preview the file, or fail to render an inline image, even when the bytes are perfectly correct.

Match the content_type to the actual file rather than guessing from the extension, especially for inline images where the wrong type can stop the cid: reference from displaying. Nylas documents the supported media types for attachments, which is the place to check when a particular file type isn't behaving the way you expect on send or download.

List the attachments on a message

When mail arrives, the message object tells you which attachments it carries, and the Attachments API reads them. To see what's on a message from the terminal, nylas email attachments list <message-id> prints each attachment with its filename, type, and size. It's the fastest way to inspect what came in before you decide what to pull down.

nylas email attachments list <message-id>

Each entry has an id, which is the attachment_id you'll use to fetch the file, along with its filename, content_type, and size. An inbound newsletter might list a logo marked inline alongside a PDF marked as a regular attachment, and the metadata tells you which is which before you spend bandwidth downloading anything.

You often don't even need a separate call for this. The message object itself carries an attachments array, where each entry holds the id, filename, size, content_type, and an is_inline flag. So when you fetch or receive a message, you already have the metadata to decide what to download, and is_inline tells you whether an attachment is an embedded image or a file the recipient would download on its own.

Get an attachment's metadata

When you have an attachment_id and want its details without the bytes, GET /v3/grants/{grant_id}/attachments/{attachment_id} returns the metadata. There's a requirement that trips people up: you must pass the message_id as a query parameter, because an attachment is identified relative to the message it belongs to, not on its own.

curl --request GET \
  --url "https://api.us.nylas.com/v3/grants/<GRANT_ID>/attachments/<ATTACHMENT_ID>?message_id=<MESSAGE_ID>" \
  --header "Authorization: Bearer <NYLAS_API_KEY>"

The CLI command mirrors that requirement: nylas email attachments show <attachment-id> <message-id> takes both IDs as positional arguments, because the metadata lookup needs the message context just like the API does. Reading metadata first is useful when you want to check a file's size or type before committing to the download, for example to skip anything over a threshold or filter by content type.

Download the file

To get the bytes, GET /v3/grants/{grant_id}/attachments/{attachment_id}/download streams the file. Like the metadata call, it requires the message_id query parameter, so both attachment endpoints always take the attachment ID and the message ID together. The response is the raw file, which you redirect to disk or pipe onward.

curl --request GET \
  --url "https://api.us.nylas.com/v3/grants/<GRANT_ID>/attachments/<ATTACHMENT_ID>/download?message_id=<MESSAGE_ID>" \
  --header "Authorization: Bearer <NYLAS_API_KEY>" \
  --output invoice.pdf

From the CLI, nylas email attachments download <attachment-id> <message-id> saves the file, defaulting to its original filename, and -o ./path/file.pdf writes it wherever you want. This is the call an inbound-processing agent makes after it decides a message's attachment is worth keeping: list the attachments, check the metadata, then download the ones that matter.

Process inbound attachments automatically

The read side comes together in a webhook loop. When a message arrives, the message.created webhook fires with the message object, and that object already lists its attachments with their IDs, sizes, and types. Your handler reads that array, decides which files matter, and downloads only those by pairing each attachment_id with the message's id.

That ordering keeps an inbound pipeline efficient. An invoice-processing agent, for example, can ignore inline signature images by checking is_inline, skip anything over a size threshold by reading size, and download only the PDFs it needs to parse. Because the metadata rides on the message you already received, you spend bandwidth only on the files you keep, not on everything that lands in the mailbox. The download itself is the one call that pulls bytes, so gating it on the metadata you already have is what keeps the pipeline cheap at volume.

Things to keep in mind

A few details separate a smooth attachments integration from one that returns confusing errors.

  • Always pass message_id to read an attachment. Both the metadata and download endpoints require it; an attachment ID alone isn't enough to locate the file.
  • Pick the encoding by size. Under 3 MB inline as Base64, under 25 MB with multipart/form-data, and the Microsoft-only upload session for files up to 150 MB.
  • Inline versus attached is one field. A content_id plus a cid: reference in the HTML body makes an image render in place; without it, the file is a separate download.
  • Add through Messages or Drafts, read through Attachments. The Attachments API never adds files; you attach when you send or draft.
  • Check metadata before downloading. Reading size and content_type first lets you skip oversized or unwanted files without spending the bandwidth.
  • is_inline separates embedded images from files. On inbound mail, read it to skip inline logos and signatures and download only the real attachments.
  • Raise the Exchange mailbox limit for large files. Exchange Online defaults to a 35 MB send size, so the 150 MB upload session needs that raised first; Nylas accepting the file doesn't guarantee Exchange delivers it.

Wrapping up

Attachments come down to two flows. Outbound, you add files to a send or a draft, choosing the encoding by size: Base64 inline under 3 MB, multipart under 25 MB, an upload session for very large Microsoft files. Inbound, you list a message's attachments, read their metadata, and download the bytes, always pairing the attachment_id with its message_id. The same handful of calls, or the nylas email attachments commands, cover every provider Nylas connects, so a logo embedded in a Gmail newsletter and a PDF on an Exchange message are the same code path.

Where to go next: