Repository navigation
TorQ email modularization - #88
Conversation
| @@ -0,0 +1,428 @@ | |||
| / module for sending html emails via the system sendmail utility | |||
There was a problem hiding this comment.
All comments should be double comments "//" as opposed to "/"
| / sendmail utilities (ported from qmail) | ||
| / ============================================================ | ||
|
|
||
| utilityexists:{not 0b~@[system;"which ",x," 2>/dev/null";{0b}]}; |
There was a problem hiding this comment.
I think you can simplify this to:
utilityexists:{@[system;"which ",x," 2>/dev/null";0b]};
|
Some thoughts:
|
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>
DIReview Summary1 critical | 3 warning(s) | 0 suggestion(s)
|
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>
DIReview Summary0 critical | 4 warning(s) | 1 suggestion(s)
Suggestions
|
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>
DIReview Summary0 critical | 0 warning(s) | 1 suggestion(s)
Suggestions
|
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>
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
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>
DIReview Summary0 critical | 1 warning(s) | 2 suggestion(s)
Suggestions
|
…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>
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
alowrydi
left a comment
There was a problem hiding this comment.
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,senddataandtest.
What's good
- CR/LF header-injection guard on
to/cc/subject shquoteon shell arguments- SMTP credentials in a
0600file forcurl --config, so they never appear inps - temp-file cleanup on every path
logas a required dependency with no fallback
Also worth fixing in this PR
- Test count:
test.csvhas 290 rows, but the PR description still says 273. - Style:
style.mdasks 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.
| if[historyenabled;.z.m.loghistory[msgdict`to;msgdict`subject;`disabled;-1]]; | ||
| :-1; | ||
| ]; | ||
| to:","sv string$[-11h=type msgdict`to;enlist msgdict`to;msgdict`to]; |
There was a problem hiding this comment.
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?
|
|
||
| ```q | ||
| email:use`di.email | ||
| log:use`di.log |
There was a problem hiding this comment.
log:usedi.log throws an assign error (log is reserved in KDB-X). Suggest mylog:usedi.util.log then email.init[cfg;mylog.logdict]
| 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;()!()] |
There was a problem hiding this comment.
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.
| 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;()!()] |
There was a problem hiding this comment.
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.
| 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]]; |
There was a problem hiding this comment.
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.
| 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]]]; |
There was a problem hiding this comment.
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.
| .z.m.smtpuser:""; | ||
| .z.m.smtppassword:""; | ||
| .z.m.smtpssl:1b; | ||
| logdict:$[99h=type deps;$[(`log in key deps) and not (::)~deps`log;deps`log;()!()];()!()]; |
There was a problem hiding this comment.
This accepts a log dict missing warn/error. Worth adding checks for consistency.
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>
| enabled:0b; | ||
|
|
||
| / controls whether senddefault appends rows to history - overwritten by init | ||
| historyenabled:1b; |
There was a problem hiding this comment.
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].
|
|
||
| addcolor:{mailcolors[x;"";"";y]}; | ||
| mailsize:{mailcolors["";"";x;y]}; | ||
| mailbgcolor:{mailcolors["";x;"";y]}; |
There was a problem hiding this comment.
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).
| / escape the characters that change meaning in html; & first or the others get double escaped | ||
| htmlescape:{[x] ssr[ssr[ssr[x;"&";"&"];"<";"<"];">";">"]}; | ||
|
|
||
| / turn one body element into zero or more lines |
There was a problem hiding this comment.
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;...].
| (0h=type x) and all 10h=type each x;x; | ||
| enlist -3!x] | ||
| }; | ||
|
|
There was a problem hiding this comment.
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.
DIReview Summary3 critical | 1 warning(s) | 0 suggestion(s)
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| / 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]]; |
There was a problem hiding this comment.
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.
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
alowrydi
left a comment
There was a problem hiding this comment.
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
-fsurvives a'in the address. - Real curl against a local fake relay:
smtpurland credentials are used (including'and"in the password), andtoandccall become RCPT. So the Nov 5 bot threads on bare names don't hold. - Docs: the
mylog.logdictexample works. The timer job clears history when it fires (run at 100ms rather than 1D). - TorQ wording: the
to,cc,subjectand "must be specified" messages match the strings intorQemail.so. The param message and thedi.email:prefix differ, and it's nowattachments.
Please fix before merge
- A bare string body is split per character.
body:"hello"sends one<p>per character and returns1b, because the footer is joined beforebodylinesruns. TorQ's lib accepts "a char array or a list of char arrays", so ported code can hit this. Please normalise a string body withenlistbefore the join. history.recipientsdoesn't stay symbol. After one multi-recipient send the column becomes0h, and then filtering it withselect from history where recipients=...signals'type.clearhistorykeeps the0h, 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--usersent fine. Please only write that line whensmtpuseris 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.mdwants a multi-line function's comment on the line after the declaration.headersafe,htmlpart,imagepart,attachpart,bodylines,msgerror,dataaslinesandcleantmpdirput it above.colorhsv2rgbalso has uppercase names. senddata:- Its own signals skip
logerr. - It signals on a bad message when disabled, where
senddefaultreturns-1. - String filenames return
1band leave a temp directory behind, because they become nested directoriescleantmpdircan't remove. A11h=type key datacheck would catch it. - A
"or newline in a filename ends up in the part headers, so please reject those too.
- Its own signals skip
- Test row 197:
hdel each att1,att2has an unquoted comma, soatt2is left in/tmpon every run. - curl output: without
-sS, every send writes the progress meter to the process output, and failures are logged only ascurl smtp error: os. - Temp paths:
mktemp /tmp/...ignoresTMPDIR.mktemp -tshould honour it, which is friendlier on client systems and could also solve the test.csv:305 flake. - Empty
to: a nullto(`) passes the "not empty" check and sends with an emptyTo:header. - Failed
init: a re-init with bad deps resetsenabledandmailfrombefore 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 (
mailheadingthroughcolorizestereo) can't be reached from any export, and only tests call them. Either export them or delete them.
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>
| / remove a temp attachment directory and everything in it | ||
| @[hdel;;::]each .Q.dd[dir]each key dir; | ||
| @[hdel;dir;::]; | ||
| }; |
There was a problem hiding this comment.
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.
| / 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; |
There was a problem hiding this comment.
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.
| / 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) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
DIReview Summary2 critical | 2 warning(s) | 0 suggestion(s)
|
|
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
left a comment
There was a problem hiding this comment.
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 afterclearhistory.- 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.
initsignals before it touches the logger, andecho $?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.
addressed Eoghan's comments in the PR, he's busy on client side so dismissing this to be able to merge
Email
email.qprovides a self-contained HTML email module. It supports two transports: the systemsendmailutility, or SMTP viacurl. The HTML template and sendmail transport are ported from qmail.Ported from TorQ's
code/common/email.q, without thetorQemail.soC library — each send shells out tosendmailorcurl, so there is no per-platform build and no persistent connection.di/email/email.mdis 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:
smtpurlis configured. See Sendmail setup (msmtp) below.smtpurlis set in config. Most systems have this by default.Unix only: the module needs
which,mktemp,base64,fileand/tmp.Sendmail setup (msmtp)
msmtpis the recommended sendmail transport. It acts as a drop-insendmailreplacement and routes mail through an SMTP relay.1. Install
msmtp-mtacreates the/usr/sbin/sendmailsymlink that the module uses.2. Configure
Create
~/.msmtprc:Set permissions (msmtp refuses to run if the file is world-readable):
chmod 600 ~/.msmtprcFor Gmail,
passwordmust be an App Password — not your account password. App Passwords require 2-Step Verification to be enabled on the account.3. Test outside q
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.mailfrom"kdbx@localhost"enabled0b1bto allow emails to be senthistoryenabled1b0bto stop recording sends inhistoryimg`(none)smtpurl"""smtp://smtp.gmail.com:587". When set, curl is used instead of sendmailsmtpuser""smtppassword""0600file read bycurl --config, so it never appears in the command line or inpssmtpssl1b--ssl-reqd). TorQ'susessldefaulted to0b; Gmail will not advertise AUTH without itDependencies
Passed as the second dictionary to
init.`log`info`warn`error, each{[c;m]}. Required —initthrows if absent. Seedi.util.log.The transport is chosen automatically: curl SMTP when
smtpurlis 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:0jsent,-1jfailed or disabled — a status marker, not the message size)Main Functions
initParameters:
[config; deps]Initialises the module. Pass
(::)for config to use defaults (email disabled, sendmail transport). Alogdependency is always required.senddefaultParameters:
[msgdict]Sends an HTML email.
msgdictkeys:to— symbol or symbol list of recipientssubject— stringbody— 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 appendedcc— (optional) symbol or symbol list. Gets aCc:header and is added to the envelope recipientsattachments— (optional) hsym or list of hsyms (TorQ's singularattachmentis warned about)Returns
1bon success,0bon send failure,-1if disabled.senddataParameters:
[msgdict]As
senddefault, butattachmentsis 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.testParameters:
[to]Sends a test email to
to(symbol). Returns1bon success.getstatus/clearhistory/versionReturn the
historytable, truncate it (preserving schema), and the module version.Usage Examples
Every example requires a logger:
1. Send a plain email via sendmail
2. Send via SMTP, with a cc
3. Attach a q table without writing a file first
4. Testing without real sends
Tests
348 checks.