> ## Documentation Index
> Fetch the complete documentation index at: https://www.voiceflow.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Connect Salesforce Agentforce Service email to a Voiceflow agent

> Connect Salesforce Email-to-Case to Voiceflow. Poll automation-owned cases and send reviewed replies through the supplied Apex REST service.

## Overview

Receive email as Salesforce Email-to-Case records, poll automation-owned cases and send reviewed Voiceflow replies through a supplied Apex REST service. This walkthrough uses Salesforce's case and email APIs, including a deployed Apex class.

**Note:** 

Reuse the [Salesforce integration](/docs/documentation/build/tools/salesforce-tool) for CRM tools and record access. Those tools do not establish Email-to-Case receiving. This manual includes an Apex deployment; the API reference alone is not a second installation method.

<a id="before-you-begin"></a>

## Before you begin

Prepare the agent, platform administrator and relay operator.

Use an existing [support agent](/docs/guides/usecases/customer-service/build-faq-agent) with approved public [Knowledge](/docs/documentation/build/importing-data-sources). The agent owner publishes the intended Environment; the help desk administrator owns email routing and assignment; a backend developer operates the relay.

| Requirement | What to prepare |
| --- | --- |
| Voiceflow | Project ID, server-side project API key and released Environment alias. |
| Host | Node 24.14.1 and one persistent worker with encrypted SQLite storage; the bundle supplies Docker/Compose. |
| Test | A customer inbox you control, an expected policy answer and a human support owner. |
| Salesforce | Agentforce Service / Service Cloud org with Email-to-Case, REST API and Apex deployment access. |
| Identity | Dedicated integration user/queue, API-enabled OAuth app and verified organization-wide email sender. |
| Cases | Pilot cases linked to a Contact, with readable incoming EmailMessage records and original MessageIdentifier values. |
| Deployment | Salesforce CLI and a sandbox; an administrator must validate/deploy the supplied Apex project and assign its permission set. |

This supervised example answers public support questions. Email addresses and help desk records do not authorize access to private customer data. Keep `AUTO_SEND=false`: APIs do not consistently expose raw automatic-response headers, so a person reviews every outbound message and its recipients.

<a id="prepare-relay"></a>

## Prepare the relay

Install the supplied implementation and durable review queue.

### 1. Configure the executable service

Extract the [relay bundle](/docs/examples/email-relay/email-relay.zip), enter `email-relay` and run with Node 24.14.1:

```sh
npm ci
cp .env.example .env
chmod 600 .env
openssl rand -hex 32
```

Use the generated value for `IDENTITY_SECRET`. Set `VF_PROJECT_ID`, `VF_API_KEY`, `VF_ENVIRONMENT`, a fixed UTC `ACCEPT_AFTER` just before the pilot and `ALLOW_SENDERS` to your test inbox. Keep `AUTO_SEND=false` and `POLL_SECONDS=60`. The provider steps below supply the remaining fields.

The bundle's `helpdesk-adapters.mjs` implements the exact provider calls; `helpdesk.mjs` checks ownership and input, and the shared worker stores message identities, sessions and cached replies. Read its `HELPDESKS.md` for file/operation mapping.

### 2. Keep one worker and a narrow pilot

Use one process/database for this provider, address, automation owner and scope. The relay scans the selected pilot work and paginates histories; it does not use a webhook or expiring event subscription. API/OAuth credentials still require renewal or rotation. Its 300-page cap fails visibly rather than silently truncating a large scan.

This is a small supervised deployment with no distributed lease or bounded work queue. Monitor quota, disk and oldest pending work; add incremental ingestion and capacity controls before a high-volume rollout.

<a id="connect-email"></a>

## Connect receiving and replies

Configure the native email channel and its API permissions.

### 1. Prepare Email-to-Case and the sender

Enable Email-to-Case, create/verify the routing address and forward the support mailbox to Salesforce's generated receiving address. Use assignment rules to put pilot cases under one dedicated automation user or queue. Confirm an external email creates a Case and incoming EmailMessage, and that a manual case email reply reaches the customer.

Verify the organization-wide email address, sender domain and integration user as required by Salesforce. Set the pilot Case's Contact; the supplied sender refuses cases without one so it can log the response against the Contact and Case. Disable competing case auto-responses for this pilot.

### 2. Authorize API access and deploy the Apex service

Create an External Client App with the client-credentials flow, the `api` scope and an approved run-as integration user. That user needs API Enabled, access to the pilot Cases, Contact Read, EmailMessage Read and permission to send email using the verified organization-wide address. Its sharing and field permissions still apply; the supplied class reads Case/EmailMessage in user mode.

Set `PROVIDER=salesforce`, `HD_ORIGIN` to the org's My Domain HTTPS origin, `HD_CLIENT_ID`, `HD_CLIENT_SECRET` and `HD_OWNER_ID` to the automation owner. Set `SF_ORG_WIDE_EMAIL_ID` to the verified OrgWideEmailAddress ID. Leave `HD_TOKEN` empty; the relay obtains fresh client-credentials tokens. Set the three email fields to the verified address.

From the bundle's `salesforce` directory, authorize the sandbox and validate the exact source:

```sh
sf org login web --alias email-sandbox
sf project deploy start --target-org email-sandbox --source-dir force-app --test-level RunSpecifiedTests --tests VoiceflowEmailReplyTest
sf org assign permset --target-org email-sandbox --name VoiceflowEmailRelay --on-behalf-of YOUR_INTEGRATION_USERNAME
```

The permission set grants class access; configure object/field/send privileges separately. Resolve org-specific validations and run the deployment/tests successfully before starting the relay. Repeat your organization's validated deployment process in production.

### 3. Poll EmailMessage and send a case-linked reply

The relay uses REST API v66.0 to list open automation-owned Cases, then reads their EmailMessage records. Only incoming email addressed to `MAILBOX` becomes input. Outgoing case emails are barriers.

The supplied `VoiceflowEmailReply` Apex service re-locks the Case, checks ownership/open state/Contact and confirms the expected incoming EmailMessage is still newest. It sends a `Messaging.SingleEmailMessage` from the verified address, with `In-Reply-To`/`References` from the incoming MessageIdentifier, and saves the activity against the Contact/Case. It does not instantiate Salesforce's own AI agent.

To inspect the native IDs, first fill this provider's credentials, then run the supplied read-only helper in a private terminal:

```sh
node --env-file=.env helpdesk-discover.mjs '/services/data/v66.0/query?q=SELECT+Id,Address+FROM+OrgWideEmailAddress'
```

Replace any `PILOT_…_ID` with the native ID from a ticket/conversation you can open. The helper permits ID discovery before owner/scope fields are filled; it only performs GET requests plus any required OAuth token exchange. Its output can contain customer data. Copy the fields identified above, then run the scoped check below.

The supplied adapter builds this reply payload after approval; replaceable IDs come from the native incoming record, not from the language model:

```json
{"caseId":"CASE_ID","emailId":"INCOMING_EMAILMESSAGE_ID","ownerId":"AUTOMATION_OWNER_ID","orgWideEmailId":"VERIFIED_SENDER_ID","body":"Reviewed answer"}
```

<a id="host-relay"></a>

## Run the persistent worker

Verify read access, then start processing without a public webhook.

### 1. Check the native route without sending

After filling `.env`, run:

```sh
node --env-file=.env helpdesk-check.mjs
```

Expect your test ticket/conversation with the correct owner, `open=true`, `scoped=true` and `eligible=true`. This command may obtain/cache an OAuth token but sends no Voiceflow turns or customer replies. Resolve access/routing problems before starting the worker.

### 2. Start locally, then host the same state

```sh
npm start
```

In another terminal, `curl -f http://127.0.0.1:8080/health` should report running. No public `/inbound` endpoint is enabled for help desks. Polling uses outbound HTTPS and stored server credentials; there is no incoming webhook secret or subscription to configure.

For a persistent Linux host, install Docker/Compose, copy the bundle and protected `.env`, set `DB_PATH=/app/data/relay.sqlite`, and run `docker compose up -d --build`. The supplied service has a persistent volume and restart policy; port 8080 is bound to host loopback. Keep it private. If you obtained a local OAuth grant, stop the local worker and copy its complete stopped database into the host volume before starting; never run both copies. The bundle README gives the exact database copy commands.

<a id="conversation-mapping"></a>

## Keep tickets and sessions aligned

Use native ownership, message identity and the actual customer sender.

Case ID plus actual email sender scopes the Voiceflow session. Salesforce email headers preserve the original reply relationship, and Email-to-Case handles later receiving/case correlation. Case merges, closed-case follow-ups and a changed Contact need operator reconciliation rather than silent session migration.

| Control | What the supplied relay does |
| --- | --- |
| Deduplication | Persists native message IDs; repeat scans cannot resend the same job. |
| Customer burst | Combines messages received before the first turn. New input overlapping an already generated/uncertain answer is held for human reconciliation. |
| Takeover | Re-reads ownership, scope and latest content before the turn and before sending; stale jobs become `ignored`. |
| Content | Holds files, truncated/missing text, changed Reply-To, forwards and input over 12,000 characters. |
| Output | Caches text traces; holds interactive/handoff output for a written reply. |

Reassign to a person **before** replying manually. The recheck is not a universal lock: keep competing humans/automations outside this assignment. Resolve old held jobs before returning work to automation.

