adachsoft / workflow-step-mail
Mail search, change-tracking, and sending steps for AdachSoft workflows.
Requires
- php: ^8.3
- adachsoft/mailbox-contracts: ^0.2
- adachsoft/mailbox-gmail: ^0.1
- adachsoft/mailbox-imap: ^0.1
- adachsoft/workflow: ^7.5
- guzzlehttp/guzzle: ^7
- psr/clock: ^1.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
Requires (Dev)
- adachsoft/php-code-style: ^0.7.4
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Provider-independent mailbox steps for the AdachSoft workflow engine. The package provides workflow steps to search messages, read mailbox changes, and send e-mail through the adachsoft/mailbox-contracts interface. Built-in providers support IMAP/SMTP and the Gmail API.
Requirements
- PHP 8.3 or newer.
- The AdachSoft workflow engine and mailbox contracts, installed automatically as Composer dependencies.
Installation
composer require adachsoft/workflow-step-mail
The package installs the IMAP, Gmail, Guzzle, and PSR Clock dependencies used by its default providers.
Usage
Registering the steps
The step types are mail_search, mail_changes, and mail_send. Register instances because each step needs a MailboxFactory:
use AdachSoft\Workflow\Builder\WorkflowRunnerBuilder;
use AdachSoft\Workflow\Registry\InMemoryStepRegistry;
use AdachSoft\WorkflowStepMail\Mailbox\MailboxFactory;
use AdachSoft\WorkflowStepMail\Step\MailChangesStep;
use AdachSoft\WorkflowStepMail\Step\MailSearchStep;
use AdachSoft\WorkflowStepMail\Step\MailSendStep;
$mailboxFactory = MailboxFactory::withDefaultProviders();
$stepRegistry = new InMemoryStepRegistry();
$stepRegistry->registerInstance(MailSearchStep::class, new MailSearchStep($mailboxFactory));
$stepRegistry->registerInstance(MailChangesStep::class, new MailChangesStep($mailboxFactory));
$stepRegistry->registerInstance(MailSendStep::class, new MailSendStep($mailboxFactory));
$workflowRunner = WorkflowRunnerBuilder::create()
->withStepRegistry($stepRegistry)
// Configure the application's SecretResolverInterface here.
->build();
MailboxFactory::withDefaultProviders() registers the imap and gmail providers. Pass additional MailboxProviderInterface implementations as arguments to register custom providers alongside them.
Mailbox input
Every step accepts a mailbox object. Its provider field selects the provider; other fields are provider-specific. Configure the workflow engine's secret resolver and use ${secret:NAME} references for credentials. The engine resolves these references in memory before the step runs; do not hardcode secret values in workflow definitions or source code.
IMAP/SMTP
{
"mailbox": {
"provider": "imap",
"imap_host": "imap.example.test",
"imap_port": 993,
"imap_encryption": "ssl",
"smtp_host": "smtp.example.test",
"smtp_port": 465,
"smtp_encryption": "ssl",
"username": "${secret:MAIL_USERNAME}",
"password": "${secret:MAIL_PASSWORD}",
"append_sent_copy": true
}
}
| Option | Type | Required | Default / meaning |
|---|---|---|---|
provider | string | Yes | Must be imap. |
imap_host | string | Yes | IMAP server host. |
imap_port | integer | Yes | IMAP server port. |
imap_encryption | string | Yes | ssl, starttls, or none (case-insensitive). |
smtp_host | string | Yes | SMTP server host. |
smtp_port | integer | Yes | SMTP server port. |
smtp_encryption | string | Yes | ssl, starttls, or none (case-insensitive). |
username | string | Yes | IMAP account name; also the default SMTP user name. |
password | string | Yes | IMAP password; also the default SMTP password. |
smtp_username | string | No | Overrides username for SMTP. |
smtp_password | string | No | Overrides password for SMTP. |
append_sent_copy | boolean | No | true; save successful SMTP sends to the IMAP Sent folder when available. |
imap_timeout_seconds | integer | No | 30; IMAP connection timeout. |
imap_special_folder_overrides | object of strings | No | Special-folder value to server folder-name map, for example {"sent":"Sent Items"}. |
imap_change_tracking_folder | string | No | INBOX; folder used for change tracking. |
smtp_timeout_seconds | integer | No | 30; SMTP connection timeout. |
smtp_default_from | string | No | Optional fallback sender e-mail address. |
smtp_default_from_name | string | No | Optional display name; requires smtp_default_from. |
The same IMAP/SMTP account credentials are used for SMTP unless the SMTP overrides are supplied. smtp_default_from is used only when a sent message does not provide from.
Gmail
Use exactly one refresh-token source. refresh_token is an inline token (normally provided as a secret reference); alternatively, refresh_token_file is the path to a file containing the token.
{
"mailbox": {
"provider": "gmail",
"client_id": "${secret:GMAIL_CLIENT_ID}",
"client_secret": "${secret:GMAIL_CLIENT_SECRET}",
"refresh_token": "${secret:GMAIL_REFRESH_TOKEN}",
"user_id": "me"
}
}
For a token file, replace refresh_token with a path such as "refresh_token_file": "/run/secrets/gmail-refresh-token". The file is read when the provider creates a mailbox; missing, unreadable, or empty files are rejected without including the path or token in the error message.
| Option | Type | Required | Default / meaning |
|---|---|---|---|
provider | string | Yes | Must be gmail. |
client_id | string | Yes | Google OAuth client ID. |
client_secret | string | Yes | Google OAuth client secret; use a secret reference. |
refresh_token | string | One token source | Inline OAuth refresh token; use a secret reference. |
refresh_token_file | string | One token source | Path to a readable file containing a non-empty refresh token. |
user_id | string | No | Gmail API user identifier; defaults to me. |
The Gmail provider uses Guzzle's PSR-18 client and PSR-17 HTTP factory by default. GmailMailboxProvider also accepts injected PSR-18 and PSR-17 implementations when the application needs custom HTTP configuration.
mail_search
Searches one page of mailbox messages. With wait_seconds greater than zero, it polls again while no message matches; when extract_pattern is set, it continues until a value is extracted or the wait expires. The default wait is zero, so the default behavior performs one search.
Inputs
| Input | Type | Required | Default / meaning |
|---|---|---|---|
mailbox | object | Yes | Provider configuration described above. |
from | string | No | Sender filter. |
to | string | No | Recipient filter. |
subject | string | No | Subject substring filter. |
since | string | No | Inclusive ISO-8601 lower date bound. |
before | string | No | Exclusive ISO-8601 upper date bound. |
folder | string | No | Special folder name or provider-specific folder ID. |
unseen_only | boolean | No | false; return only messages not marked as seen when true. |
has_attachments | boolean or null | No | null; optionally filter by attachment presence. |
limit | integer | No | 50; valid range is 1-500. |
include_body | boolean | No | false; include text and HTML bodies in output. |
extract_pattern | string | No | PCRE pattern applied to the subject and plain-text body. The first capture group is returned, or the whole match if no capture group exists. |
mark_seen | boolean | No | false; mark returned messages as seen. |
cursor | string | No | Opaque page cursor returned by a previous search. |
wait_seconds | integer | No | 0; polling duration from 0 to 600 seconds. |
poll_interval_seconds | integer | No | 10; poll delay, at least 1 second. |
Outputs
| Output | Type | Meaning |
|---|---|---|
messages | array | Matching messages with IDs, addresses, subject, receive time, flags, folder/labels, and attachment metadata. text and html are included only when include_body is true. |
next_cursor | string or null | Opaque cursor for the next page, if available. |
extracted | array | Entries with message_id and extracted value. |
first_extracted | string or null | First extracted value, if any. |
error (on_error) | string | Sanitized failure message. |
When configured, on_empty is selected after an empty search or after polling times out without an extracted value. Without an on_empty target, an empty result uses on_next. on_error handles invalid options and mailbox failures.
Wait for a verification code
{
"mailbox": {
"provider": "imap",
"imap_host": "imap.example.test",
"imap_port": 993,
"imap_encryption": "ssl",
"smtp_host": "smtp.example.test",
"smtp_port": 465,
"smtp_encryption": "ssl",
"username": "${secret:MAIL_USERNAME}",
"password": "${secret:MAIL_PASSWORD}"
},
"from": "no-reply@example.test",
"subject": "Your verification code",
"extract_pattern": "/\\b(\\d{6})\\b/",
"wait_seconds": 120,
"poll_interval_seconds": 5
}
The step searches immediately, then repeats every five seconds until it extracts a six-digit code or the 120-second timeout expires. Route on_empty to the workflow's timeout handling step.
mail_changes
Returns additions, removals, and flag changes since a saved synchronization token. The step never persists the token itself. Store next_sync_token in workflow/application state and pass it back as sync_token on the next run. Omitting sync_token initializes synchronization and returns the current token without reporting changes.
Inputs
| Input | Type | Required | Default / meaning |
|---|---|---|---|
mailbox | object | Yes | Provider configuration described above. |
sync_token | string or null | No | Opaque token from the previous run; omit it to initialize. |
include_body | boolean | No | false; include text and HTML bodies for added messages. |
Outputs
| Output | Type | Meaning |
|---|---|---|
added | array | Newly added messages, with bodies only when requested. |
removed | array | Opaque IDs of removed messages. |
flags_changed | array | Opaque IDs of messages whose flags changed. |
next_sync_token | string | Token to store and pass on the next run. |
full_resync_required | boolean | Whether local mailbox state must be rebuilt. |
initialized | boolean | true when this call only initialized synchronization. |
error (on_error) | string | Sanitized failure message. |
Carry the token between runs
Map the token from workflow context into the input and map the returned token back into context:
use AdachSoft\Workflow\Engine\PayloadVo;
$mailChangesStep = new PayloadVo([
'type' => 'mail_changes',
'config' => new PayloadVo([
'on_next' => 'process_changes',
'on_error' => 'mail_error',
]),
'input_map' => new PayloadVo([
'mailbox' => '$context.mailbox',
'sync_token' => '$context.mail_sync_token',
]),
'output_map' => new PayloadVo([
'next_sync_token' => '$context.mail_sync_token',
]),
]);
For the first run, the context may have no mail_sync_token; the optional input is then omitted and synchronization initializes. Persist the resulting mail_sync_token with the workflow state and provide it in the next run's context. If full_resync_required is true, rebuild local state according to the provider's synchronization contract before continuing incremental processing.
mail_send
Sends a text and/or HTML e-mail through the selected provider. At least one recipient across to, cc, and bcc and at least one body (text or html) are required. Recipient fields accept an array of addresses or a comma-separated string.
Inputs
| Input | Type | Required | Default / meaning |
|---|---|---|---|
mailbox | object | Yes | Provider configuration described above. |
from | string | No | Sender address; an IMAP/SMTP smtp_default_from or the authenticated Gmail address may be used when omitted. |
to | array or string | No | Primary recipients. |
cc | array or string | No | Carbon-copy recipients. |
bcc | array or string | No | Blind-carbon-copy recipients. |
reply_to | array or string | No | Reply-to addresses. |
subject | string | Yes | Message subject; an empty subject is allowed. |
text | string or null | No | Plain-text body; provide text, html, or both. |
html | string or null | No | HTML body; provide text, html, or both. |
attachments | array | No | Local file descriptors with path, and optional filename and content_type. |
in_reply_to | string | No | Message identifier for the In-Reply-To header. |
Outputs
| Output | Type | Meaning |
|---|---|---|
message_id | string or null | Provider message identifier, when available. |
rfc_message_id | string | RFC Message-ID returned by the provider. |
thread_id | string or null | Provider thread identifier, when available. |
error (on_error) | string | Sanitized failure message. |
Send with an attachment
{
"mailbox": {
"provider": "imap",
"imap_host": "imap.example.test",
"imap_port": 993,
"imap_encryption": "ssl",
"smtp_host": "smtp.example.test",
"smtp_port": 465,
"smtp_encryption": "ssl",
"username": "${secret:MAIL_USERNAME}",
"password": "${secret:MAIL_PASSWORD}",
"smtp_default_from": "notifications@example.test"
},
"to": ["recipient@example.test"],
"subject": "Your report",
"text": "The requested report is attached.",
"attachments": [
{
"path": "/srv/workflow/reports/report.pdf",
"filename": "report.pdf",
"content_type": "application/pdf"
}
]
}
Attachment paths are read by the workflow process. Keep files in an application-controlled location and grant only the required file access.
Error handling
Configure an on_error target on each step. The branch output contains an error string with resolved workflow input values (including secrets) redacted. Handle the branch without logging credentials or other sensitive data. Provider settings validation errors identify the invalid option but never include password, client-secret, refresh-token, or token-file path values.
Custom providers
Implement MailboxProviderInterface, return a stable provider name from name(), and return a MailboxInterface from create(). Validate provider-specific options with MailboxSettings and throw InvalidMailboxSettingsException for invalid configuration. Register custom providers without replacing the built-ins:
$mailboxFactory = MailboxFactory::withDefaultProviders(new CustomMailboxProvider());
The steps depend only on the mailbox contract, so a custom provider can supply any compatible mailbox implementation.