How to check if an e mail address exists
There are a few ways to check if an email address exists:
- SMTP Verification: You can use the Simple Mail Transfer Protocol (SMTP) to send a test email to the address and see if it bounces back. This method is not foolproof, as it's possible for the email address to exist but not be monitored or checked regularly.
Here's an example of how you can do this using Python:
import smtplib
def check_email_exists(email):
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'your_password')
server.sendmail('[email protected]', email, 'Test email')
server.quit()
return True
except smtplib.SMTPRecipientsRefused:
return False
email_to_check = '[email protected]'
if check_email_exists(email_to_check):
print(f"{email_to_check} exists")
else:
print(f"{email_to_check} does not exist")
- Email Verification APIs: There are several APIs available that can help you verify if an email address exists. Some popular options include:
- Mailgun's Email Verification API
- Sendgrid's Email Verification API
- Clearbit's Email Verification API
These APIs typically require you to send a request with the email address you want to verify, and they'll respond with a boolean indicating whether the email address exists or not.
Here's an example of how you can use Mailgun's API:
import requests
def check_email_exists(email):
api_key = 'your_api_key'
api_url = f'https://api.mailgun.net/v3/YOUR_DOMAIN/validate'
headers = {'Authorization': f'Basic {api_key}'}
data = {'address': email}
response = requests.post(api_url, headers=headers, json=data)
if response.status_code == 200:
return response.json()['is_valid']
else:
return False
email_to_check = '[email protected]'
if check_email_exists(email_to_check):
print(f"{email_to_check} exists")
else:
print(f"{email_to_check} does not exist")
- Email Provider's API: Some email providers, such as Gmail or Outlook, offer APIs that allow you to verify if an email address exists. For example, Gmail's API has a
users.get
method that returns information about a user, including whether the email address exists.
Here's an example of how you can use Gmail's API:
import google.auth
from googleapiclient.discovery import build
def check_email_exists(email):
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/admin.directory.user'])
service = build('admin', 'directory_v1', credentials=credentials)
user = service.users().get(userId=email).execute()
if user.get('error'):
return False
else:
return True
email_to_check = '[email protected]'
if check_email_exists(email_to_check):
print(f"{email_to_check} exists")
else:
print(f"{email_to_check} does not exist")
Note that these methods may not always work, as email addresses can be created and deleted rapidly. Additionally, some email providers may not provide APIs for verifying email addresses, or may require you to have a paid account or meet certain requirements to access their APIs.