The preferred method for SMTP message forwarding is using your ISP's SMTP server. The job of locating Google's Message transfer agent is handled by such servers.
To use Google's servers directly, you need to look up the MX records provided by google via DNS. From a Python
program, a DNS library is needed. Here is an example, using dnspython
, a A DNS toolkit for Python.
>>> from dns import resolver
>>> mxrecs = resolver.query('gmail.com', 'MX')
>>> [mx for mx in mxrecs]
[<DNS IN MX rdata: 20 alt2.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 40 alt4.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 30 alt3.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 10 alt1.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 5 gmail-smtp-in.l.google.com.>]
>>> mx.exchange.to_text()
'gmail-smtp-in.l.google.com.'
>>> mx.preference
5
>>>
The preferred mail-exchange server here is gmail-smtp-in.l.google.com
, which can be used with smtplib
to forward messages.