Search by

adachsoft / workflow-step-mail

Arkadiusz Adach

Mail search, change-tracking, and sending steps for AdachSoft workflows.

Package info

gitlab.com/a.adach/workflow-step-mail

Issues

pkg:composer/adachsoft/workflow-step-mail

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.1 2026-11-26 11:44 UTC

This package is auto-updated.

Last update: 2026-11-26 10:45:19 UTC


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
  }
}
OptionTypeRequiredDefault / meaning
providerstringYesMust be imap.
imap_hoststringYesIMAP server host.
imap_portintegerYesIMAP server port.
imap_encryptionstringYesssl, starttls, or none (case-insensitive).
smtp_hoststringYesSMTP server host.
smtp_portintegerYesSMTP server port.
smtp_encryptionstringYesssl, starttls, or none (case-insensitive).
usernamestringYesIMAP account name; also the default SMTP user name.
passwordstringYesIMAP password; also the default SMTP password.
smtp_usernamestringNoOverrides username for SMTP.
smtp_passwordstringNoOverrides password for SMTP.
append_sent_copybooleanNotrue; save successful SMTP sends to the IMAP Sent folder when available.
imap_timeout_secondsintegerNo30; IMAP connection timeout.
imap_special_folder_overridesobject of stringsNoSpecial-folder value to server folder-name map, for example {"sent":"Sent Items"}.
imap_change_tracking_folderstringNoINBOX; folder used for change tracking.
smtp_timeout_secondsintegerNo30; SMTP connection timeout.
smtp_default_fromstringNoOptional fallback sender e-mail address.
smtp_default_from_namestringNoOptional 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.

OptionTypeRequiredDefault / meaning
providerstringYesMust be gmail.
client_idstringYesGoogle OAuth client ID.
client_secretstringYesGoogle OAuth client secret; use a secret reference.
refresh_tokenstringOne token sourceInline OAuth refresh token; use a secret reference.
refresh_token_filestringOne token sourcePath to a readable file containing a non-empty refresh token.
user_idstringNoGmail 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

InputTypeRequiredDefault / meaning
mailboxobjectYesProvider configuration described above.
fromstringNoSender filter.
tostringNoRecipient filter.
subjectstringNoSubject substring filter.
sincestringNoInclusive ISO-8601 lower date bound.
beforestringNoExclusive ISO-8601 upper date bound.
folderstringNoSpecial folder name or provider-specific folder ID.
unseen_onlybooleanNofalse; return only messages not marked as seen when true.
has_attachmentsboolean or nullNonull; optionally filter by attachment presence.
limitintegerNo50; valid range is 1-500.
include_bodybooleanNofalse; include text and HTML bodies in output.
extract_patternstringNoPCRE 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_seenbooleanNofalse; mark returned messages as seen.
cursorstringNoOpaque page cursor returned by a previous search.
wait_secondsintegerNo0; polling duration from 0 to 600 seconds.
poll_interval_secondsintegerNo10; poll delay, at least 1 second.

Outputs

OutputTypeMeaning
messagesarrayMatching 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_cursorstring or nullOpaque cursor for the next page, if available.
extractedarrayEntries with message_id and extracted value.
first_extractedstring or nullFirst extracted value, if any.
error (on_error)stringSanitized 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

InputTypeRequiredDefault / meaning
mailboxobjectYesProvider configuration described above.
sync_tokenstring or nullNoOpaque token from the previous run; omit it to initialize.
include_bodybooleanNofalse; include text and HTML bodies for added messages.

Outputs

OutputTypeMeaning
addedarrayNewly added messages, with bodies only when requested.
removedarrayOpaque IDs of removed messages.
flags_changedarrayOpaque IDs of messages whose flags changed.
next_sync_tokenstringToken to store and pass on the next run.
full_resync_requiredbooleanWhether local mailbox state must be rebuilt.
initializedbooleantrue when this call only initialized synchronization.
error (on_error)stringSanitized 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

InputTypeRequiredDefault / meaning
mailboxobjectYesProvider configuration described above.
fromstringNoSender address; an IMAP/SMTP smtp_default_from or the authenticated Gmail address may be used when omitted.
toarray or stringNoPrimary recipients.
ccarray or stringNoCarbon-copy recipients.
bccarray or stringNoBlind-carbon-copy recipients.
reply_toarray or stringNoReply-to addresses.
subjectstringYesMessage subject; an empty subject is allowed.
textstring or nullNoPlain-text body; provide text, html, or both.
htmlstring or nullNoHTML body; provide text, html, or both.
attachmentsarrayNoLocal file descriptors with path, and optional filename and content_type.
in_reply_tostringNoMessage identifier for the In-Reply-To header.

Outputs

OutputTypeMeaning
message_idstring or nullProvider message identifier, when available.
rfc_message_idstringRFC Message-ID returned by the provider.
thread_idstring or nullProvider thread identifier, when available.
error (on_error)stringSanitized 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.