My laptop is usually connected behind a restrictive firewall. Since port 25 is blocked, I can't send mail the normal way. Instead I just build a tunnel to my mail server using ssh -Nf -L25025:localhost:25 mailhost and configure Mail's SMTP server to point to localhost port 25025. Usually this works fine, but sometimes I get unexplained connection failures.
Finally, I have unearthed the cause of the problem.
Mail's 'Connection Doctor' is worse than useless. It claimed that there is no server listening on port 25025 on localhost. I spent an hour trying to diagnose this phantom connection problem. Eventually I used tcpdump to check the connection, and found that the truth was very different. In fact it's talking to Exim, but Exim is rejecting its advances with the error:
rejected HELO from localhost [127.0.0.1]: syntactically invalid argument(s): [1N?IPv6:::1]
So, Mail is connecting to the server, and claiming to be "[1N?IPv6:::1]". Since that's not a valid address (not even a valid IPv6 address), Exim is rejecting it. I have no idea why Mail sometimes uses this nonsense IP address, but at other times seems to work fine. I don't think it's possible to configure mail to use a proper hostname, so I've had to try and fix the problem at the server end.
Exim has an option "helo_accept_junk_hosts" which turns off this error checking. I've tried setting it to selectively ignore the nonsense produced by OSX Mail, but I can't get it to accept the string "[1N?IPv6:::1]" as a hostname. In the end, I've settled on turning off the checking altogether, by adding the following line to my Exim configuration:
helo_accept_junk_hosts = *
This isn't a perfect solution, but since this mail server doesn't receive loads of mail from the Internet, it seems like it should be reasonably safe.