Reputation: 965
I'd like to send Direct-To-MX mail. To retrieve the correct MX server(s) I use the following functions.
import dns.resolver
def MX():
domain = self.to.split('@')[1] # self.to is an email address
mx = resolve_MX(domain)
s = smtplib.SMTP(mx, 25)
return s
def resolve_MX(domain):
MXlist = []
for mx in dns.resolver.query(domain, 'MX'):
MXlist.append(mx)
rand = randint(0,len(MXlist)-1)
mx_record = MXlist[rand]
return str(mx_record)[3:]
The resolver returns a string like 20 ALT1.ASPMX.L.GOOGLE.COM
or 1 ASPMX.L.GOOGLE.COM
. The digit in front of the MX server indicates the priority. This can be a double digit or single digit and here lies my problem. Because the dns.resolver does not return a tuple eg. (priority, server)
, how can I strip the either single or double digit priority of the string. Right now I assume the priority will be a double digit number.
Upvotes: 0
Views: 73
Reputation: 32189
Since your string is separated into two parts by a space, you can do:
final_str = received_string.split(' ')
>>> print final_str
['20', 'ALT1.ASPMX.L.GOOGLE.COM']
Furthermore, if you are going to be performing priority comparisons in terms of numbers, it is better if your priority number is an int
rather than a string
. For that, you can do:
final_str = received_string.split(' ')
final_str[0] = int(final_str[0])
>>> print final_str
[20, 'ALT1.ASPMX.L.GOOGLE.COM']
Upvotes: 1