Skip to content

TorQ email modularization - #88

Merged
DI-Dexter merged 24 commits into
DataIntellectTech:mainfrom
DI-Dexter:Dexter_emailModularization
Nov 6, 2026
Merged

DI-Dexter merged 24 commits into
DataIntellectTech:mainfrom
DI-Dexter:Dexter_emailModularization

Conversation

@DI-Dexter

@DI-Dexter DI-Dexter commented Apr 10, 2026 •

Copy link
Copy Markdown
Collaborator

Email

email.q provides a self-contained HTML email module. It supports two transports: the system sendmail utility, or SMTP via curl. The HTML template and sendmail transport are ported from qmail.

Ported from TorQ's code/common/email.q, without the torQemail.so C library — each send shells out to sendmail or curl, so there is no per-platform build and no persistent connection. di/email/email.md is the full reference, including a "Migrating from TorQ's .email" section covering every rename and behaviour change.

Requirements

One of the following must be installed and configured:

  • sendmail via msmtp — lightweight sendmail replacement. Used when no smtpurl is configured. See Sendmail setup (msmtp) below.
  • curl — used when smtpurl is set in config. Most systems have this by default.

Unix only: the module needs which, mktemp, base64, file and /tmp.

Sendmail setup (msmtp)

msmtp is the recommended sendmail transport. It acts as a drop-in sendmail replacement and routes mail through an SMTP relay.

1. Install

sudo apt install msmtp msmtp-mta

msmtp-mta creates the /usr/sbin/sendmail symlink that the module uses.

2. Configure

Create ~/.msmtprc:

defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        ~/.msmtp.log

account        default
host           smtp.gmail.com
port           587
from           me@example.com
user           me@example.com
password       myapppassword

Set permissions (msmtp refuses to run if the file is world-readable):

chmod 600 ~/.msmtprc

For Gmail, password must be an App Password — not your account password. App Passwords require 2-Step Verification to be enabled on the account.

3. Test outside q

echo -e "To: me@example.com\nSubject: test\n\ntest body" | sendmail me@example.com
cat ~/.msmtp.log

A successful send logs exitcode=EX_OK. If it fails, the log contains the SMTP error.

Configuration

Passed as the first dictionary to init. All keys are optional; pass (::) for defaults.

Key Type Default Description
mailfrom string or symbol "kdbx@localhost" From address on outgoing emails
enabled boolean 0b Set 1b to allow emails to be sent
historyenabled boolean 1b Set 0b to stop recording sends in history
img hsym or string ` (none) Image embedded inline at the foot of every message
smtpurl string or symbol "" SMTP server URL e.g. "smtp://smtp.gmail.com:587". When set, curl is used instead of sendmail
smtpuser string or symbol "" SMTP username
smtppassword string "" SMTP password. Written to a temporary 0600 file read by curl --config, so it never appears in the command line or in ps
smtpssl boolean 1b Require TLS (--ssl-reqd). TorQ's usessl defaulted to 0b; Gmail will not advertise AUTH without it

Dependencies

Passed as the second dictionary to init.

Key Required Type Description
`log yes dict Logger with keys `info`warn`error, each {[c;m]}. Required — init throws if absent. See di.util.log.

The transport is chosen automatically: curl SMTP when smtpurl is set, sendmail otherwise.

Core Structures

  • history (table, .z.m) — Append-only log of every send attempt:
    • time (timestamp), recipients (symbol), subject (any), status (symbol: `sent / `failed / `disabled), bytes (long: 0j sent, -1j failed or disabled — a status marker, not the message size)

Main Functions

init

Parameters: [config; deps]

Initialises the module. Pass (::) for config to use defaults (email disabled, sendmail transport). A log dependency is always required.

senddefault

Parameters: [msgdict]

Sends an HTML email. msgdict keys:

  • to — symbol or symbol list of recipients
  • subject — string
  • body — list of lines. A line starting with < is passed through as HTML; anything else is escaped and wrapped in a styled <p>. Nested lists are flattened and non-strings rendered as text, so TorQ's reporter alert shape works. A timestamp footer is appended
  • cc — (optional) symbol or symbol list. Gets a Cc: header and is added to the envelope recipients
  • attachments — (optional) hsym or list of hsyms (TorQ's singular attachment is warned about)

Returns 1b on success, 0b on send failure, -1 if disabled.

senddata

Parameters: [msgdict]

As senddefault, but attachments is a dictionary of filename to q object — `trades.csv`notes.txt!(tradetable;"some text"). Tables become CSV, strings text, anything else its text form. Written to a private temp directory and removed after the send.

test

Parameters: [to]

Sends a test email to to (symbol). Returns 1b on success.

getstatus / clearhistory / version

Return the history table, truncate it (preserving schema), and the module version.

Usage Examples

Every example requires a logger:

logdep:`info`warn`error!(
  {[c;m] -1 "INFO  [",string[c],"] ",m;};
  {[c;m] -1 "WARN  [",string[c],"] ",m;};
  {[c;m] -2 "ERROR [",string[c],"] ",m;});

1. Send a plain email via sendmail

email:use`di.email
email.init[`mailfrom`enabled!("me@example.com";1b);enlist[`log]!enlist logdep]
email.senddefault`to`subject`body!(`$"ops@example.com";"Deployed";enlist"Build 42 deployed.")

2. Send via SMTP, with a cc

email:use`di.email
email.init[
  `mailfrom`enabled`smtpurl`smtpuser`smtppassword!(
    "me@example.com";1b;"smtp://smtp.gmail.com:587";"me@example.com";"myapppassword");
  enlist[`log]!enlist logdep]
email.senddefault`to`cc`subject`body!(
  `$"ops@example.com";`$"boss@example.com";"Deployed";enlist"Build 42 deployed.")

3. Attach a q table without writing a file first

trades:select sum size by sym from trade
email.senddata`to`subject`body`attachments!(
  `$"ops@example.com";"EOD volume";enlist"see attached";
  (enlist`volume.csv)!enlist trades)

4. Testing without real sends

mocklog:`info`warn`error!({[c;m]};{[c;m]};{[c;m]})
mocksend:{[frm;to;cc;sub;body;att]}
email:use`di.email
email.init[`mailfrom`enabled!("me@example.com";1b);enlist[`log]!enlist mocklog]
.m.di.0email.send:mocksend
email.senddefault`to`subject`body!(`$"a@b.com";"test";enlist"hello")

Tests

k4unit:use`di.k4unit
k4unit.moduletest`di.email

348 checks.

Comment thread di/email/email.q Outdated
@@ -0,0 +1,428 @@
/ module for sending html emails via the system sendmail utility

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All comments should be double comments "//" as opposed to "/"

Comment thread di/email/email.q Outdated
/ sendmail utilities (ported from qmail)
/ ============================================================

utilityexists:{not 0b~@[system;"which ",x," 2>/dev/null";{0b}]};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can simplify this to:
utilityexists:{@[system;"which ",x," 2>/dev/null";0b]};

@jonnypress

Copy link
Copy Markdown
Contributor

Some thoughts:

  • I don't think we need the ability to override the send function in the init function - it makes things too complicated (the send function isn't straight forward). A user can still do this if they like without us providing the ability explicitly, i.e. they can call .email.init[] and then redefine .email.send after the init invocation.
  • I think you should modify the reporter functionality, and remove any TorQ references (and remove any direct attempt to support TorQ functionality). This will live outside of TorQ. I think what that function is really is a wrapper function to allow sending of an email with a specific attachment, which is passed in as a q data object. This is generally useful, so we can support it, but we should make it more generic (e.g. the subject line is hardcoded into that function).
  • It's good to log the email attempts, but we should have a mechanism to switch that off, and an api call to clear out the logging table (which could externally be added to a timer) because that table will have a growing memory footprint

DI-Dexter and others added 5 commits April 16, 2026 17:28
Simplification pass over email.q with the docs and k4unit rows reworked to match.
Committed as-is to free the working tree; not reviewed or run yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
consistency.md requires a VERSION file read into an exported `version`; add
both. Keeping the module's existing // comment style.

Default from-address was torq@localhost; this module stands outside TorQ, so
use kdbx@localhost (code, test and doc together). The provenance comment stays
- wdb.q and merge.q carry the same.

No deps.toml: di.email `use`s no other module, and every deps.toml in the repo
belongs to one that does.

Suite 163/163.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The skill's definition of done wants a test per export. `test` and the new
`version` had none.

version: string, non-empty, semver-shaped - verified to fail against a
malformed VERSION file.
test[]: returns 1b through a mocked send, logs exactly one history row with its
canned subject, and returns -1 when the enabled gate is off.

Suite 163 -> 174, all passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/email/email.q Resolved
Comment thread di/email/email.q Resolved
Comment thread di/email/email.q Resolved
Comment thread di/email/email.q Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

1 critical | 3 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Addresses the DIReview comments on PR DataIntellectTech#88 and Jonny's second review point.

Two of the four review comments were reproducible:

- The SMTP password was interpolated into a single-quoted shell string,
  so a password containing a quote gave arbitrary command execution.
  Verified by sending a password that created a marker file. Added a
  shquote helper and applied it at every interpolation point, including
  encodefile and mimetype, which take caller-supplied attachment paths
  and were quoted weakly or not at all. Credentials now go in a mktemp
  0600 file read via curl --config, so they no longer appear in the
  command line or in ps output.

- mailsend left its temp file behind when the message could not be
  built. smtpsend_ had the same leak for the same reason: mailtemplate
  was evaluated in the argument list of .[f;args;handler], outside the
  trap. Both now build the message before creating any temp file.

The other two comments were name-resolution claims that do not hold.
.z.m is the module namespace, so a bare smtpurl and .z.m.smtpurl are
the same cell; transport selection and the loghistory call both work as
written. The two loghistory call sites were made consistent anyway.

Jonny asked for the attachment capability to be kept generically, with
the object passed in as q data rather than a file path. senddata takes
attachments as a filename!object dict, rendering tables and keyed
tables as csv, strings as text and anything else as its text form, into
a private temp directory that is removed after the send. Names
containing a separator are rejected, since they would otherwise write
outside that directory.

Docs: the HTML helpers were documented as exported but have never been
in the export dictionary, and example 3 called email.ztable, which
cannot resolve. Marked them internal and rewrote the example to supply
html directly.

Suite is 196 checks, all passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/email/email.q Resolved
Comment thread di/email/email.q Resolved
Comment thread di/email/email.q Resolved
Comment thread di/email/test.csv Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 4 warning(s) | 1 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Suggestions

  • di/email/email.q:286 — dataaslines checks (0h=type x) and all 10h=type each x to detect a list of strings. The each iterates over the list's elements, which is correct for a general list. However, 0h=type x is true for a mixed list but also for an empty list (type () is 0h). An empty attachment value (no lines) passes this branch and returns x (an empty list), which is then passed to 0: — this is probably fine, but a truly empty general list where all short-circuits to 1b over zero elements would also pass, so a () value slips through as a list-of-strings. More practically, 10h=type each x applies type to each character of a string — but the outer 0h=type x guard prevents that because a plain string has type 10h, not 0h. The logic is correct for non-empty mixed lists; the only real edge case is () being treated as a list of strings and rendered as an empty file, which is likely acceptable.

From the second round of DIReview comments on PR DataIntellectTech#88.

The smtp cleanup ran `hdel fn; hdel cf` unprotected and in that order.
`hdel` raises on a file that is already gone, so a failure on the first
would skip the second and strand the credentials file. The sequence is
not reachable today, but the ordering was wrong either way: the
credentials file is the sensitive one and is now removed first, and both
deletes tolerate an absent file. senddata's directory cleanup had the
same shape and is fixed with it.

Also adds the coverage the review asked for: non-dict attachments values
other than a symbol atom, and a regression test that a send failing
while building the message leaves no temp file behind.

Two of the four comments in this round do not hold. A failing
`mktemp -d` makes `system` raise, so `dir` can never be the null symbol
the comment describes. And while attachment files do inherit the umask
at 0644, they sit in a 0700 directory, so another user cannot traverse
to them.

Suite is 203 checks, all passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 0 warning(s) | 1 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Suggestions

  • di/email/email.q:289 — @[hdel;;::]each uses a partially-applied @[hdel;;::] as the function iterated by each. In q, @[f;x;h] takes exactly three arguments; @[hdel;;::] is a three-argument trap with the middle argument (the file handle) left as a gap — this is not valid q syntax for creating a partial application of @. The correct form to tolerate individual file deletion failures is {@[hdel;x;::]}each or @[hdel;;::]' if the interpreter supports it. Depending on the q version, @[hdel;;::]each may parse as (@[hdel;;::]) each where @[hdel;;::] throws a rank/parse error at load time rather than being a projectable trap. Use {@[hdel;x;::]}each instead.

From a coverage check of the module against TorQ 5.2.19's code/common/email.q
and the reporter's calls into it.

TorQ's reporter sends with a singular `attachment key:

  .email.senddefault[`to`subject`body`attachment!(...;filepath)]

This module reads only `attachments. A ported caller therefore attached
nothing, got 1b back, and saw no warning - the worst available failure shape
for something whose whole job is delivering a report. senddefault now logs a
warning when it sees the singular key. The test covering it fails without the
warning, so it is not a tautology.

email.md gains a "Migrating from TorQ's .email" section, which it had no
equivalent of. It records the config renames (url, user, password, usessl,
from, debug, img), the attachment key, and three behaviour changes: disabled
returns -1 where TorQ threw, the return value is a boolean rather than a byte
count, and the footer no longer carries proctype/procname/host since there is
no .proc coupling.

Also written down, as not ported rather than missed:

- the torQemail.so layer (connect, disconnect, create, g, getSocket,
  connectdefault, connected, lib, libfile, libexists). There is no C library
  and no persistent connection; each send invokes sendmail or curl. TorQ
  disabled email outright on 64-bit Windows for want of that library.
- img, the configurable image TorQ put at the foot of every message. There is
  no image support here at all.
- sendviaservice/servicesend/servicecallback, which delegated a send to another
  process over .servers and .async. This module takes no servers dependency.

Suite is 214 checks, all passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/email/email.q Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Closes the last capability gap against TorQ's .email, narrows the attachment
warning, and writes down the reasoning behind each omission.

img: TorQ put a configurable image at the foot of every message, via the C
library's `image key. That capability had no equivalent here. The config now
takes an `img` path, sent as an inline MIME part carrying a Content-ID, with the
html body given an <img src="cid:..."> that references it - so the image travels
with the message instead of being fetched from a server. An img makes a message
multipart even with no attachments; unset, a plain message stays single-part
exactly as before, which the suite asserts both ways.

Whether a client renders a cid: image can only be confirmed by sending a real
one, so the k4unit tests assert the MIME structure (one Content-ID, an inline
disposition, and a body reference whose cid matches the part) and manual test O
sends a real png for a visual check.

Attachment warning: narrowed to fire only when `attachments is absent. With
both keys present the plural is used and nothing is lost, so the old message -
"nothing was attached" - was simply false. Raised by review.

email.md gains a "Why these were left out" section. Each omission was a
decision rather than an oversight, and the reasoning was only in review threads
and commit messages: the C library and its platform limits, the cached
connection, the .servers/.async send-via-service trio, the reporter-specific
entry point whose capability senddata now covers generically, the .proc footer,
and debug. It also records that historyenabled and clearhistory exist because
review asked for the history to be switchable and bounded.

Suite is 235 checks; the manual script is 107.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/email/email.q Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 2 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Suggestions

  • di/email/email.q:427 — When img is a plain string in config, hsym$configimg will fail if the string already starts with : (double-colon prefix), and more importantly it will silently accept any string without validating it is a valid path. More critically: hsym configimg casts a general string via `` hsym$ , but `hsym` expects a symbol, not a string — the correct idiom for a string is $":" , configimg or hsym$configimg . The actual bug is that when `config`img` is a string (type 10h), the code does `hsym`$config`img` where `config`img` is already a string — $ `` on a string gives a symbol then hsymre-applies the colon prefix, which double-prefixes any path that already starts with:. For a plain file path string like "/tmp/logo.png", `` hsym$"/tmp/logo.png" produces :/tmp/logo.png `` which is correct, but for an hsym string like ":/tmp/logo.png"it produces ``://tmp/logo.png `` which is wrong. Guard against already-symbol and already-hsym inputs consistently.
  • di/email/email.q:258 — The module-level img:`` ;default is set at load time, butinitalways resets.z.m.imgunconditionally (line 409) before checking config. This means the module-level variableimg(line 258) is effectively dead — it is never read afterinitruns because all call sites use.z.m.img`. The module-level declaration is harmless but misleading; if the intent is to document the default, a comment suffices.

…olve the cid

The embedded image shipped in b68001e did not render. A real send to gmail
came back with a broken-image placeholder: the <img src="cid:..."> was in the
html and the Content-ID matched it, but the client never resolved the one to
the other.

Two reasons, both structural. The image part sat directly in the
multipart/mixed container as a sibling of the html, where a client is entitled
to treat it as an attachment rather than as a resource the html refers to -
RFC 2387 multipart/related is what binds them. And the Content-ID was a bare
token; a content id is a message id, so it needs the addr-spec form with an @.

The html and the image now go in a multipart/related, nested inside the
multipart/mixed that carries any real attachments, and the cid is
img<uuid>@kdbx.local.

The tests passed throughout, which is the point worth recording: they asserted
that the headers were present - a Content-ID, an inline disposition, a cid in
the body - but never that the parts were nested so a client could match them.
Presence was not structure. Four assertions added that fail on the old flat
layout: that the image is in a multipart/related, that the container declares
its root part, that the content id carries an @, and that exactly one blank
line precedes each boundary. Reverting to the flat shape now fails 8 checks.

That last assertion also closes the doubled blank line raised in review. It was
pre-existing - two consecutive parts each contributed one - and emitting the
separator at the call site instead of inside each part removes it.

Suite is 239 checks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/email/email.q Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

@DI-Dexter
DI-Dexter requested a review from alowrydi October 14, 2026 03:02

@alowrydi alowrydi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: di.email

I don't know C so it is hard to compare to the existing torq code, but from playing around with it, this looks like a solid port. Dropping torQemail.so for sendmail/curl makes the module much simpler to deploy, and the "Migrating from TorQ" section is thorough.

What I checked

  • k4unit.moduletestdi.email` passes under KDB-X.
  • Live sends through the sendmail transport (Postfix relaying through Mailjet) all arrived: plain, cc, pre-built HTML table, file attachments, senddata and test.

What's good

  • CR/LF header-injection guard on to/cc/subject
  • shquote on shell arguments
  • SMTP credentials in a 0600 file for curl --config, so they never appear in ps
  • temp-file cleanup on every path
  • log as a required dependency with no fallback

Also worth fixing in this PR

  • Test count: test.csv has 290 rows, but the PR description still says 273.
  • Style: style.md asks for / comments (this file uses //) and no underscores in names (smtpsend_, min_val, …). I haven't flagged these line by line.
  • Docs tip: add a note to the sendmail section that the relay must accept the From address. An unverified sender can be accepted locally and then dropped silently, which is how some of my test messages went missing while still recorded as sent (see comment on line 396 of email.q).

Verdict

Request changes for the inline comment items, which are both small. Happy to approve once they land; the rest can be follow-ups.

Comment thread di/email/email.q
if[historyenabled;.z.m.loghistory[msgdict`to;msgdict`subject;`disabled;-1]];
:-1;
];
to:","sv string$[-11h=type msgdict`to;enlist msgdict`to;msgdict`to];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A string to gets split per character here: senddefault with tosubject`body!("a@b.com";"s";enlist"b") hands "a,@,b,.,c,o,m" to the transport and still returns 1b. test (line 426) has the same issue. Could we validate up front (to/cc symbol or symbol list, subject string) and log via logerr before signalling?

Comment thread di/email/email.md Outdated

```q
email:use`di.email
log:use`di.log

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log:usedi.log throws an assign error (log is reserved in KDB-X). Suggest mylog:usedi.util.log then email.init[cfg;mylog.logdict]

Comment thread di/email/email.md Outdated
email.init[`mailfrom`enabled!("me@example.com";1b);enlist[`log]!enlist logdep]

/ clear history every 24 hours
timer.addjob[`emailhistoryclear;email.clearhistory;();0D01:00:00:00;`repeat;()!()]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0D01:00:00:00 is one hour, not 24 (1D is a day). Also, timer.addjob in di.timer is a dict of variants (addjob.custom[id;func;params;period;mode;opts]), and timer.init takes a single [configs] argument, so this example doesn't run as written.

Comment thread di/email/email.q Outdated
clearhistory:{[]
// truncate the history table; schema is preserved
// to clear on a schedule via di.timer:
// timer.addjob[`emailhistoryclear;email.clearhistory;();0D01:00:00:00;`repeat;()!()]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0D01:00:00:00 is one hour, not 24 (1D is a day). Also, timer.addjob in di.timer is a dict of variants (addjob.custom[id;func;params;period;mode;opts]), and timer.init takes a single [configs] argument, so this example doesn't run as written.

Comment thread di/email/email.q Outdated
msg:mailtemplate[frm;to;cc;sub;body;att];
fn:hsym`$first system"mktemp /tmp/qmail.XXXXXXXXXX";
.[{[a;b]a 0: b};(fn;msg);{[fn;e]hdel fn;'"sendmail write error: ",e}[fn]];
@[system;"sendmail -t < ",(shquote 1_string fn);{[fn;e]hdel fn;'"sendmail error: ",e}[fn]];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No -f here, so the envelope sender is the OS user rather than mailfrom. Adding -f ",shquote mailfrom keeps them aligned; relays like Mailjet are pickier when they differ.

Comment thread di/email/email.q
att:$[`attachments in key msgdict;$[-11h=type msgdict`attachments;enlist msgdict`attachments;msgdict`attachments];""];
res:.[send;(mailfrom;to;cc;msgdict`subject;htmlbody;att);{[e].z.m.logerr[`email;"send failed: ",e];0b}];
ok:not res~0b;
if[historyenabled;.z.m.loghistory[msgdict`to;msgdict`subject;`failed`sent ok;$[ok;0j;-1j]]];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sent / 1b only means the local MTA accepted the message. In my testing, six messages the relay later dropped were all recorded as sent. Worth saying so in the md, under senddefault's return values.

Comment thread di/email/email.q Outdated
.z.m.smtpuser:"";
.z.m.smtppassword:"";
.z.m.smtpssl:1b;
logdict:$[99h=type deps;$[(`log in key deps) and not (::)~deps`log;deps`log;()!()];()!()];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This accepts a log dict missing warn/error. Worth adding checks for consistency.

DI-Dexter and others added 3 commits November 5, 2026 17:02
Matches the checks, order and wording of TorQ's emailSend. Also checks the log dict's keys, removes underscores from names and corrects the logger and timer examples in the docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread di/email/email.q
enabled:0b;

/ controls whether senddefault appends rows to history - overwritten by init
historyenabled:1b;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The transport selection reads the module-level variable smtpurl directly instead of .z.m.smtpurl. At the end of init, .z.m.smtpurl is assigned from config but the guard $[count smtpurl;smtpsend;mailsend] reads the top-level smtpurl (which is always "" because it is never written back to the module-level name — only .z.m.smtpurl is updated). This means curl SMTP transport is never selected regardless of what is passed in config. Fix: change $[count smtpurl;smtpsend;mailsend] to $[count .z.m.smtpurl;smtpsend;mailsend].

Comment thread di/email/email.q Outdated

addcolor:{mailcolors[x;"";"";y]};
mailsize:{mailcolors["";"";x;y]};
mailbgcolor:{mailcolors["";x;"";y]};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

smtpsend reads smtpurl, smtpuser, smtppassword, and smtpssl as bare names, but init stores them in .z.m.smtpurl, .z.m.smtpuser, .z.m.smtppassword, and .z.m.smtpssl. The bare names resolve to the module-level defaults ("", "", "", 1b) and never to the values configured via init. Fix: replace each bare reference in smtpsend with the .z.m. prefixed version (e.g. .z.m.smtpurl, .z.m.smtpuser, .z.m.smtppassword, .z.m.smtpssl).

Comment thread di/email/email.q Outdated
/ escape the characters that change meaning in html; & first or the others get double escaped
htmlescape:{[x] ssr[ssr[ssr[x;"&";"&amp;"];"<";"&lt;"];">";"&gt;"]};

/ turn one body element into zero or more lines

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mailtemplate reads .z.m.img to decide whether to embed an image, but it is called at module-load time (in tests) and also by mailsend/smtpsend which are themselves module-level functions that capture their environment at definition time. More critically, mailtemplate also reads .z.m.img directly — this is correct IF mailtemplate is always called from within the module context. However mailsend and smtpsend are assigned to .z.m.send and called via .[send;...] in senddefault, where send is a bare module-level alias. The bare send resolves to the module-level send variable (initialised to mailsend at line ~248), not .z.m.send. When senddefault calls .[send;...] it calls the stale module-level send, not the one stored in .z.m.send after init. Fix: change the call in senddefault from .[send;...] to .[.z.m.send;...].

Comment thread di/email/email.q
(0h=type x) and all 10h=type each x;x;
enlist -3!x]
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When email is disabled and historyenabled is 1b, senddefault calls .z.m.loghistory[msgdict\to;msgdict`subject;`disabled;-1]before the message has been validated. Ifmsgdictis not a dictionary (e.g. it is a string),msgdict`tothrows, signalling an error instead of returning-1cleanly. The enabled-gate is supposed to short-circuit all validation; the history write should guard against a non-dictmsgdictor defer to after the type check. Fix: wrap the history call with a guard such asif[99h=type msgdict;...]or use@[msgdict;`to;`::]` to tolerate a missing key.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