For additions during review, `show` identifies `helpdesk.priorJobs` and the hold reason. Inspect those cached answers and all new questions, discard stale work, then write one reconciled reply for the newest held job; the agent does not replay earlier messages.

Files stay in the help desk and are never fetched or forwarded. Check original quoted/inline content; the quote heuristic is limited. Outgoing/agent messages cannot start self-reply loops. Manual review also screens external auto-responses whose raw headers the API omits.

<a id="test-conversation"></a>

## Test the complete conversation

Prove receiving, agent execution and actual email delivery separately.

### 1. Receive, review and deliver the first answer

From the permitted external inbox, email the support address. Confirm the native ticket/conversation and its automation assignment, then inspect the queue and Voiceflow transcript:

```sh
node --env-file=.env cli.mjs list
node --env-file=.env cli.mjs show JOB_ID
node --env-file=.env cli.mjs approve JOB_ID
```

Replace `JOB_ID` with the actual ID from `list`. Approve only after checking the question, cached answer, original sender/recipients and support identity; the next worker pass sends it. For `review-input`, have a person inspect the original and write a reply with the shared [review workflow](/docs/guides/channels/email/review-replies-before-sending). Expected result: one runtime answer, one reviewed native reply and an email in the test customer's inbox.

Inspect the Case's sent email activity, native email logs/deliverability and customer inbox. Apex send acceptance is subject to Salesforce's email limits and does not prove inbox placement. Check the follow-up returns to the same Case.

### 2. Test continuation, takeover and recovery

Reply in-thread with a follow-up requiring earlier context. Expect the same native conversation and sender-scoped runtime session. Send a separate new support request and expect a new session. Repeat polling and restart the worker; expect no duplicate answer for an already processed native message.

While a reply awaits approval, reassign the ticket to a person, then approve the cached job in this controlled test. Expect `ignored` and no email. Also test a human reply, two consecutive customer messages, an attachment, an auto-response and a changed Reply-To where supported. Reconcile/discard held work before assigning the conversation back. Finally exercise a controlled API rejection and interrupted send, then use recovery below.

<a id="troubleshooting" />

### The email never becomes eligible work

Check the native email channel before the agent.

Confirm a real incoming email record, open status, exact automation owner, scope/address and pilot cutoff. The read-only check reports these separately. Check sender allowlisting and provider API permissions; a healthy process cannot prove the support mailbox is receiving. A private note, outgoing email, archived ticket or unrelated channel should not run the agent.

### The answer is held or becomes stale

Inspect the durable state and original conversation.

`review-input` needs an operator-written answer after inspecting the original; `review` has a cached candidate. `ignored` with a ticket-change explanation means the ownership/content guard prevented a stale reply. Do not force it through by resetting the database. Discard old held work after the human takes responsibility. Check the released Environment and runtime transcript for `uncertain-turn`.

### The reply was accepted but no email arrived

Reconcile provider delivery before any retry.

Check Apex class access, user-mode object/field access, Contact linkage and verified organization-wide sender access. Rejected stale/ownership checks require human review. For a timeout after Apex execution, inspect email history/logs before retrying; do not redeploy or call the service again to guess the outcome.

Keep a timed-out write in `uncertain-send` until native history proves whether it was accepted. Never rerun the agent to recreate a cached answer. A 429 backs off using Retry-After; the sample never retries a write automatically.

<a id="go-live"></a>

## Release and maintain the connection

Keep review, assignment and durable recovery in place.

### 1. Release the reviewed support route

Publish the reviewed Voiceflow Environment, deploy one worker and repeat the entire customer test through the production support address. Keep `AUTO_SEND=false`; the example enforces it for help desks. Widen `ALLOW_SENDERS` only with approved public-support scope, abuse controls and staffed review. Record API/seat access, email delivery and takeover acceptance in your deployment record.

Changing provider, address, owner/scope, project, Environment, cutoff or identity secret requires draining/resolving old work and a new database. Credential rotation alone does not. Stop the worker before copying/backing up SQLite, preserve its WAL if present, encrypt backups and set retention for help desk content, transcripts and local records.

### 2. Recover without replaying unknown writes

`uncertain-turn` may include completed tool side effects: inspect the transcript before using `restart JOB_ID --reviewed-side-effects`. For `uncertain-send`, inspect native history and delivery. If already sent, use `mark-sent JOB_ID`; if confirmed never accepted, use `retry-send JOB_ID --confirmed-not-sent` to retry the cached answer. Run these through `node --env-file=.env cli.mjs …`; ownership is checked again before any send.

Monitor poll errors, API quota, failed delivery, disk and held-job age. Rotate/revoke credentials with the provider administrator and retest. For rollback, route/assign work to human support, resolve queued jobs, stop the relay and then revoke its credentials. Receiving remains in the help desk during relay outages; reconcile the native backlog against durable jobs before resuming.
