=== 404ops AI Email Manager ===
Contributors: spwhite
Tags: email, imap, ai, automation, analytics
Requires at least: 7.0
Tested up to: 7.1
Requires PHP: 8.0
Stable tag: 1.10.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Bring your mailboxes into WordPress: IMAP sync, AI classification with privacy redaction, a team inbox and analytics.

== Description ==

404ops AI Email Manager reads your mailboxes over IMAP into WordPress, sorts new mail with the AI connection you set up once for all 404ops plugins, and gives your team one admin inbox to work from. Bring your own key: OpenAI, Anthropic, Google Gemini, OpenRouter, any OpenAI-compatible endpoint, or Ollama (local).

Features:

* Any number of mailboxes, each with an owner, private or shared with the team
* Gmail and Microsoft 365 / Outlook.com sign-in with OAuth (IMAP and SMTP XOAUTH2): no stored mailbox password, a setup checklist for each provider, and a directory (tenant) setting for Microsoft applications registered for one organisation
* AI classification with thread and sender context, per-message AI summaries and AI-drafted replies
* Privacy redaction: email addresses, phone numbers, postal addresses, account numbers and secrets are replaced with stable placeholders before anything reaches the AI provider, and the Inbox shows exactly what a message sends
* Replies and forwards from the Inbox through the mailbox's own SMTP server, with reply templates
* Team collaboration: assignment, internal notes, and a reply lock so two people do not answer the same customer twice
* Rules described in plain language, reviewed row by row before anything is saved
* Dashboard and analytics
* Optional per-site retention for local messages, notes, audit entries and rule history on supported hosts
* Mailbox passwords and OAuth tokens encrypted at rest; personal data export and erase
* WP-CLI commands for sync, classification and status

This plugin reads mail; it never changes or deletes mail on the mail server.

An optional Pro add-on, 404ops AI Email Manager Pro, adds what the free plugin does not do: a hand-built rule builder; changes on the mail server (read, flag, move, archive, Trash) from the Inbox or through an approval list; an AI inbox cleanup plan that you review before anything is applied; and automatic replies held for approval. Everything above stays free.

== Installation ==

1. Upload the plugin zip to `Plugins > Add New` and activate it.
2. Open `404ops > AI Email Manager` in the admin sidebar. The `404ops` item is shared with any other 404ops plugin on the site, and `AI Email Manager` opens this plugin's Dashboard. Every other screen below is reached from the navigation row across the top of that page, not from the sidebar.
3. From that navigation row, choose `Email Accounts` to add an IMAP account. (The plugin uses a built-in pure-PHP IMAP client, so the PHP `imap` extension is not required; installing it only speeds up MIME decoding.)
4. Connect an AI provider on `404ops > AI Connection` and tick `404ops AI Email Manager` in its "Plugins using this connection" list -- until you do, nothing is classified and nothing is sent. Choose `AI Prompts` from the same row to see whether this plugin is connected and to edit the prompts.
5. Choose `Inbox` to view ingested emails, and `Analytics` for metrics.

== External services ==

Mail servers and sign-in:

* The IMAP and SMTP servers you configure for each mailbox are contacted to read and send mail. The Gmail and Microsoft presets use `imap.gmail.com` with `smtp.gmail.com`, and `outlook.office365.com`.
* Gmail sign-in, only if you connect with OAuth: `accounts.google.com` and `oauth2.googleapis.com`.
* Microsoft 365 and Outlook.com sign-in, only if you connect with OAuth: `login.microsoftonline.com`.

AI classification and summaries:

