Skip to content

Instantly share code, notes, and snippets.

@Kein1945
Created February 26, 2013 11:03
Show Gist options
  • Save Kein1945/5037697 to your computer and use it in GitHub Desktop.
Save Kein1945/5037697 to your computer and use it in GitHub Desktop.
Python mail checker. Проверяет наличие почтового ящика на сервере. Следует учесть что не все сервера отвечают корректно, к примеру mail.ru всегда отвечает успешно, хотя ящика может не быть на сервере
#!/usr/bin/python2.7
import socket
import sys
import DNS
import cgi
arg = cgi.FieldStorage()
if "debug" in arg:
debug = True
else:
debug = False
def check(host, resp, sender = 'test@localhost'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 25))
getreply(sock)
ehlo_or_helo_if_needed(sock)
return test_msg(sock, sender, resp)
def test_msg(sock, sender, resp):
putcmd(sock, 'mail FROM:<%s>'%sender)
getreply(sock)
putcmd(sock, 'rcpt TO:<%s>' % resp)
result = getreply(sock)
putcmd(sock, 'quit')
getreply(sock)
sock.close()
return result[0] == 250
def getreply(sock):
f = sock.makefile('rb')
resp = []
while 1:
try:
line = f.readline()
except socket.error:
line = ''
if line == '':
self.close()
raise Exception('Connection unexpectedly closed')
if debug:
print 'Recv \'%s\''%(line.strip())
resp.append(line[4:].strip())
code = line[:3]
try:
errcode = int(code)
except ValueError:
errcode = -1
break
if line[3:4] != "-":
break
errmsg = "\n".join(resp)
return errcode, errmsg
def putcmd(sock, cmd):
if debug:
print 'Send \'%s\'' % cmd
sock.send('%s%s' % (cmd, '\r\n'))
def ehlo(sock):
putcmd(sock, 'ehlo 127.0.0.1')
return getreply(sock)
def helo(sock):
putcmd(sock, 'helo 127.0.0.1')
return getreply(sock)
def ehlo_or_helo_if_needed(sock):
if not (200 <= ehlo(sock)[0] <= 299):
(code, resp) = helo(sock)
if not (200 <= code <= 299):
raise Exception('Hello error')
if "email" in arg:
email = arg['email'].value
tmp = email.split('@')
if len(tmp) != 2:
print 'Incorrect mail %s' % email
exit()
else:
domain = tmp[1]
mxs = DNS.mxlookup(domain)
if len(mxs) < 1:
print 'No mx records at %s' % domain
if debug:
print mxs
if check(mxs[0][1], email):
print 'OK'
else:
print 'Nope ;('
else:
print 'No email to check'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment