Is there any way to find that name and port programmatically?
You can find the mail host's name (or names) in DNS. Query for the MX
record. Once you get a mail host, you use port 25
per RFC 5321, Simple Mail Transfer Protocol. You won't need a username and password since it's the other's mail server.
If you are trying to connect to your organization's mail server so that your mail server sends the mail to the other system, then try port 465 or port 587. Use 465 first because that's SMTPS
, and then try port 587 for MSA
. You want SMTPS
because you don't want to put your authentication credentials on the wire in the plain text.
Here's how you query for a MX
record with dig(1)
:
$ dig gmail.com MX
; <<>> DiG 9.8.5-P1 <<>> gmail.com MX
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42931
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;gmail.com. IN MX
;; ANSWER SECTION:
gmail.com. 3599 IN MX 20 alt2.gmail-smtp-in.l.google.com.
gmail.com. 3599 IN MX 30 alt3.gmail-smtp-in.l.google.com.
gmail.com. 3599 IN MX 10 alt1.gmail-smtp-in.l.google.com.
gmail.com. 3599 IN MX 5 gmail-smtp-in.l.google.com.
gmail.com. 3599 IN MX 40 alt4.gmail-smtp-in.l.google.com.
;; Query time: 23 msec
;; SERVER: 172.16.1.10#53(172.16.1.10)
;; WHEN: Fri Feb 07 22:19:33 EST 2014
;; MSG SIZE rcvd: 150
You should include support for the STARTTLS
command per RFC 3207, SMTP Service Extension for Secure SMTP over Transport Layer Security. The server will advertise it, but the client has to engage it. That is, its the client's choice.
The STARTTLS
command will keep the eavesdroppers out, like the telecoms, the NSA and GHCQ. The adversaries will have to undertake active attacks, which are more easily spotted in the wild. For example, I believe the EFF runs some X509 certificate monitoring tools that could catch some of the funny business associated with active MitM attacks.