This plugin downloads email from the mailboxes you configure and, when an AI
connection is enabled for it, sends part of each message to that provider so it
can be classified. Message content therefore leaves your server. What is sent, on
every classification, is the message subject, the sender address and name, and
the first 1000 characters of the plain-text body. When the mailbox already
holds earlier context for the message, the classification also carries it, in
a block capped at 2048 bytes: the subjects and short body excerpts (350
characters each) of up to three earlier messages of the same thread in the
same mailbox, matched by subject with Re:/Fwd: prefixes ignored, and the
counts of the sender's earlier classifications. Everything in that block is
content this plugin already stored; nothing new is collected for it, and a
first message from an unknown sender is sent exactly as before, with no block.
The Inbox marks a verdict that was made with this context. Pressing Summarize
on a message in the Inbox sends the same fields to the same provider, with the
first 2000 characters of the plain-text body; the summary is shown in the
message view and cached per message for a day, so a second press is answered
from the cache instead of the provider. Attachments, the HTML body and the
raw headers are never transmitted.

Before any request leaves the site, the plugin replaces email addresses,
phone numbers, postal addresses, account and card numbers, and passwords,
codes and keys in it with placeholders such as [EMAIL_1] (an address keeps
its domain unless you turn that off). The provider's answer comes back with
the real values put back in, except secrets. This is on by default; an
administrator can switch each kind off on the AI Prompts screen. Detection is
by pattern, so personal names are not replaced and an unusually written
value can pass through: "What is sent to the AI" in the Inbox shows the exact
request a message makes, without sending it.

Pressing "Propose rules" on the Rules screen sends one further request to the
same provider: the rule schema (the exact condition fields, operators, actions
and classification values the plugin can validate), the current stored
ruleset, and the description you typed, redacted as above. No message
bodies and no stored mail of any kind is sent. The proposal comes back for
review only -- nothing is saved until you accept rows, each acceptance is
re-validated server-side, and a proposal expires after 30 minutes.

An add-on (such as the optional Pro add-on's inbox cleanup plan) may send
further requests through this plugin; they go to the same provider, through
the same redaction, and that add-on's readme says what they contain.

Only the provider on the AI Connection screen is contacted, and only when this
plugin is ticked in that screen's "Plugins using this connection" list. The
connection (provider, model, key, endpoint) is shared by every 404ops plugin
and is configured on that screen, not in this plugin; this plugin never sees or
stores the key. A further request reaches the same provider from that screen
itself: its "Test connection" button sends a short fixed test request
containing no email data, and sends your API key.

OpenAI
Classification: https://api.openai.com/v1/chat/completions
Terms: https://openai.com/policies/terms-of-use
Privacy: https://openai.com/policies/privacy-policy

Anthropic
Classification: https://api.anthropic.com/v1/messages
Terms: https://www.anthropic.com/legal/consumer-terms
Privacy: https://www.anthropic.com/legal/privacy

Google Gemini
Classification: https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent
Terms: https://ai.google.dev/gemini-api/terms
Privacy: https://policies.google.com/privacy

OpenRouter
Classification: https://openrouter.ai/api/v1/chat/completions
Terms: https://openrouter.ai/terms
Privacy: https://openrouter.ai/privacy

OpenAI-compatible endpoint
Classification: the base URL you enter on the AI Connection screen, at
{base URL}/chat/completions. Where the message goes, and which terms and
privacy policy apply, is whatever service you point it at.

Ollama
Classification: your own server, http://localhost:11434/api/chat by default
(the address you enter on the AI Connection screen). Ollama is self-hosted, so
with this provider no message content is sent to any third party, and no
remote service's account, terms or privacy policy applies.

Mailbox OAuth (only when you connect a Gmail or Microsoft mailbox with OAuth)

Each mailbox you connect with OAuth causes this site to talk to that
provider's identity platform: the consent screen in your browser, then token
requests from the server carrying your own OAuth client credentials, the
authorization code, or the stored refresh token. What is exchanged is exactly
the OAuth protocol's fields -- never message content. The resulting access
tokens (and your client secret) are stored encrypted, the same as mailbox
passwords. Bring your own credentials: you register your own application in
the provider's console; this plugin operates no service and shares nothing
with 404ops.

Google
Token endpoint: https://oauth2.googleapis.com/token
Consent screen: https://accounts.google.com
The scope requested is Google's IMAP scope (https://mail.google.com/), the
only scope Google grants IMAP/SMTP XOAUTH2 under. Google classifies it as
restricted; while your own application is unverified, the consent screen
shows Google's unverified-app warning, which you proceed through via
Advanced. Verifying your own application removes the warning.
Privacy: https://policies.google.com/privacy

Microsoft
Token endpoint: https://login.microsoftonline.com/common/oauth2/v2.0/token
(or your directory's id or domain in place of "common", when you enter one
with the Microsoft client)
Consent screen: https://login.microsoftonline.com
The scopes requested are Exchange Online's IMAP and SMTP submission scopes
(https://outlook.office365.com/IMAP.AccessAsUser.All and
https://outlook.office365.com/SMTP.Send), plus offline_access so the
connection can be renewed. No Microsoft Graph permission is requested or
used. A tenant administrator can consent for the whole tenant from the
consent screen.
Privacy: https://privacy.microsoft.com/

The plugin also stores the email it downloads -- including the personal data of
people who are not users of this site -- in its own database tables. It
registers a personal data exporter and eraser, so a request about any address
can be answered from Tools > Export Personal Data and Tools > Erase Personal
Data. Suggested privacy policy wording is offered under
Settings > Privacy > Policy Guide.

== Frequently Asked Questions ==

= Do I need API keys? =
Yes for cloud providers (OpenAI, Anthropic, Gemini, OpenRouter) -- entered once on the AI Connection screen, not in this plugin. Ollama can run locally without an API key.

= Are credentials stored securely? =
Mailbox passwords are, and so are OAuth credentials: the access tokens,
refresh tokens and the OAuth client secret a mailbox connection uses are
sealed with the same encryption. Mailbox passwords are encrypted at rest
with Sodium
(sodium_crypto_secretbox) where that extension is available and AES-256-GCM
otherwise, and the Email Accounts form never renders a stored password back
into the page. Where this site has usable wp-config.php secrets the key is
derived from them and never touches the database. Where it does not, the plugin
falls back to generating a random key and saving it in the
ai_email_manager_encryption_key option -- so on such a site the key is stored in
the same database as the encrypted passwords, and the encryption no longer
protects a database dump on its own.

This plugin does not store an AI provider key at all. The AI connection is
shared by every 404ops plugin on the site and is configured once on the AI
Connection screen, which seals the key in the `ops404_ai_settings` option
(XSalsa20-Poly1305, keyed from this site's wp-config.php secrets) and never
shows it again -- leave the field blank to keep it. Treat it as you would any
other secret in wp_options, and rotate it at the provider if the site is ever
compromised.

= Who can see a mailbox and its messages? =
Every mailbox belongs to the person who added it, and it is private unless
they tick "Share with the team" on the Email Accounts screen. A private
mailbox and its messages are seen by its owner and by administrators only. A
shared mailbox is seen by everyone who can open the Inbox (Authors, Editors
and Administrators by default). Whoever can see a mailbox can read its
messages and press Sync; only its owner and administrators can change its
settings, test it, delete it, or share and unshare it. An administrator can
hand a mailbox to another owner from its edit form. Mailboxes added before
this setting existed were given their owner on upgrade and are private; one
whose owner could not be worked out is visible to administrators only until
an administrator assigns one.

= Is email content sent to a third party? =
Yes, when a cloud provider (OpenAI, Anthropic, Gemini, OpenRouter or an
OpenAI-compatible endpoint) is connected on the AI Connection screen and this
plugin is enabled there: the subject, sender and the start of the message body
are sent to it for classification, and again when you press Summarize on a
message, with email addresses, phone numbers, postal addresses, account
numbers and secrets replaced by placeholders first (on by default). Until this
plugin is enabled on a connection, nothing is sent. See "External services"
above for endpoints and policies.
Connect the self-hosted Ollama provider if no content may leave your server.

= Can I answer a GDPR or CCPA request about email this plugin stored? =
Yes. The plugin registers a WordPress personal data exporter and eraser keyed
by email address, so Tools > Export Personal Data and Tools > Erase Personal
Data cover the messages it has ingested, matching both the sender and the To
and Cc recipients. Configured email accounts are reported as retained rather
than deleted, because removing one would stop your mail syncing; delete those
from the Email Accounts screen if they should go.

= How long are stored messages kept? =
Automatic cleanup starts paused on each site. On a supported host, open `404ops > AI Email Manager > Settings > Retention` to review and confirm separate periods for messages, notes, audit entries, rule history and resolved Pro approvals. Enter 0 to keep a category indefinitely or 7 to 3650 days. Previously saved retention and cleanup interval values cannot start the schedule. Importing or resetting settings pauses cleanup until you confirm the policy again.

Each daily WP-Cron run removes a limited batch of eligible records from the local database and leaves mail on your server untouched. A message stays while retained notes, rule history, approval records or an active reply still need it. Explicit rule or account deletion, confirmed privacy erasure and opt-in data removal on uninstall follow their own controls.

Ask your host to check the requirements in the bundled `docs/RETENTION.md` guide before enabling cleanup. Sites on other database configurations can keep using the plugin with scheduled cleanup paused. Before upgrading from an older version, stop scheduled work, drain active requests and update Free first, then Pro. On multisite, review each site's policy separately.

= Can I run the sync or the classification from a script, or check a site from the shell? =
Yes, with WP-CLI. `wp ai-email-manager accounts` lists the accounts on the Email Accounts screen with the id the scheduled sync reads each one under (`sync_id`; "none" means only Sync now on the screen or `wp ai-email-manager sync <id>` fetches that account). `wp ai-email-manager sync <id>`, or `sync --all`, fetches new mail now, without the schedule's 15-minute throttle. `wp ai-email-manager classify` runs one classification pass on the shared AI connection this plugin is enabled on and says how many messages it classified, failed or left for the next pass. `wp ai-email-manager test-connection <id>` signs in and lists the folders. `wp ai-email-manager status` reports the counts, the last sync, the usable provider and the next scheduled runs. Every run is written to the audit log. Passwords and API keys are never printed. There is no REST API: stored messages leave this site only through the export tools under Tools.

= What happens if I uninstall the plugin? =
By default, deleting the plugin keeps its database tables, settings, and synced email attachments, so reinstalling restores everything. Scheduled cron events and internal debris (a legacy unused key file and a debug log) are always cleared on uninstall regardless. To also remove the database tables, settings, and attachments, open `404ops > AI Email Manager`, choose `Settings` from the navigation row at the top of the page, and enable "Remove all plugin data when deleted" in the Uninstall section before deleting the plugin. The shared AI connection (`ops404_ai_settings`) belongs to every 404ops plugin on the site, so deleting this plugin never removes it; with "Remove all plugin data when deleted" enabled, only this plugin's own entry in it (its enable flag) is taken out, and the other plugins' entries and the connection itself stay.

= What happens to the old uploads key file? =
Older versions created an unused `.key` file in the plugin's uploads directory. After an update, the plugin removes a regular `.key` file there when it is 64 bytes long and has the same owner as that directory. A custom file with those same attributes will also be removed. Symlinked key files and plugin directories are left alone. On multisite, the check runs for each site when that site receives a request; a site that is not visited retains its old file until then. This file is separate from the encryption key used to open saved mailbox credentials.

= Where can I get help? =
Visit https://supportminer.404ops.com to open a support request.

== Screenshots ==

1. Dashboard with recent messages, email totals and system status.
2. Inbox with account, classification, status and assignment filters.
3. Rules for handling new mail after classification.
4. AI Prompts with connection status and controls for redacting personal data.
5. Retention settings with separate periods for local records and explicit confirmation before cleanup starts.

== Changelog ==

= 1.10.0 =
* Added per-site, opt-in retention for local mailbox records, notes, audit entries and rule history on supported hosts. The matching Pro add-on supports retention of resolved approvals.
* Analytics message views, daily metrics and exports now use calendar presets that include today. The 7-, 30- and 90-day presets no longer include the extra earlier date from previous versions; Last Year uses an inclusive calendar-year range. Existing records are unchanged. Classification and provider charts can still use different time ranges and clocks.

= 1.9.5 =
* Fixed: uninstall removes this plugin's saved settings and notices through WordPress APIs so their cached copies are cleared too.

= 1.9.4 =
* Maintenance: bundles ai-client 0.4.3, which normalizes the AI Connection nonce before verification and rejects malformed inputs.

= 1.9.3 =
* Added: guarded read-only administrative status interfaces.
* Added: five bundled draft language catalogs with checked WordPress loading.
* Improved: development test-session and catalog packaging checks.

= 1.9.2 =
* Fixed: the plugin no longer writes a key file or a connection log into the public uploads folder, and that folder now carries a deny rule. A failed connection goes to the PHP error log with its error text only, never the mailbox host or port.
* Fixed: importing settings now keeps only the options the Settings screen can save, and cleans each value, instead of storing the file as it came.
* Fixed: the audit log records the address the request came from, not a header the visitor can set.
* Fixed: a malformed page address (?page[]=) no longer raises an error on admin pages, and an inbox search containing an apostrophe now matches.
* Changed: WordPress.org loads the translations; database queries bind table names; successful syncs no longer write a line to the error log on every run.

= 1.9.1 =
* Updated the licence client (0.3.5): Pro keeps working after a licence expires.

= 1.9.0 =
* New: privacy redaction for every AI request. Email addresses, phone numbers, postal addresses, account numbers and secrets are replaced with stable placeholders before anything is sent, and put back into summaries, drafts and proposed rules (secrets never). On by default; each kind can be switched off on the AI Prompts screen, which also has a Try it box.
* New: "What is sent to the AI" in the Inbox shows the exact request a message makes, for a summary and for classification, without sending it.
* New: a directory (tenant) setting for the Microsoft OAuth client, so an application registered for one organisation can sign in.
* New: the Google and Microsoft sign-in screens now suggest the mailbox being connected; the Email Accounts screen shows a setup checklist for each provider and provider-specific guidance on the account form.
* New: a documented hook that lets an add-on offer per-message mail-server buttons in the Inbox. This plugin itself still never changes mail on the server.

= 1.8.5 =
* Updated the bundled licence client to 0.3.4.

= 1.8.4 =
* Listing: real WordPress.org screenshots, with one matching caption each in the Screenshots section. No code change.

= 1.8.3 =
* Fixed a fatal error on the licence screen after activating a Pro licence.

= 1.8.2 =
* Pro update packages now publish with maintenance information and one shared licence client version.

= 1.8.1 =
* Pro update packages now publish with maintenance information.

= 1.8.0 =
* New: the plugin now offers a small, documented set of hooks that an add-on can answer (the boot action, the navigation row, rule actions, held automatic replies, and the mailbox client). With no add-on active every one of them does nothing, and the plugin behaves exactly as before. This plugin itself still never changes or deletes existing mail on the mail server.
* New: the optional Pro add-on (separate plugin) answers them.
* Updated the licence client.

Older entries are in CHANGELOG.md. Recent-release history is also retained in CHANGELOG-ARCHIVE.txt.

== Upgrade Notice ==

= 1.10.0 =
Stop scheduled work and drain active requests before updating Free, then Pro. Review the bundled `docs/RETENTION.md` guide. Automatic cleanup starts paused on every site.

= 1.9.5 =
Update both editions together. Corrects scoped uninstall cache cleanup.

= 1.9.3 =
Includes checked draft translations and administrative status reporting. Human linguistic review is separate.

= 1.9.0 =
Personal data is now replaced with placeholders before any AI request (on by default), the Inbox shows what is sent, and Microsoft single-organisation applications can sign in. Safe to update.

= 1.8.4 =
Listing-only update: new screenshots and captions. No code change.

= 1.8.0 =
Adds hooks for the optional Pro add-on. No change to what the plugin does on its own. Safe to update.

Older entries are in CHANGELOG.md.
