Getting started overview

Integrating mailboxlayer involves a sequence of steps designed to quickly enable real-time email validation within an application. The process begins with account creation, which provides the necessary API access key for authenticating requests. Once an API key is obtained, developers can construct and execute their initial API call to the mailboxlayer endpoint, verifying an email address. This initial verification confirms the API key's validity and demonstrates the service's core functionality. Subsequent steps typically involve refining integration, handling API responses, and scaling usage according to application requirements.

The mailboxlayer API operates as a RESTful service, accepting HTTP GET requests. Responses are returned in JSON format, providing data points such as email validity, syntax checks, domain existence, and common email provider flags. The API's design focuses on simplicity, facilitating integration across various programming languages and platforms, as detailed in the mailboxlayer API documentation.

Quick Reference Table

Step What to Do Where
1. Sign Up Create a mailboxlayer account to get an API key. mailboxlayer homepage
2. Locate API Key Find your unique 32-character API key. mailboxlayer account dashboard
3. Construct Request Build the API endpoint URL with your key and target email. Using the mailboxlayer API reference
4. Execute Request Send an HTTP GET request to the constructed URL. From your application or a testing tool (e.g., cURL, Postman)
5. Parse Response Process the JSON response to extract validation data. Within your application's code

Create an account and get keys

To begin using the mailboxlayer API, an account is required to generate a unique API access key. This key authenticates all requests made to the API, ensuring secure and authorized access to the service. mailboxlayer offers a free tier that includes 1,000 API requests per month, which is sufficient for initial testing and development.

Account Creation Process

  1. Navigate to the mailboxlayer website: Open your web browser and go to the mailboxlayer homepage.
  2. Sign up: Look for a "Sign Up" or "Get Started" button. You will typically be prompted to enter your email address and create a password.
  3. Verify email (if prompted): Some services require email verification to activate the account. Check your inbox for a confirmation link.
  4. Access dashboard: Upon successful signup and login, you will be redirected to your personal mailboxlayer dashboard.

Locating Your API Access Key

Your API access key is a critical credential that must be kept confidential. It is typically displayed prominently within your account dashboard once you have signed in.

  1. Log in: If not already logged in, navigate to the mailboxlayer site and log in using your registered credentials.
  2. Dashboard access: Your API key is usually visible on the main page of your dashboard. It is a 32-character alphanumeric string.
  3. Copy the key: Copy this key carefully. It will be used in every API request you make.

The API key acts as a form of token-based authentication, a common pattern in RESTful API design, as explained in general API security guidelines such as those provided by Google's API key usage documentation. It should be passed as a query parameter in your API requests.

Your first request

After obtaining your API access key, you are ready to make your first request to the mailboxlayer API. This section demonstrates how to construct and execute a basic email validation request.

API Endpoint Structure

The core endpoint for email validation is structured as follows:

http://api.mailboxlayer.com/api/check
  ? access_key = YOUR_ACCESS_KEY
  & email = TARGET_EMAIL_ADDRESS
  [ & smtp = 1 ]
  [ & format = 1 ]
  • access_key: Your unique 32-character API key.
  • email: The email address you wish to validate.
  • smtp (optional): Set to 1 to enable SMTP verification. This performs a deeper check for email deliverability.
  • format (optional): Set to 1 to receive a formatted JSON response.

Example Request using cURL

cURL is a command-line tool and library for transferring data with URLs. It is a common method for testing REST APIs. Replace YOUR_ACCESS_KEY with your actual key and [email protected] with the email you want to validate.

curl "http://api.mailboxlayer.com/api/check?access_key=YOUR_ACCESS_KEY&[email protected]&smtp=1"

Example Requests in Popular Languages

mailboxlayer provides examples in PHP, Python, jQuery, Go, and Ruby. The following examples demonstrate a basic request in Python and JavaScript (jQuery).

Python Example

This Python script uses the requests library to send a GET request and print the JSON response.

import requests
import json

access_key = 'YOUR_ACCESS_KEY'
email_address = '[email protected]'

# Construct the API request URL
api_url = f"http://api.mailboxlayer.com/api/check?access_key={access_key}&email={email_address}&smtp=1"

try:
    response = requests.get(api_url)
    response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()

    # Print the full JSON response for inspection
    print(json.dumps(data, indent=4))

    # Example of accessing specific validation results
    if data.get('format_valid') and data.get('mx_found') and data.get('smtp_check'):
        print(f"Email '{email_address}' appears valid and deliverable.")
    else:
        print(f"Email '{email_address}' validation details: Invalid format: {not data.get('format_valid')}, No MX record: {not data.get('mx_found')}, SMTP check failed: {not data.get('smtp_check')}")

except requests.exceptions.RequestException as e:
    print(f"An error occurred during the API request: {e}")
except ValueError:
    print("Failed to parse JSON response. Check API key and network connection.")

jQuery Example (Client-side)

This JavaScript snippet uses jQuery's $.ajax method. Note that exposing API keys directly in client-side code is generally discouraged for security reasons, especially for paid tiers, as it can be easily extracted by users. For production applications, server-side integration is recommended.

$(document).ready(function() {
  var access_key = 'YOUR_ACCESS_KEY';
  var email_address = '[email protected]';

  $.ajax({
      url: 'http://api.mailboxlayer.com/api/check?access_key=' + access_key + '&email=' + email_address + '&smtp=1',
      dataType: 'jsonp',
      success: function(json) {
          // API response successfully received
          console.log(json);

          // Example: Check if the email is valid
          if (json.format_valid && json.mx_found && json.smtp_check) {
              $('#validation-result').text('Email ' + email_address + ' is valid and deliverable.');
          } else {
              $('#validation-result').text('Email ' + email_address + ' validation failed. Details: ' + JSON.stringify(json));
          }
      },
      error: function(jqXHR, textStatus, errorThrown) {
          // An error occurred during the API call
          console.error("API request failed: " + textStatus, errorThrown);
          $('#validation-result').text('Error validating email.');
      }
  });
});

After executing the request, the API will return a JSON object containing detailed validation results for the specified email address. Key fields in the response include format_valid, mx_found, smtp_check, and various error codes or flags, as documented in the mailboxlayer API reference.

Common next steps

Once you have successfully made your first API call and understand the basic request/response cycle, consider these common next steps for a robust integration:

  • Error Handling: Implement comprehensive error handling based on the API's error codes. This includes network errors, invalid API keys, rate limits, and email-specific validation failures. The mailboxlayer error codes documentation provides specific details.
  • Response Parsing and Logic: Develop application logic to parse the JSON response and act upon the validation results. For instance, you might prevent signup for invalid emails or flag suspicious addresses for manual review.
  • SMTP Check Integration: If not already done, integrate the smtp=1 parameter for a more thorough validation, which includes checking if an SMTP server accepts mail for the address. Be aware that SMTP checks can sometimes introduce slight latency.
  • Rate Limiting: Understand and respect the API's rate limits. For the free tier, this is 1,000 requests per month. For higher volumes, consider upgrading to a paid plan to avoid interruptions.
  • Asynchronous Processing: For bulk validation or processes where immediate feedback isn't critical, consider making API calls asynchronously to prevent blocking your application's main thread.
  • Data Storage and Caching: Decide if and how to store validation results to avoid re-validating the same email addresses, which can save API requests and improve performance. Implement a caching strategy if appropriate.
  • Secure API Key Management: Ensure your API key is stored and used securely, especially in server-side applications. Avoid hardcoding keys directly into source code and consider environment variables or secure configuration management systems.
  • Monitoring and Logging: Set up monitoring for API call success rates and response times. Implement logging to track API usage and potential issues.
  • Webhooks (if available): While mailboxlayer primarily uses a direct request/response model, some email validation services offer webhooks for asynchronous notifications. Check the mailboxlayer documentation for any updates on such features.

Troubleshooting the first call

Encountering issues during your initial API call is common. Here's a guide to common problems and their solutions:

  • Invalid API Key:
    • Symptom: API returns an error indicating an invalid or missing access key (e.g., "code": 101, "info": "You have not supplied an API Access Key." or "code": 104, "info": "Your current Subscription Plan does not allow this API Feature.").
    • Solution: Double-check that your API key is copied correctly from your mailboxlayer dashboard. Ensure there are no leading or trailing spaces. Verify that the key is passed exactly as access_key=YOUR_ACCESS_KEY in the URL query string. If you're using a free tier, ensure you haven't exceeded the 1,000 request limit, as this can also lead to access errors.
  • Incorrect Endpoint or Parameters:
    • Symptom: HTTP 404 Not Found error, or an API response indicating unknown parameters.
    • Solution: Verify the base URL is http://api.mailboxlayer.com/api/check. Ensure all parameters (access_key, email) are correctly spelled and properly URL-encoded. For example, special characters in an email address (though uncommon for valid emails) should be encoded. Refer to the official API documentation for exact parameter names.
  • Network or Connection Issues:
    • Symptom: Request times out, connection refused, or no response received.
    • Solution: Check your internet connection. If running locally, ensure no firewall or proxy is blocking outbound HTTP requests to api.mailboxlayer.com. Try making the cURL request from a different environment or a public online cURL tester to rule out local network issues.
  • JSON Parsing Errors:
    • Symptom: Your application fails to parse the API response, indicating malformed JSON.
    • Solution: The mailboxlayer API reliably returns JSON for successful requests. If parsing fails, it's likely due to an error response (e.g., HTTP 4xx or 5xx status code) not being valid JSON, or your parsing logic being incorrect. Always check the HTTP status code first. Use a JSON validator or print the raw response to inspect its structure.
  • Rate Limit Exceeded:
    • Symptom: API returns an error related to exceeding request limits (e.g., "code": 104, "info": "Your current Subscription Plan does not allow this API Feature." or a specific rate limit error code).
    • Solution: If on the free tier, you are limited to 1,000 requests/month. Monitor your usage from your dashboard. If you need more requests, consider upgrading to a paid plan. Implement a delay or exponential backoff strategy for retries if hitting rate limits.