3 critical | 1 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread di/email/email.q
/ signals if an enabled send has a missing field, or a to, cc, subject or attachments of the wrong type
if[not enabled;
.z.m.logerr[`email;"email sending is not enabled"];
if[historyenabled and 99h=type msgdict;.z.m.loghistory[msgdict`to;msgdict`subject;`disabled;-1]];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard 99h=type msgdict is only added inside the not enabled branch, but the call to msgerror msgdict on the next line (outside this branch) still indexes into msgdict assuming it is a dict. If enabled is true and msgdict is not a dict (e.g. a string), execution falls through to if[count err:msgerror msgdict;…] and then to msgdict\to/msgdict`subjectetc., where indexing a non-dict will signal a type error rather than returning a clean error. The non-dict guard needs to be applied at the top ofsenddefault`, before any branch, not only inside the disabled path.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

@alowrydi
alowrydi self-requested a review November 5, 2026 13:16

@alowrydi alowrydi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nearly there. All the earlier threads are fixed, but testing live turned up a few small things to fix before merge, so requesting changes.

Verified at 3b45463

  • Suite: 335/335 when test.csv:305 doesn't trip (see below). The branch is clean against current main and only touches di/email.
  • Stand-in sendmail: a multipart message with image, attachment and cc parses cleanly, and -f survives a ' in the address.
  • Real curl against a local fake relay: smtpurl and credentials are used (including ' and " in the password), and to and cc all become RCPT. So the Nov 5 bot threads on bare names don't hold.
  • Docs: the mylog.logdict example works. The timer job clears history when it fires (run at 100ms rather than 1D).
  • TorQ wording: the to, cc, subject and "must be specified" messages match the strings in torQemail.so. The param message and the di.email: prefix differ, and it's now attachments.

Please fix before merge

  • A bare string body is split per character. body:"hello" sends one <p> per character and returns 1b, because the footer is joined before bodylines runs. TorQ's lib accepts "a char array or a list of char arrays", so ported code can hit this. Please normalise a string body with enlist before the join.
  • history.recipients doesn't stay symbol. After one multi-recipient send the column becomes 0h, and then filtering it with select from history where recipients=... signals 'type. clearhistory keeps the 0h, and the disabled path can store a string. The md documents this column as symbol. A single comma-joined symbol would keep it simple.
  • Sending without credentials fails if the relay advertises AUTH. The config always writes user = ":", so curl attempts AUTH with empty credentials. My fake relay rejected that and curl exited 67, while plain curl with no --user sent fine. Please only write that line when smtpuser is set.
  • test.csv:305 is flaky. before=tmpcount[] counts everything in /tmp, and the suite scored 334/335 in 2 of my 4 runs on a shared box. Count only the module's own temp files, or give the test a private directory.
  • Comments break style.md. It says comments state what the code does and need nothing outside the repo. Several explain why or refer to TorQ, for example "silently sending nothing… is the worst failure shape available", "TorQ's .email.senddefault took a singular", "a nested list of strings arrives as a single element from TorQ's reporter", and "the checks, order and wording of TorQ's emailSend". Please cut each to a one-line what. The rationale already lives in the md.

Nits, fine as a follow-up

  • Comment placement: style.md wants a multi-line function's comment on the line after the declaration. headersafe, htmlpart, imagepart, attachpart, bodylines, msgerror, dataaslines and cleantmpdir put it above. colorhsv2rgb also has uppercase names.
  • senddata:
    • Its own signals skip logerr.
    • It signals on a bad message when disabled, where senddefault returns -1.
    • String filenames return 1b and leave a temp directory behind, because they become nested directories cleantmpdir can't remove. A 11h=type key data check would catch it.
    • A " or newline in a filename ends up in the part headers, so please reject those too.
  • Test row 197: hdel each att1,att2 has an unquoted comma, so att2 is left in /tmp on every run.
  • curl output: without -sS, every send writes the progress meter to the process output, and failures are logged only as curl smtp error: os.
  • Temp paths: mktemp /tmp/... ignores TMPDIR. mktemp -t should honour it, which is friendlier on client systems and could also solve the test.csv:305 flake.
  • Empty to: a null to (`) passes the "not empty" check and sends with an empty To: header.
  • Failed init: a re-init with bad deps resets enabled and mailfrom before it signals. Validate first.
  • Docs: "TorQ's checks, in the same order and with the same wording" overstates it, since the body, bodyType and image checks are gone and it's now attachments.
  • Unreachable helpers: about 50 lines of html helpers (mailheading through colorizestereo) can't be reached from any export, and only tests call them. Either export them or delete them.

DI-Dexter and others added 2 commits November 6, 2026 11:57
Also validates senddata and init up front, honours TMPDIR, reports curl's own errors, and trims comments to style.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Removes the qmail table, colour and formatting helpers, which no export can reach and TorQ never used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread di/email/email.q
/ remove a temp attachment directory and everything in it
@[hdel;;::]each .Q.dd[dir]each key dir;
@[hdel;dir;::];
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The curl command wraps output in a subshell (curl ... ; echo $?) and captures it into r, then checks last r against "0". But when curl succeeds and produces no stdout (which is normal — curl writes progress/errors to stderr, not stdout), -sS suppresses progress, so the only line in r is "0". However when curl fails, the error goes to stderr (redirected with 2>&1), so r contains the error lines followed by the exit-code line. The check (enlist"0")~last r is correct for the success case, but the error branch does '"curl smtp error: "," " sv -1_r— it drops the last element (the exit code) and joins the rest. If curl produces no stderr output before exiting non-zero,-1_ris empty and the error message is"curl smtp error: "with no detail. More critically: when curl succeeds but also prints any unexpected stdout,last rwould not be"0"and a successful send would be reported as an error. The logic assumes curl produces zero stdout lines on success, which is fragile. Theecho $?approach is only reliable if curl's own stdout is suppressed entirely; the command should redirect curl's stdout to /dev/null (e.g.> /dev/null`) or use a temp file for the message upload check, not mix curl's output with the exit code.

Comment thread di/email/email.q
/ a q object as file lines: a table as csv, strings as text, anything else its text form
$[.Q.qt x;csv 0: x;
10h=type x;enlist x;
(0h=type x) and all 10h=type each x;x;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When smtpuser is empty (count smtpuser is 0), the curl config file cf is created by tmppath"" but never written to and never removed: cleansmtptmp[cf;fn] still deletes it, so the file is removed on the happy path. However if the .[{[a;b]a 0: b};(fn;msg);onwritefail] line throws, onwritefail calls cleansmtptmp[cf;fn] which also handles the empty-credentials case correctly. So the empty-file case is actually safe. The real issue is that cfgfile (an empty 0600 file) is passed to --config regardless of whether credentials were written. An empty curl config is harmless, but it means a temp file is always created and passed even when there are no credentials, which is misleading. Consider skipping --config entirely when smtpuser is empty.

Comment thread di/email/email.q
/ smtppassword (string) - smtp password
/ smtpssl (boolean) - require tls (default 1b)
/ img (hsym or string) - image embedded at the foot of every message
/ pass (::) for config to use defaults (email disabled, sendmail transport)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The init function now validates logdict and sets .z.m.loginfo/.z.m.logwarn/.z.m.logerr BEFORE setting .z.m.mailfrom, .z.m.enabled, .z.m.historyenabled, and the other module state. If the log validation passes but a later statement throws (e.g. the img hcount check at line ~400), .z.m.loginfo etc. will have been updated to the new logger while .z.m.mailfrom, .z.m.enabled, etc. remain at their old values — a partially-applied init leaving the module in an inconsistent state. The existing Test 63 asserts the logger is unchanged after a failed init, but with this ordering the logger IS changed before the config is applied. The log validation block (lines 368-371) was moved to before the state assignments, which means a failed init now corrupts the logger. Move the .z.m.loginfo/warn/err assignments to after all other state is set, so a throw before that point leaves the module fully unchanged.

Comment thread di/email/test.csv
true,0,0,q,"""di.email: senddata attachments must be a dict of filename!qobject""~baddata 42",1,1,not a dict
true,0,0,q,"""di.email: senddata needs a dictionary""~@[email.senddata;""hello"";{x}]",1,1,a message that is not a dictionary
true,0,0,q,"""di.email: senddata needs an attachments dict of filename!qobject""~@[email.senddata;`to`subject`body!(`$""a@b.com"";""subj"";enlist""b"");{x}]",1,1,no attachments
true,0,0,q,7=count select from emaillogs where lvl=`error,1,1,each one is logged

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test 63 at line 441 asserts mocklog[info]~.m.di.0email.loginfo(the logger is unchanged after a failed init), but in the newinitordering inemail.qthe log dependency checks and.z.m.loginfoassignment happen BEFORE the config is applied. The failed init in the test passes the log check (onlyinfokey present, missingwarn/error), so the test would signal at the not allcheck — but.z.m.loginfowill already have been overwritten with the partial log dict'sinfofunction before the signal fires. The test assertion thatloginfo` is unchanged will therefore FAIL with the new code order.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

2 critical | 2 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

@DI-Dexter

Copy link
Copy Markdown
Collaborator Author

Thanks Aaron, I've made the changes to address your comments. That covers the five must-fix items and the nits, and I've also removed the unreachable HTML helpers rather than exporting them.

The one thing I've left unchanged is the null to, to match TorQ: torQemail.so accepts it and sends with To: <>. In practice the relay decides. msmtp refuses it with no recipients found, and Gmail over curl refuses it with RCPT failed: 553, so senddefault returns 0b in both cases. A permissive relay would accept it, as you found, and a local test relay did the same. This is documented in email.md.

I also checked DIReview's latest comments, and the critical ones don't hold. The test suite passes, including the Test 63 row it says would fail.

@alowrydi
alowrydi self-requested a review November 6, 2026 10:00

@alowrydi alowrydi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. I re-reviewed 90eb54a and 8f60551 and ran them.

Verified at 8f60551

  • Suite: 348/348 on all 8 runs, including 3 at once and one on top of current main. The test.csv:305 flake is gone and the suite leaves no temp files.
  • Bare string body: renders as one line.
  • history.recipients: stays symbol after a multi-recipient send, when disabled and after clearhistory.
  • Credentials (real curl against a local fake relay advertising AUTH): no credentials sends no AUTH and succeeds. With credentials, a password containing ' and " arrives intact. Curl's error text now reaches the log.
  • TMPDIR: works with a space, a ' or empty, and leaves nothing behind.
  • Removed helpers: nothing on main or in the POC uses them.
  • Latest DIReview threads: the Test 63 one and the curl stdout one don't hold. init signals before it touches the logger, and echo $? is always the last line. The empty config file is harmless.

Eoghan's earlier request for changes is still open. His points now look fixed or documented, so probably fine to dismiss.

@DI-Dexter
DI-Dexter dismissed eohara-di’s stale review November 6, 2026 10:16

addressed Eoghan's comments in the PR, he's busy on client side so dismissing this to be able to merge

@DI-Dexter
DI-Dexter merged commit 34933c0 into DataIntellectTech:main Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants