# Verifying Email Addresses with Python's smtplib

## Introduction

Sending [emails](https://bytescrum.com/) is crucial to many [applications](https://emaillistvalidation.com/blog/python-email-verify-ensuring-the-validity-of-email-addresses-with-confidence/), but ensuring that the recipient's email address is valid and deliverable is equally important. Python's `smtplib` module allows developers to interact with SMTP servers to <mark>verify email addresses effectively</mark>. In this comprehensive guide, we'll explore in-depth how to verify email addresses using `smtplib`, including error handling, best practices, and potential pitfalls.

## **Understanding SMTP and Email Verification**

[SMTP](https://www.emailhippo.com/resources/blog/how-does-email-verification-work-using-smtp#:~:text=SMTP%20and%20other%20sources%20build,one%20is%20a%20mail%20server.) (Simple Mail Transfer Protocol) is the standard protocol for sending emails across the internet. To verify an email address, we can <mark>connect to an SMTP server and use the </mark> `RCPT TO` <mark> command to check if the address is deliverable</mark>. The server responds with a status code indicating whether the address is valid.

## **Setting Up Your Environment**

[Before](https://blog.bytescrum.com/how-to-set-up-your-python-development-environment-a-step-by-step-tutorial) we begin, could you make sure you have Python installed on your system? You can install the `smtplib` module using pip:

```bash
pip install secure-smtplib
```

## **The Verify Email Function**

Let's start by defining a function `verify_email` that takes an email address as input and returns a boolean indicating whether the address is deliverable:

```bash
import smtplib

def verify_email(address):
    try:
        with smtplib.SMTP('smtp.example.com') as smtp:
            smtp.helo()
            smtp.mail('your-email@example.com')
            resp = smtp.rcpt(address)
            if resp[0] == 250:
                return True
            elif resp[0] == 550:
                return False
            else:
                return resp[0]
    except smtplib.SMTPServerDisconnected as err:
        print("SMTP connection error:", err)
        return None
```

In this function, we connect to an SMTP server ([`smtp.example.com`](http://smtp.example.com) in this example), introduce ourselves (`helo`), and specify the sender (`mail`). We then use the `rcpt` method to verify the recipient's address. If the address is deliverable, we return `True`; if it's not, we return `False`. If an unexpected response code is received, we return the code for further investigation.

### **Working Example:**

The below code is a working example of email verification using Google SMTP.

```bash
from smtplib import SMTP
import smtplib

address_to_test = "sanjulok22@gmail.com"

def verify_email(address):
    try:
        with SMTP('gmail-smtp-in.l.google.com', port=25) as smtp:
            smtp.helo()  # send the HELO command
            # send the MAIL command
            smtp.mail('sanjays442@gmail.com')
            resp = smtp.rcpt(address)
            if resp[0] == 250:  # check the status code
                deliverable = True
            elif resp[0] == 550:
                deliverable = False
            else:
                print(resp[0])
                return resp[0]
    except smtplib.SMTPServerDisconnected as err:
        print("SMTP connection error", err)
    return deliverable

print(verify_email(address_to_test))
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1715603374351/ba9decbb-b261-4408-834a-1de91c3c713f.png align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">It works mostly with the gmail email addresses but some other email addresses may also work.</div>
</div>

## **Error Handling and Robustness**

Email verification can be prone to [errors](https://medium.com/@darshilvsheth10/handling-errors-like-a-pro-practical-strategies-for-python-error-management-8adffc17e178), such as network issues or server timeouts. It's essential to handle these gracefully to ensure our application remains robust. The `verify_email` function includes error handling to catch `SMTPServerDisconnected` exceptions and print an error message. It then returns `None` to indicate that the verification process encountered an issue.

## **Best Practices and Pitfalls**

When [verifying](https://www.bytescrum.com/portfolio/) email addresses, consider the following best practices and potential pitfalls:

* **Use a Valid Sender Address**: Ensure that the sender address (`mail` command) is valid and authorized to send emails.
    
* **Check for Response Codes**: Always check the response codes from the SMTP server (`rcpt` command) to determine the deliverability status of the email address.
    
* **Handle Errors Gracefully**: Use try-except blocks to handle errors and exceptions, such as `SMTPServerDisconnected`, to prevent application crashes.
    
* **Avoid Excessive Verification**: Avoid verifying email addresses too frequently, as this may lead to temporary bans or restrictions from SMTP servers.
    
* **Consider Rate Limiting**: Implement rate limiting to prevent excessive verification requests and comply with SMTP server policies.
    

<details data-node-type="hn-details-summary"><summary>Conclusion</summary><div data-type="detailsContent">Verifying email addresses is a critical step in ensuring successful email delivery. Python's <code>smtplib</code> module provides a powerful and flexible way to verify addresses by interacting with SMTP servers. By following best practices, handling errors gracefully, and understanding potential pitfalls, you can build robust email verification systems to enhance the reliability of your applications.</div></details>

---

**Share Your Thoughts**

Have you used SMTP verification to validate email addresses in your projects? Share your experiences and tips in the comments below!
