Skip to content

Instantly share code, notes, and snippets.

@krazybean
Created December 19, 2017 06:44
Show Gist options
  • Select an option

  • Save krazybean/068ae1d23ea0ecf5c2c8728243696814 to your computer and use it in GitHub Desktop.

Select an option

Save krazybean/068ae1d23ea0ecf5c2c8728243696814 to your computer and use it in GitHub Desktop.
Gmail email address validation
import sys
import random
import smtplib
class Gmail(object):
"""
Verify Gmail email box exists
"""
def __init__(self):
"""
Setup for random smtp_host selection and sender declaration.
"""
self.smtp_hosts = ['gmail-smtp-in.l.google.com',
'alt1.gmail-smtp-in.l.google.com',
'alt2.gmail-smtp-in.l.google.com',
'alt3.gmail-smtp-in.l.google.com',
'alt4.gmail-smtp-in.l.google.com']
self.sender = 'example@codecult.io'
def parse_code(self, response):
""" Parse the response for the code
Args:
response (tuple): Response body from smtp connection.
Returns:
code (int): 2xx or 5xx dependent on mailbox existence.
"""
code = None
if response:
code = int(response[0])
return code
def connect(self, host, sender, mailbox):
""" Connect to SMTP host and request a response
Args:
host (str): Gmail SMTP host
sender (str): Sending email address
mailbox (str): Mailbox to check for
Returns:
reply (str): SMTP Server response
"""
smtp = smtplib.SMTP()
smtp.connect(host)
smtp.docmd('helo', 'codecult.io')
smtp.docmd('mail from:', '<{0}>'.format(sender))
reply = smtp.docmd('rcpt to:', '<{0}>'.format(mailbox))
smtp.quit()
return reply
def results(self, code):
""" Massage response code to return an undersetandable response.
Args:
code (int): Code to evaulate for a response
Returns:
response (str): Understandable existence response.
"""
if code:
if code in range(200, 299):
return "exists"
elif code in range(500, 599):
return "does not exist"
def validate(self, mailbox):
""" Main function to initiate the check
Args:
mailbox (str): Email Address (test@gmail.com)
Returns:
string: test@gmail.com (does|does not) exist
"""
smtp_host = random.choice(self.smtp_hosts)
response = self.connect(smtp_host, self.sender, mailbox)
return '{0} {1}'.format(mailbox,
self.results(self.parse_code(response)))
if __name__ == '__main__':
gmail = Gmail()
mailbox = 'test@gmail.com'
if len(sys.argv) >= 1:
mailbox = sys.argv[1]
print gmail.validate(mailbox)
@theerrorfinder
Copy link

can this be updated? with all the code that gmail gives like inbox full, valid, invalid and spamtrap?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment