From fcb5cabd822fd3831f8bde43db6cbcac84a02fe1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 13:17:45 +0000 Subject: [PATCH] E-mail: tests with Python's mail clients, docs and the sample configuration The E-mail wiki page (addresses, folders, a smarthost or direct delivery, DNS, the MX and LMTP), the mail sections in bbs.conf.sample, SMTP's 530 for mail before a login, and the TODO section done. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRVPRbt1YgtG7eQJZxD --- README.md | 1 + TODO.md | 33 -- bbs.conf.sample | 71 ++++ docs/wiki/Configuration-Reference.md | 91 +++++ docs/wiki/E-mail.md | 159 ++++++++ docs/wiki/Home.md | 4 + docs/wiki/_Sidebar.md | 1 + internal/email/email_test.go | 567 +++++++++++++++++++++++++++ internal/email/listen.go | 11 +- internal/email/python_test.go | 95 +++++ internal/email/smtp.go | 9 +- 11 files changed, 1002 insertions(+), 40 deletions(-) create mode 100644 docs/wiki/E-mail.md create mode 100644 internal/email/email_test.go create mode 100644 internal/email/python_test.go diff --git a/README.md b/README.md index fb23dda..b170bd0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Main menu - Message areas, private mail, chat, paging and doors (DOS doors in dosemu2, or Linux programs) - File areas with X/Y/ZMODEM, Kermit, IND$FILE and FTP +- E-mail: IMAP, POP3 and SMTP, to and from the internet, directly or through a smarthost - Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, and MRC - Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics - On the web: a forum, image boards, a web terminal and an HTTP API diff --git a/TODO.md b/TODO.md index 5d5f7b3..bae1fc7 100644 --- a/TODO.md +++ b/TODO.md @@ -42,36 +42,3 @@ layer between a door and a 3270 could show them: be tried by hand. - **Shape.** An option on a `[door]` (`tn3270 = yes`) that shows the door on the 3270 Doors menu and puts this layer between them. - -## Email: POP3, IMAP and SMTP - -*Status: pinned; scope not chosen.* - -Private mail already lives in SQLite, one inbox per user with a read flag; -NNTP and FTP already share the BBS's login, throttling and TLS modes, and -`internal/news` already makes and safely decodes RFC 5322/MIME messages. - -- **POP3** (RFC 1939, STLS): small. The inbox is the mailbox, a mail's id - its UIDL, DELE deletes. -- **IMAP** (RFC 3501/9051): moderate, with emersion's go-imap server (v2 - is beta: pin it). INBOX is the inbox, \Seen the read flag; new: a Sent - folder (mail is kept only in the recipient's inbox today), stored flags, - UIDVALIDITY. -- **SMTP**, three jobs: - - *submission* (587, AUTH required, so never an open relay) to BBS users - and FidoNet netmail: small, with emersion's go-smtp; - - *inbound from the internet*: easy code, hard operations (MX, port 25 - often blocked, spam, SPF/DKIM/DMARC checks); - - *outbound to the internet*: queue, retries, bounces, DKIM, SPF/DMARC, - rDNS, IP reputation: most of the long-term trouble. -- **Suggested shape**: phase 1, POP3 + IMAP + submission for BBS users; - phase 2, internet mail through Postfix: inbound delivered to the BBS by - LMTP (go-smtp does LMTP), outbound by a smarthost. The BBS as its own - internet MTA is possible but not advised. -- **To decide**: addresses for names with spaces (`alice.smith@domain`, as - news posters' already are) and collisions; attachments (kept whole for - POP/IMAP, text part plus a list of attachments on terminals, a size - limit); `user@domain` as a third recipient form beside user names and - FidoNet addresses (those have `:` and `/`); app passwords (optional). -- **Testing**: Python's imaplib, poplib and smtplib; Postfix (Ubuntu) for - LMTP and the smarthost. diff --git a/bbs.conf.sample b/bbs.conf.sample index 84b29ad..46bdae4 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -472,6 +472,77 @@ address = 127.0.0.1:2513 ; the addresses it may send us articles from (IHAVE) ;accept_from = news.example.net +; E-mail. Each user is name@domain (bbs mail address NAME shows it), and +; their BBS mail is their e-mail: Inbox, Sent, Drafts, Starred, Unread, +; All Mail and Trash, in any mail program, over POP3 and IMAP. Without +; this section the BBS has no e-mail +;[mail] +;domain = example.org +; this host's name, said in SMTP's greeting and Received lines +;hostname = mail.example.org +; how mail for elsewhere goes: direct (to each domain's MX, port 25), +; smarthost (through [smarthost]) or none (only mail here) +;outbound = direct +; the largest message taken; recipients in one; days in the trash before +; mail is gone (0: until emptied); days the queue keeps trying +;max_message = 10M +;max_recipients = 50 +;trash_days = 30 +;queue_days = 5 +; who gets postmaster@, abuse@ and bounces' notes (default: the sysop) +;postmaster = sysop +; DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS +; record (selector._domainkey.domain) +;dkim_key_file = /etc/bbs/dkim.pem +;dkim_selector = bbs +; the certificate for the mail servers (each can name its own) +;cert_file = /etc/bbs/cert.pem +;key_file = /etc/bbs/key.pem + +; An outgoing mail server to send through, instead of straight to each +; domain's MX: your provider's, or a relay such as Postfix. tls: starttls, +; implicit (port 465) or no. insecure = yes: its certificate unchecked +;[smarthost] +;address = smtp.example.net:587 +;tls = starttls +;username = bbs@example.org +;password = secret +;insecure = no + +; The mail servers: each runs only with its section. tls: no, optional +; (STARTTLS offered), required (STARTTLS before a login) or implicit (TLS +; from the first byte: POP3S 995, IMAPS 993, SMTPS 465). Each takes +; address, tls, cert_file, key_file, max_clients, max_per_ip and +; idle_timeout, as [nntp] does. POP3: mail programs fetch the inbox +;[pop3] +;address = :1110 +;tls = required + +; IMAP: mail programs read and file mail in the folders. Its IDLE wants a +; long idle_timeout +;[imap] +;address = :1143 +;tls = required +;idle_timeout = 1800 + +; mail submission: users send mail, logged in (port 587 or 465) +;[smtp] +;address = :1587 +;tls = required + +; mail from the internet: on port 25, named by the domain's MX record. +; checks = yes: SPF, DKIM and DMARC checked; mail is refused that fails +; a DMARC reject policy, or (no DMARC) fails SPF and is not signed +;[mx] +;address = :25 +;tls = optional +;checks = yes + +; LMTP, for a mail server in front (Postfix's virtual_transport) to hand +; mail in: a unix socket's path or host:port +;[lmtp] +;address = /run/bbs/lmtp.sock + ; FidoNet (or another FTN network). bbs area echo General FSX_GEN makes an ; area an echo; mail to Name@zone:net/node is netmail. Without this section ; the BBS is not on FidoNet diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 98ee3bf..d479f61 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -25,6 +25,13 @@ the file is laid out. | [`[news]`](#news) | Newsgroups: a message area with a newsgroup name (bbs area newsgroup General bbs.general) is a newsgroup, served by NNTP to newsreaders and kept in step with peer news servers. | | [`[nntp]`](#nntp) | The NNTP server. | | [`[peer NAME]`](#peer-name) | A peer news server, one section each. | +| [`[mail]`](#mail) | E-mail. | +| [`[smarthost]`](#smarthost) | An outgoing mail server to send through, instead of straight to each domain's MX: your provider's, or a relay such as Postfix. | +| [`[pop3]`](#pop3) | The mail servers: each runs only with its section. | +| [`[imap]`](#imap) | IMAP: mail programs read and file mail in the folders. | +| [`[smtp]`](#smtp) | mail submission: users send mail, logged in (port 587 or 465) | +| [`[mx]`](#mx) | mail from the internet: on port 25, named by the domain's MX record. | +| [`[lmtp]`](#lmtp) | LMTP, for a mail server in front (Postfix's virtual_transport) to hand mail in: a unix socket's path or host:port. | | [`[fido]`](#fido) | FidoNet (or another FTN network). | | [`[binkp]`](#binkp) | binkp: answer the links' calls. | | [`[link NAME]`](#link-name) | A system we exchange mail with, one section each. | @@ -313,6 +320,90 @@ There may be any number of these, each with its own NAME. | `accept_from` | | | the addresses it may send us articles from (IHAVE) Examples: `news.example.net`. | +## `[mail]` + +E-mail. Each user is name@domain (bbs mail address NAME shows it), and their BBS mail is their e-mail: Inbox, Sent, Drafts, Starred, Unread, All Mail and Trash, in any mail program, over POP3 and IMAP. Without this section the BBS has no e-mail. + +| key | default | live | what it does | +|---|---|---|---| +| `domain` | | | See the section above. Examples: `example.org`. | +| `hostname` | | | this host's name, said in SMTP's greeting and Received lines. Examples: `mail.example.org`. | +| `outbound` | | | how mail for elsewhere goes: direct (to each domain's MX, port 25), smarthost (through [smarthost]) or none (only mail here) Examples: `direct`. | +| `max_message` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `10M`. | +| `max_recipients` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `50`. | +| `trash_days` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `30`. | +| `queue_days` | | | the largest message taken; recipients in one; days in the trash before mail is gone (0: until emptied); days the queue keeps trying. Examples: `5`. | +| `postmaster` | | | who gets postmaster@, abuse@ and bounces' notes (default: the sysop) Examples: `sysop`. | +| `dkim_key_file` | | | DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS record (selector._domainkey.domain) Examples: `/etc/bbs/dkim.pem`. | +| `dkim_selector` | | | DKIM: bbs mail dkim /etc/bbs/dkim.pem makes the key and prints its DNS record (selector._domainkey.domain) Examples: `bbs`. | +| `cert_file` | | | the certificate for the mail servers (each can name its own) Examples: `/etc/bbs/cert.pem`. | +| `key_file` | | | the certificate for the mail servers (each can name its own) Examples: `/etc/bbs/key.pem`. | + + +## `[smarthost]` + +An outgoing mail server to send through, instead of straight to each domain's MX: your provider's, or a relay such as Postfix. tls: starttls, implicit (port 465) or no. insecure = yes: its certificate unchecked. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `smtp.example.net:587`. | +| `tls` | | | See the section above. Examples: `starttls`. | +| `username` | | | See the section above. Examples: `bbs@example.org`. | +| `password` | | | See the section above. Examples: `secret`. | +| `insecure` | | | See the section above. Examples: `no`. | + + +## `[pop3]` + +The mail servers: each runs only with its section. tls: no, optional (STARTTLS offered), required (STARTTLS before a login) or implicit (TLS from the first byte: POP3S 995, IMAPS 993, SMTPS 465). Each takes address, tls, cert_file, key_file, max_clients, max_per_ip and idle_timeout, as [nntp] does. POP3: mail programs fetch the inbox. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1110`. | +| `tls` | | | See the section above. Examples: `required`. | + + +## `[imap]` + +IMAP: mail programs read and file mail in the folders. Its IDLE wants a long idle_timeout. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1143`. | +| `tls` | | | See the section above. Examples: `required`. | +| `idle_timeout` | | | See the section above. Examples: `1800`. | + + +## `[smtp]` + +mail submission: users send mail, logged in (port 587 or 465) + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:1587`. | +| `tls` | | | See the section above. Examples: `required`. | + + +## `[mx]` + +mail from the internet: on port 25, named by the domain's MX record. checks = yes: SPF, DKIM and DMARC checked; mail is refused that fails a DMARC reject policy, or (no DMARC) fails SPF and is not signed. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:25`. | +| `tls` | | | See the section above. Examples: `optional`. | +| `checks` | | | See the section above. Examples: `yes`. | + + +## `[lmtp]` + +LMTP, for a mail server in front (Postfix's virtual_transport) to hand mail in: a unix socket's path or host:port. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `/run/bbs/lmtp.sock`. | + + ## `[fido]` FidoNet (or another FTN network). bbs area echo General FSX_GEN makes an area an echo; mail to Name@zone:net/node is netmail. Without this section the BBS is not on FidoNet. diff --git a/docs/wiki/E-mail.md b/docs/wiki/E-mail.md new file mode 100644 index 0000000..d08f665 --- /dev/null +++ b/docs/wiki/E-mail.md @@ -0,0 +1,159 @@ +With a `[mail]` section each user has an e-mail address, and their BBS +mail is their e-mail. A letter written on a 3270, a modem or the web goes +out to the internet, and mail from the internet arrives in the same inbox +the CompuServe and BBS mail commands read. Mail programs (Thunderbird, +Apple Mail, mutt, K-9) read it over IMAP or POP3 and send over SMTP, logged +in with the BBS name and password. + +``` +; bbs.conf +[mail] +domain = example.org +hostname = mail.example.org +dkim_key_file = /etc/bbs/dkim.pem +cert_file = /etc/bbs/cert.pem +key_file = /etc/bbs/key.pem + +[imap] +address = :993 +tls = implicit + +[pop3] +address = :995 +tls = implicit + +[smtp] ; submission: users send mail, logged in +address = :587 +tls = required + +[mx] ; mail from the internet +address = :25 +``` + +Every server runs only if its section is there. All of them use the BBS's +guard (bans, throttling), and each has `max_clients`, `max_per_ip` and +`idle_timeout`. `tls` is `no`, `optional` (STARTTLS offered), `required` +(no login before STARTTLS) or `implicit` (TLS from the first byte). Ports +below 1024 are bound before the BBS drops root, as the others are. + +## Addresses + +A user's address is their name in lower case, with spaces as dots, at the +domain: `Alice Smith` is `alice.smith@example.org`. `bbs mail address +NAME` prints it. `+tags` are ignored (`alice.smith+lists@` reaches Alice). +`postmaster@`, `abuse@`, `hostmaster@` and `webmaster@` go to `[mail] +postmaster`, or the first sysop. + +When writing mail on the BBS, the recipient can be a user's name, a FidoNet +address (`Name@1:234/5`) or an internet address (`bob@example.net`). In +CompuServe Mail, `>INTERNET:bob@example.net` works as it did there. Mail to +FidoNet's internet form (`john.doe@f5.n234.z1.fidonet.org`) goes as +netmail. + +## Folders + +Mail is kept once. Each user has their own entry for it, with its read and +starred marks, so the same mail sent to five users is stored once. Every +mail program sees the same folders: + +| Folder | Holds | Special-use | +|---|---|---| +| INBOX | mail received, not deleted | | +| Sent | mail sent | `\Sent` | +| Drafts | drafts saved by a mail program | `\Drafts` | +| Starred | starred mail (`\Flagged`) | `\Flagged` | +| Unread | unread mail received | | +| All Mail | everything not deleted | `\All` | +| Trash | deleted mail | `\Trash` | + +Starred, Unread and All Mail are views: starring a mail in the inbox puts +it in Starred, and taking it out of Starred unstars it. Deleting moves mail +to the Trash, where a mail program can restore it (by moving it out) or +expunge it. Mail in the trash longer than `trash_days` (30) is removed for +good. Folders cannot be created or renamed. + +POP3 sees the inbox. Mail retrieved is marked read, and `DELE` puts it in +the trash. + +## Sending to the internet + +`[mail] outbound` says how mail for other domains leaves: + +- `direct` (the default): the BBS looks up each domain's MX and delivers + on port 25, with STARTTLS when the other side offers it. Many home and + cloud networks block port 25 out, and receivers want SPF, DKIM and a + reverse DNS name for the host, so this needs some DNS work (below). +- `smarthost`: everything goes through another mail server (your + provider's, a relay such as Postfix, or a service like Mailgun), given in + `[smarthost]`. That server does the delivering. This is the easy route + when one is at hand. +- `none`: only mail between users here, and FidoNet. + +``` +[mail] +domain = example.org +outbound = smarthost + +[smarthost] +address = smtp.example.net:587 +tls = starttls ; or implicit (465), or no +username = bbs@example.org +password = secret +``` + +Mail out waits in a queue, tried again with longer gaps (five minutes, then +up to four hours) for `queue_days` (5). When a server refuses a recipient for +good, or the days run out, the sender gets a note in their inbox saying +why. `bbs mail queue` lists what is waiting, and `bbs mail send` tries it +all now. + +## DNS for a domain of its own + +For mail to arrive, and to be believed when sent directly: + +``` +example.org. MX 10 mail.example.org. +mail.example.org. A 203.0.113.5 +example.org. TXT "v=spf1 mx -all" +bbs._domainkey.example.org. TXT "v=DKIM1; k=rsa; p=..." +_dmarc.example.org. TXT "v=DMARC1; p=quarantine" +``` + +and a reverse DNS (PTR) name for 203.0.113.5 of `mail.example.org`, which +the hosting provider sets. `bbs mail dkim /etc/bbs/dkim.pem` makes the DKIM +key and prints its record. With a smarthost, use the SPF and DKIM its +provider gives instead. + +## Mail from the internet + +`[mx]` takes mail for the domain on port 25, without a login, and only for +users here: it is never an open relay. With `checks = yes` (the default) it +checks SPF, DKIM and DMARC, and adds an `Authentication-Results` header. A +mail is refused when it fails a DMARC policy of `p=reject`, or, for a domain +with no DMARC record, when SPF fails and no signature of that domain holds. + +If another mail server already takes the domain's mail (Postfix, with its +own spam filtering), it can hand mail to the BBS by LMTP instead: + +``` +[lmtp] +address = /run/bbs/lmtp.sock +``` + +``` +# Postfix main.cf +virtual_mailbox_domains = example.org +virtual_transport = lmtp:unix:/run/bbs/lmtp.sock +``` + +## On the terminal + +Mail from the internet is shown as text: HTML mail is turned into plain +text, and attachments are listed by name and size (they stay whole for +mail programs). Messages larger than `max_message` (10M) are refused. + +## Databases + +Mail lives in the BBS's database, whichever it is: SQLite, PostgreSQL, +MySQL or MariaDB. `bbs db copy` carries the mail, the folders and the +queue along with the rest. diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 8357ebb..94fd454 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -40,6 +40,7 @@ Main menu | Make it look like your own | [Customization](Customization), [Scripting](Scripting) | | Take calls by modem | [Modem callers](Modem-Callers) | | Join FidoNet, QWK networks or Usenet | [FidoNet](FidoNet), [Offline mail](Offline-Mail#qwk-networks), [Newsgroups and NNTP](Newsgroups-and-NNTP) | +| Give users e-mail addresses | [E-mail](E-mail) | | Put the board on the web | [Web forum](Web-Forum), [Image boards](Image-Boards), [HTTP API](HTTP-API) | | Work on the code | [Development](Development) | @@ -76,6 +77,8 @@ which is generated from `bbs.conf.sample`. - [FidoNet](FidoNet) and other FTN networks: echomail, netmail, file echoes, AreaFix and a built-in binkp mailer +- [E-mail](E-mail): each user an address, their BBS mail read over IMAP + and POP3 and sent over SMTP, to and from the internet - [Newsgroups](Newsgroups-and-NNTP) served by NNTP and exchanged with other news servers - [IRC](IRC), where the chat rooms are channels, [AIM and ICQ](AIM-and-ICQ) @@ -130,6 +133,7 @@ which is generated from `bbs.conf.sample`. | [Files and FTP](Files-and-FTP) | file areas, the FTP (FTPS) server | | [File transfers](File-Transfers) | X/Y/ZMODEM, Kermit, IND$FILE | | [Doors](Doors) | DOS doors in dosemu2 (Docker), Linux doors, doors on other systems | +| [E-mail](E-mail) | addresses, IMAP, POP3, SMTP, the MX, a smarthost, DNS | | [Newsgroups and NNTP](Newsgroups-and-NNTP) | the NNTP server, news peers | | [FidoNet](FidoNet) | echomail, netmail, binkp, file echoes, AreaFix, nodelists | | [Chat and paging](Chat-and-Paging) | chat rooms, node messages, paging the sysop | diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 4dcd373..9127141 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -29,6 +29,7 @@ - [Files and FTP](Files-and-FTP) - [File transfers](File-Transfers) - [Doors](Doors) +- [E-mail](E-mail) - [Newsgroups and NNTP](Newsgroups-and-NNTP) - [FidoNet](FidoNet) - [Chat and paging](Chat-and-Paging) diff --git a/internal/email/email_test.go b/internal/email/email_test.go new file mode 100644 index 0000000..221779c --- /dev/null +++ b/internal/email/email_test.go @@ -0,0 +1,567 @@ +package email + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "errors" + "fmt" + "log" + "net" + "net/smtp" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/emersion/go-imap/v2" + "github.com/emersion/go-imap/v2/imapclient" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +func init() { store.BcryptCost = 4 } + +// fakeDNS is DNS for the tests. +type fakeDNS struct { + mu sync.Mutex + txt map[string][]string + mx map[string][]*net.MX +} + +func (d *fakeDNS) LookupTXT(ctx context.Context, name string) ([]string, error) { + d.mu.Lock() + defer d.mu.Unlock() + if v, ok := d.txt[strings.TrimSuffix(name, ".")]; ok { + return v, nil + } + return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} +} + +func (d *fakeDNS) LookupMX(ctx context.Context, name string) ([]*net.MX, error) { + d.mu.Lock() + defer d.mu.Unlock() + if v, ok := d.mx[strings.TrimSuffix(name, ".")]; ok { + return v, nil + } + return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} +} + +func (d *fakeDNS) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil +} + +func (d *fakeDNS) LookupAddr(ctx context.Context, addr string) ([]string, error) { + return nil, &net.DNSError{Err: "no such host", Name: addr, IsNotFound: true} +} + +// site is a BBS with e-mail, its servers on local ports. +type site struct { + b *bbs.BBS + svc *Service + st *store.Store + log *bytes.Buffer + addrs map[string]string + users map[string]*store.User +} + +// newSite makes a BBS for domain with users, and the servers of kinds +// asked for (pop3, imap, smtp, mx), without TLS. +func newSite(t *testing.T, domain string, dns *fakeDNS, users []string, kinds ...string) *site { + t.Helper() + st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + s := &site{st: st, log: &bytes.Buffer{}, addrs: map[string]string{}, users: map[string]*store.User{}} + for _, name := range users { + u, err := st.CreateUser(name, "password1", "", name == "sysop") + if err != nil { + t.Fatal(err) + } + s.users[name] = u + } + set := bbs.Defaults() + set.FailDelay = 0 + s.b = bbs.New(set, st, log.New(&syncWriter{w: s.log}, domain+": ", 0)) + ms := Defaults(domain, "mail."+domain) + ms.Resolver = dns + s.svc = New(s.b, ms) + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + for _, k := range kinds { + set := ServerSettings{Address: "127.0.0.1:0", TLS: TLSNo, MaxClients: 10, MaxPerIP: 10, IdleTimeout: time.Minute} + var run func(context.Context) error + var addr net.Addr + switch k { + case "pop3": + x, err := s.svc.NewPOP3(set) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + case "imap": + x, err := s.svc.NewIMAP(set) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + default: + x, err := s.svc.NewSMTP(k, set, k == MX) + if err != nil { + t.Fatal(err) + } + run, addr = x.Run, x.Addr() + } + s.addrs[k] = addr.String() + wg.Add(1) + go func() { defer wg.Done(); run(ctx) }() + } + t.Cleanup(func() { + cancel() + wg.Wait() + if t.Failed() { + t.Logf("%s log:\n%s", domain, s.log.String()) + } + }) + return s +} + +type syncWriter struct { + mu sync.Mutex + w *bytes.Buffer +} + +func (w *syncWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.w.Write(p) +} + +// submit sends a mail by SMTP submission, as name. +func submit(t *testing.T, addr, name, from string, to []string, msg string) error { + t.Helper() + host, _, _ := net.SplitHostPort(addr) + return smtp.SendMail(addr, smtp.PlainAuth("", name, "password1", host), from, to, []byte(msg)) +} + +// inbox is a user's inbox. +func inbox(t *testing.T, s *site, name string, folder int) []*store.Message { + t.Helper() + id := s.users[name].ID + l, err := s.st.Folder(id, folder) + if err != nil { + t.Fatal(err) + } + for i, m := range l { + full, _, err := s.st.BoxMail(id, m.Box) + if err != nil { + t.Fatal(err) + } + l[i].Raw = full.Raw + } + return l +} + +// TestAddresses: users' addresses, those here and FidoNet's read. +func TestAddresses(t *testing.T) { + dns := &fakeDNS{} + s := newSite(t, "bbs.test", dns, []string{"Alice Smith", "sysop", "Bob"}) + if a := s.svc.Address(s.users["Alice Smith"]); a != "alice.smith@bbs.test" { + t.Errorf("address %q", a) + } + for addr, want := range map[string]string{"alice.smith@bbs.test": "Alice Smith", "ALICE.SMITH+lists@BBS.TEST": "Alice Smith", + "postmaster@bbs.test": "sysop", "abuse@mail.bbs.test": "sysop", "bob@bbs.test": "Bob"} { + r, err := s.svc.resolve(addr) + if err != nil || r.kind != toLocal || r.user.Name != want { + t.Errorf("%s: %+v %v", addr, r, err) + } + } + if _, err := s.svc.resolve("carol@bbs.test"); !errors.Is(err, ErrNoUser) { + t.Errorf("no such user: %v", err) + } + r, err := s.svc.resolve("john.doe@p4.f100.n1.z21.fidonet.org") + if err != nil || r.kind != toFido || r.name != "John Doe" || r.ftn.String() != "21:1/100.4" { + t.Errorf("fidonet: %+v %v", r, err) + } + if r, _ := s.svc.resolve("x@example.com"); r.kind != toInternet { + t.Errorf("internet: %+v", r) + } + if !bbs.IsEmailAddress("x@example.com") || !bbs.IsEmailAddress(`"Jo, Smith" `) || + bbs.IsEmailAddress("Bob@1:2/3") || bbs.IsEmailAddress("Bob") || bbs.IsEmailAddress("x@localhost") { + t.Error("IsEmailAddress") + } + if got := shownAddress("Jo, Smith", "jo@example.com"); !bbs.IsEmailAddress(got) { + t.Errorf("shown %q is not an address again", got) + } +} + +// TestParse: a mail's text for the terminals, from plain text, HTML, and +// with attachments listed. +func TestParse(t *testing.T) { + raw := "From: \"Jo\" \r\nTo: bob@bbs.test\r\nSubject: =?utf-8?q?Caf=C3=A9?=\r\n" + + "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=b\r\n\r\n" + + "--b\r\nContent-Type: text/html; charset=utf-8\r\n\r\n

Hello there

bye & all

\r\n" + + "--b\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename=a.pdf\r\n" + + "Content-Transfer-Encoding: base64\r\n\r\nJVBERi0=\r\n--b--\r\n" + p, err := parse([]byte(raw)) + if err != nil { + t.Fatal(err) + } + if p.subject != "Café" || p.fromAddr != "jo@example.com" || p.fromName != "Jo" { + t.Errorf("header: %+v", p) + } + if !strings.Contains(p.text, "Hello there\nbye & all") || !strings.Contains(p.text, "a.pdf (5 bytes)") { + t.Errorf("text: %q", p.text) + } +} + +// TestRender: mail written here, as a mail program gets it. +func TestRender(t *testing.T) { + s := newSite(t, "bbs.test", &fakeDNS{}, []string{"alice", "sysop"}) + m := &store.Message{ID: 7, FromID: s.users["alice"].ID, From: "alice", ToID: s.users["sysop"].ID, To: "sysop", + Subject: "Grüße", Body: "line one\n.dot line", Created: time.Unix(1e9, 0), ReplyTo: 3} + raw := string(s.svc.Render(m)) + for _, want := range []string{"From: \"alice\" \r\n", "To: \"sysop\" \r\n", + "Subject: =?utf-8?q?Gr=C3=BC=C3=9Fe?=\r\n", "Message-ID: \r\n", + "In-Reply-To: \r\n", "\r\n\r\nline one\r\n.dot line\r\n"} { + if !strings.Contains(raw, want) { + t.Errorf("no %q in\n%s", want, raw) + } + } + if string(s.svc.Render(m)) != raw { + t.Error("not the same twice") + } + fido := &store.Message{From: "Hub Sysop@21:1/100", Subject: "s", Body: "b"} + if a := s.svc.fromAddress(fido); a.Address != "hub.sysop@f100.n1.z21.fidonet" { + t.Errorf("fido from %v", a) + } +} + +// TestMail: mail sent by SMTP submission to a user here and to another +// BBS, which takes it from the queue by SMTP with its SPF, DKIM and DMARC +// holding; mail refused for elsewhere, forged, or for no one; a bounce; +// then the other BBS's user reads it by POP3 and IMAP. +func TestMail(t *testing.T) { + dns := &fakeDNS{txt: map[string][]string{}, mx: map[string][]*net.MX{}} + a := newSite(t, "a.test", dns, []string{"alice", "sysop"}, Submission) + b := newSite(t, "b.test", dns, []string{"bob", "sysop"}, MX, "pop3", "imap") + + // a.test signs; its records say so, and that it sends from here + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + a.svc.Set.DKIM = &DKIM{Domain: "a.test", Selector: "bbs", Signer: key} + rec, _ := DKIMRecord(key) + dns.txt["bbs._domainkey.a.test"] = []string{rec} + dns.txt["a.test"] = []string{"v=spf1 ip4:127.0.0.1 -all"} + dns.txt["_dmarc.a.test"] = []string{"v=DMARC1; p=reject"} + _, port, _ := net.SplitHostPort(b.addrs[MX]) + dns.mx["b.test"] = []*net.MX{{Host: "127.0.0.1", Pref: 10}} + a.svc.Set.MXPort = port + + sub := a.addrs[Submission] + msg := "From: alice \r\nTo: bob@b.test, sysop@a.test\r\nBcc: secret@b.test\r\nSubject: Hello\r\n\r\nHi Bob.\r\n" + if err := submit(t, sub, "alice", "alice@a.test", []string{"bob@b.test", "sysop@a.test"}, msg); err != nil { + t.Fatal(err) + } + if in := inbox(t, a, "sysop", store.FolderInbox); len(in) != 1 || in[0].Subject != "Hello" || in[0].FromID != a.users["alice"].ID { + t.Fatalf("sysop's inbox: %+v", in) + } + sent := inbox(t, a, "alice", store.FolderSent) + if len(sent) != 1 || strings.Contains(string(sent[0].Raw), "secret") || !strings.Contains(string(sent[0].Raw), "DKIM-Signature:") { + t.Fatalf("alice's sent: %+v", sent) + } + + // refused: another's address, a user not there, mail before a login + if err := submit(t, sub, "alice", "sysop@a.test", []string{"bob@b.test"}, msg); err == nil { + t.Error("sent as another") + } + if err := submit(t, sub, "alice", "alice@a.test", []string{"nobody@a.test"}, msg); err == nil { + t.Error("sent to no one") + } + if c, err := smtp.Dial(sub); err == nil { + if err := c.Mail("alice@a.test"); err == nil || !strings.Contains(err.Error(), "530") { + t.Errorf("mail without a login: %v", err) + } + c.Close() + } + + // the queue: to b.test, where it is checked + if q, _ := a.st.MailQueue(time.Time{}, 0); len(q) != 1 || q[0].Rcpt != "bob@b.test" { + t.Fatalf("queue: %+v", q) + } + a.svc.RunQueueOnce(context.Background()) + if q, _ := a.st.MailQueue(time.Time{}, 0); len(q) != 0 { + t.Fatalf("queue after: %+v", q) + } + got := inbox(t, b, "bob", store.FolderInbox) + if len(got) != 1 { + t.Fatalf("bob's inbox: %+v", got) + } + raw := string(got[0].Raw) + for _, want := range []string{"spf=pass", "dkim=pass", "dmarc=pass", "Received: from mail.a.test", "Hi Bob."} { + if !strings.Contains(raw, want) { + t.Errorf("no %q in\n%s", want, raw) + } + } + if got[0].From != "alice " || got[0].FromID != 0 || !bbs.IsEmailAddress(got[0].From) { + t.Errorf("from %q", got[0].From) + } + + // b.test's MX: no relaying, no one there, and a forgery refused + mx := b.addrs[MX] + err = smtp.SendMail(mx, nil, "x@c.test", []string{"y@elsewhere.test"}, []byte("Subject: x\r\n\r\nx\r\n")) + if err == nil || !strings.Contains(err.Error(), "550") { + t.Errorf("relayed: %v", err) + } + forged := "From: alice@a.test\r\nTo: bob@b.test\r\nSubject: Forged\r\n\r\nGive me money\r\n" + err = smtp.SendMail(mx, nil, "x@c.test", []string{"bob@b.test"}, []byte(forged)) + if err == nil || !strings.Contains(err.Error(), "DMARC") { + t.Errorf("forged: %v", err) + } + if n := len(inbox(t, b, "bob", store.FolderInbox)); n != 1 { + t.Errorf("bob has %d", n) + } + + // a bounce, for no one at b.test + if err := submit(t, sub, "alice", "alice@a.test", []string{"nobody@b.test"}, "Subject: Lost\r\n\r\nx\r\n"); err != nil { + t.Fatal(err) + } + a.svc.RunQueueOnce(context.Background()) + if in := inbox(t, a, "alice", store.FolderInbox); len(in) != 1 || in[0].Subject != "Undelivered: Lost" || + !strings.Contains(in[0].Body, "nobody@b.test") { + t.Errorf("bounce: %+v", in) + } + + // from a terminal + n, _ := a.b.Enter(&bbs.Caller{Via: "test"}, nil) + n.SetUser(a.users["alice"]) + if err := n.SendMail("bob@b.test", "From the BBS", []string{"typed on a terminal"}, 0); err != nil { + t.Fatal(err) + } + a.svc.RunQueueOnce(context.Background()) + if in := inbox(t, b, "bob", store.FolderInbox); len(in) != 2 || in[1].Subject != "From the BBS" { + t.Fatalf("bob's inbox: %+v", in) + } + + testPOP3(t, b) + testIMAP(t, b) +} + +// pop is a POP3 command's reply. +func pop(t *testing.T, r *bufio.Reader, c net.Conn, cmd string, multi bool) string { + t.Helper() + if cmd != "" { + fmt.Fprintf(c, "%s\r\n", cmd) + } + line, err := r.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if !multi || !strings.HasPrefix(line, "+OK") { + return line + } + var b strings.Builder + b.WriteString(line) + for { + l, err := r.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if l == ".\r\n" { + return b.String() + } + b.WriteString(l) + } +} + +// testPOP3: bob's inbox by POP3: listed, read, one deleted (to the trash). +func testPOP3(t *testing.T, b *site) { + c, err := net.Dial("tcp", b.addrs["pop3"]) + if err != nil { + t.Fatal(err) + } + defer c.Close() + r := bufio.NewReader(c) + pop(t, r, c, "", false) + if got := pop(t, r, c, "PASS x", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("PASS first: %q", got) + } + pop(t, r, c, "USER bob", false) + if got := pop(t, r, c, "PASS wrong", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("a wrong password: %q", got) + } + pop(t, r, c, "USER bob@b.test", false) + if got := pop(t, r, c, "PASS password1", false); !strings.HasPrefix(got, "+OK") { + t.Fatalf("login: %q", got) + } + if got := pop(t, r, c, "STAT", false); !strings.HasPrefix(got, "+OK 2 ") { + t.Errorf("STAT %q", got) + } + if got := pop(t, r, c, "UIDL", true); strings.Count(got, "\r\n") != 3 { + t.Errorf("UIDL %q", got) + } + if got := pop(t, r, c, "RETR 1", true); !strings.Contains(got, "Subject: Hello") || !strings.Contains(got, "Hi Bob.") { + t.Errorf("RETR %q", got) + } + if got := pop(t, r, c, "TOP 2 0", true); !strings.Contains(got, "Subject: From the BBS") || strings.Contains(got, "typed") { + t.Errorf("TOP %q", got) + } + pop(t, r, c, "DELE 2", false) + if got := pop(t, r, c, "RETR 2", false); !strings.HasPrefix(got, "-ERR") { + t.Errorf("deleted RETR %q", got) + } + pop(t, r, c, "QUIT", false) + in := inbox(t, b, "bob", store.FolderInbox) + if len(in) != 1 || !in[0].Read { + t.Errorf("after POP3: %+v", in) + } + if tr := inbox(t, b, "bob", store.FolderTrash); len(tr) != 1 || tr[0].Subject != "From the BBS" { + t.Errorf("trash: %+v", tr) + } +} + +// testIMAP: bob's folders by IMAP: listed with their special uses, mail +// restored from the trash, starred, read, put in Sent once, and new mail +// told of. +func testIMAP(t *testing.T, b *site) { + var mu sync.Mutex + var exists []uint32 + c, err := imapclient.DialInsecure(b.addrs["imap"], &imapclient.Options{UnilateralDataHandler: &imapclient.UnilateralDataHandler{ + Mailbox: func(d *imapclient.UnilateralDataMailbox) { + if d.NumMessages != nil { + mu.Lock() + exists = append(exists, *d.NumMessages) + mu.Unlock() + } + }}}) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.Login("bob", "wrong").Wait(); err == nil { + t.Error("a wrong password") + } + if err := c.Login("bob", "password1").Wait(); err != nil { + t.Fatal(err) + } + list, err := c.List("", "*", &imap.ListOptions{ReturnSpecialUse: true}).Collect() + if err != nil { + t.Fatal(err) + } + var names []string + for _, l := range list { + n := l.Mailbox + for _, a := range l.Attrs { + if a != imap.MailboxAttrHasNoChildren { + n += string(a) + } + } + names = append(names, n) + } + if strings.Join(names, " ") != `INBOX Sent\Sent Drafts\Drafts Starred\Flagged Unread All Mail\All Trash\Trash` { + t.Errorf("list: %v", names) + } + if err := c.Create("Work", nil).Wait(); err == nil { + t.Error("a folder made") + } + + // out of the trash, into the inbox + if d, err := c.Select("Trash", nil).Wait(); err != nil || d.NumMessages != 1 { + t.Fatalf("trash: %+v %v", d, err) + } + cd, err := c.Copy(imap.SeqSetNum(1), "INBOX").Wait() + if err != nil || len(cd.DestUIDs) != 1 { + t.Fatalf("copy: %+v %v", cd, err) + } + if err := c.Noop().Wait(); err != nil { + t.Fatal(err) + } + if mb := c.Mailbox(); mb == nil || mb.NumMessages != 0 { + t.Errorf("trash after: %+v", mb) + } + d, err := c.Select("INBOX", nil).Wait() + if err != nil || d.NumMessages != 2 { + t.Fatalf("inbox: %+v %v", d, err) + } + + // starred; read by fetching + if _, err := c.Store(imap.SeqSetNum(1), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Flags: []imap.Flag{imap.FlagFlagged}}, nil).Collect(); err != nil { + t.Fatal(err) + } + if st, _ := c.Status("Starred", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("starred: %+v", st) + } + msgs, err := c.Fetch(imap.SeqSetNum(2), &imap.FetchOptions{Envelope: true, Flags: true, RFC822Size: true, + BodySection: []*imap.FetchItemBodySection{{}}}).Collect() + if err != nil || len(msgs) != 1 { + t.Fatalf("fetch: %v %v", msgs, err) + } + body := string(msgs[0].FindBodySection(&imap.FetchItemBodySection{})) + if msgs[0].Envelope.Subject != "From the BBS" || !strings.Contains(body, "typed on a terminal") || int64(len(body)) != msgs[0].RFC822Size { + t.Errorf("fetched: %+v %q", msgs[0].Envelope, body) + } + if st, _ := c.Status("Unread", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 0 { + t.Errorf("unread: %+v", st) + } + res, err := c.Search(&imap.SearchCriteria{Body: []string{"terminal"}}, nil).Wait() + if err != nil || len(res.AllSeqNums()) != 1 || res.AllSeqNums()[0] != 2 { + t.Errorf("search: %+v %v", res, err) + } + + // put in Sent: once, by its Message-ID + mail := "From: bob@b.test\r\nTo: x@example.com\r\nSubject: Mine\r\nMessage-ID: \r\n\r\nkept\r\n" + for i := 0; i < 2; i++ { + ap := c.Append("Sent", int64(len(mail)), &imap.AppendOptions{Flags: []imap.Flag{imap.FlagSeen}}) + ap.Write([]byte(mail)) + ap.Close() + if _, err := ap.Wait(); err != nil { + t.Fatal(err) + } + } + if st, _ := c.Status("Sent", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("sent: %+v", st) + } + + // deleted: to the trash + if _, err := c.Store(imap.SeqSetNum(2), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{imap.FlagDeleted}}, nil).Collect(); err != nil { + t.Fatal(err) + } + if _, err := c.Expunge().Collect(); err != nil { + t.Fatal(err) + } + if st, _ := c.Status("Trash", &imap.StatusOptions{NumMessages: true}).Wait(); st == nil || *st.NumMessages != 1 { + t.Errorf("trash: %+v", st) + } + + // new mail, told by IDLE + idle, err := c.Idle() + if err != nil { + t.Fatal(err) + } + b.svc.Receive([]*store.User{b.users["bob"]}, []byte("From: z@example.com\r\nSubject: New\r\n\r\nnew\r\n"), "") + deadline := time.Now().Add(5 * time.Second) + for { + mu.Lock() + n := len(exists) + mu.Unlock() + if n > 0 || time.Now().After(deadline) { + break + } + time.Sleep(20 * time.Millisecond) + } + idle.Close() + idle.Wait() + mu.Lock() + defer mu.Unlock() + if len(exists) == 0 || exists[len(exists)-1] != 2 { + t.Errorf("IDLE: %v", exists) + } +} diff --git a/internal/email/listen.go b/internal/email/listen.go index 5241747..90dca7a 100644 --- a/internal/email/listen.go +++ b/internal/email/listen.go @@ -164,6 +164,11 @@ func (c *counted) Close() error { return c.Conn.Close() } -// remoteOf is the address a connection (perhaps TLS, perhaps counted) -// comes from. -func remoteOf(c net.Conn) net.Addr { return c.RemoteAddr() } +// Addr is where a server listens. +func (x *POP3Server) Addr() net.Addr { return x.ln.Addr() } + +// Addr is where a server listens. +func (x *IMAPServer) Addr() net.Addr { return x.ln.Addr() } + +// Addr is where a server listens. +func (x *SMTPServer) Addr() net.Addr { return x.ln.Addr() } diff --git a/internal/email/python_test.go b/internal/email/python_test.go new file mode 100644 index 0000000..bcd585a --- /dev/null +++ b/internal/email/python_test.go @@ -0,0 +1,95 @@ +package email + +import ( + "fmt" + "net" + "os/exec" + "strings" + "testing" + + "github.com/D-Modem/bbs/internal/store" +) + +// Python's smtplib, poplib and imaplib, mail programs of someone else's +// making, send, fetch, file and search mail. +func TestPythonClients(t *testing.T) { + if exec.Command("python3", "-c", "import smtplib, poplib, imaplib").Run() != nil { + t.Skip("no python3") + } + s := newSite(t, "a.test", &fakeDNS{}, []string{"sysop", "alice", "bob"}, Submission, "pop3", "imap") + hp := func(kind string) (string, string) { + h, p, _ := net.SplitHostPort(s.addrs[kind]) + return h, p + } + sh, sp := hp(Submission) + ph, pp := hp("pop3") + ih, ip := hp("imap") + script := fmt.Sprintf(` +import smtplib, poplib, imaplib, email +from email.message import EmailMessage + +m = EmailMessage() +m['From'] = 'alice ' +m['To'] = 'bob@a.test' +m['Subject'] = 'From Python' +m.set_content('Hello Bob, from smtplib.') +with smtplib.SMTP(%[1]q, %[2]s) as c: + c.login('alice', 'password1') + c.send_message(m) + +p = poplib.POP3(%[3]q, %[4]s) +p.user('bob') +p.pass_('password1') +count, size = p.stat() +assert count == 1, count +resp, lines, octets = p.retr(1) +msg = email.message_from_bytes(b'\r\n'.join(lines)) +assert msg['Subject'] == 'From Python', msg['Subject'] +assert 'from smtplib' in msg.get_payload(), msg.get_payload() +resp, uids, _ = p.uidl() +assert len(uids) == 1, uids +p.quit() + +i = imaplib.IMAP4(%[5]q, %[6]s) +i.login('bob', 'password1') +typ, folders = i.list() +names = b'\n'.join(folders).decode() +for want in ('INBOX', 'Sent', 'Drafts', 'Starred', 'Unread', 'All Mail', 'Trash', '\\Flagged', '\\Trash'): + assert want in names, (want, names) +typ, data = i.select('INBOX') +assert data[0] == b'1', data +typ, data = i.uid('SEARCH', None, 'SUBJECT', '"From Python"') +uid = data[0].split()[0] +typ, data = i.uid('FETCH', uid, '(FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])') +assert b'From Python' in data[0][1], data +assert b'\\Seen' in data[0][0], data +typ, _ = i.uid('STORE', uid, '+FLAGS', '(\\Flagged)') +assert typ == 'OK', typ +typ, data = i.select('Starred') +assert data[0] == b'1', data +i.select('INBOX') +typ, _ = i.uid('MOVE', uid, 'Trash') +assert typ == 'OK', typ +typ, data = i.select('INBOX') +assert data[0] == b'0', data +typ, data = i.select('Trash') +assert data[0] == b'1', data +typ, data = i.append('Drafts', '', imaplib.Time2Internaldate(0), b'Subject: Draft\r\n\r\nNot yet.\r\n') +assert typ == 'OK', (typ, data) +i.logout() +print('ok') +`, sh, sp, ph, pp, ih, ip) + out, err := exec.Command("python3", "-W", "ignore", "-c", script).CombinedOutput() + if err != nil || !strings.Contains(string(out), "ok") { + t.Fatalf("python: %v\n%s", err, out) + } + if l := inbox(t, s, "bob", store.FolderTrash); len(l) != 1 || !l[0].Starred { + t.Errorf("bob's trash: %+v", l) + } + if l := inbox(t, s, "bob", store.FolderDrafts); len(l) != 1 || l[0].Subject != "Draft" { + t.Errorf("bob's drafts: %+v", l) + } + if l := inbox(t, s, "alice", store.FolderSent); len(l) != 1 || l[0].Subject != "From Python" { + t.Errorf("alice's sent: %+v", l) + } +} diff --git a/internal/email/smtp.go b/internal/email/smtp.go index 6b17e81..073224d 100644 --- a/internal/email/smtp.go +++ b/internal/email/smtp.go @@ -95,9 +95,10 @@ func smtpErr(code int, enh smtp.EnhancedCode, msg string) *smtp.SMTPError { } var ( - errTLSFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Use STARTTLS first") - errNoRelay = smtpErr(550, smtp.EnhancedCode{5, 7, 1}, "Mail for elsewhere is not taken here") - errNoUser = smtpErr(550, smtp.EnhancedCode{5, 1, 1}, "No such user here") + errTLSFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Use STARTTLS first") + errAuthFirst = smtpErr(530, smtp.EnhancedCode{5, 7, 0}, "Authentication required") + errNoRelay = smtpErr(550, smtp.EnhancedCode{5, 7, 1}, "Mail for elsewhere is not taken here") + errNoUser = smtpErr(550, smtp.EnhancedCode{5, 1, 1}, "No such user here") ) // tls reports whether the session is in TLS. @@ -147,7 +148,7 @@ func (ss *smtpSession) Mail(from string, opts *smtp.MailOptions) error { if !ss.tls() && ss.x.set.TLS == TLSRequired { return errTLSFirst } - return smtp.ErrAuthRequired + return errAuthFirst } if from != "" && !strings.EqualFold(from, ss.x.svc.Address(ss.user)) { return smtpErr(553, smtp.EnhancedCode{5, 7, 1}, "Send from your own address, "+ss.x.svc.Address(ss.user))