emailverifygo

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2025 License: MIT Imports: 9 Imported by: 0

README

EmailVerify.io Go Package

A Go package for interacting with EmailVerify.io services. This package provides a simple and efficient way to validate email addresses, perform batch validations, find email addresses by name and domain, and check your account balance.

Installation

go get github.com/Clustox/emailverifygo

Features

  1. Email Validation: Verify the validity of individual email addresses
  2. Batch Email Validation: Validate multiple email addresses at once
  3. Email Finder: Find email addresses by name and domain
  4. Account Balance: Check your account balance and credits

API Key Configuration

This package uses the EmailVerify API which requires an API key. This key can be provide in three ways:

  1. Through an environment variable EMAIL_VERIFY_API_KEY (loaded automatically in code)
  2. Through an .env file that contains EMAIL_VERIFY_API_KEY and then calling following method before usage:
emailverifygo.LoadEnvFromFile()
  1. By settings explicitly in code, using the following method:
emailverifygo.SetApiKey("<YOUR_API_KEY>")

Usage Examples

Check Account Balance

Check your account balance and credit information.

package main

import (
	"fmt"

	"github.com/Clustox/emailverifygo"
)

func main() {
    emailverifygo.SetApiKey("<YOUR_API_KEY>")

	response, error_ := emailverifygo.GetAccountBalance()

	if error_ != nil {
		fmt.Println("error occurred: ", error_.Error())
	} else {
		fmt.Printf("Full response: %+v\n", response)
		fmt.Println("API Status:", response.APIStatus)
		fmt.Println("Daily Credits Limit:", response.DailyCreditsLimit)
		fmt.Println("Referral Credits:", response.ReferralCredits) // For appsumo accounts, ReferralCredits will be 0
		fmt.Println("Remaining Credits:", response.RemainingCredits)
		fmt.Println("Remaining Daily Credits:", response.RemainingDailyCredits) // For non-appsumo accounts, RemainingDailyCredits will be 0
		fmt.Println("Bonus Credits:", response.BonusCredits) // For non-appsumo accounts, BonusCredits will be 0
	}
}
Email Validation

Validate a single email address to check if it's valid, invalid, or has other status flags.

package main

import (
	"fmt"
	"github.com/Clustox/emailverifygo"
)

func main() {
	emailverifygo.SetApiKey("<YOUR_API_KEY>")
	
	response, error_ := emailverifygo.Validate("possible_typo@example.com")
	
	if error_ != nil {
		fmt.Println("error occurred: ", error_.Error())
	} else {
		// Now you can check status
		fmt.Println("Response", response)
		fmt.Println("Email", response.Email)
		fmt.Println("Status", response.Status)
		fmt.Println("Substatus", response.SubStatus)

		if response.Status == emailverifygo.STATUS_DO_NOT_MAIL {
			fmt.Println("This email's status is do not email")
		}

		if response.SubStatus == emailverifygo.SUBSTATUS_MAILBOX_QUOTA_EXCEEDED {
			fmt.Println("This email's sub status is mailbox quota exceeded")
		}
	}
}

We have below mentioned Constants you can use to check variable status and substatus

// Status constants
const (
	STATUS_VALID       = "valid"       // The email is valid and deliverable
	STATUS_INVALID     = "invalid"     // The email is invalid or undeliverable
	STATUS_CATCH_ALL   = "catch_all"   // The domain has a catch-all policy
	STATUS_DO_NOT_MAIL = "do_not_mail" // The email should not be mailed to
	STATUS_UNKNOWN     = "unknown"     // The status could not be determined
	STATUS_ROLE_BASED  = "role_based"  // The email is a role-based address (e.g., info@, support@)
	STATUS_SKIPPED     = "skipped"     // The validation was skipped for this email
)

// Sub-status constants
const (
	SUBSTATUS_PERMITTED            = "permitted"             // Email is permitted for sending
	SUBSTATUS_FAILED_SYNTAX_CHECK  = "failed_syntax_check"   // Email failed syntax validation
	SUBSTATUS_MAILBOX_QUOTA_EXCEEDED = "mailbox_quota_exceeded" // Mailbox is full
	SUBSTATUS_MAILBOX_NOT_FOUND    = "mailbox_not_found"     // Mailbox does not exist
	SUBSTATUS_NO_DNS_ENTRIES       = "no_dns_entries"        // Domain has no DNS entries
	SUBSTATUS_DISPOSABLE           = "disposable"            // Email is from a disposable domain
	SUBSTATUS_NONE                 = "none"                  // No specific sub-status
	SUBSTATUS_OPT_OUT              = "opt_out"               // User has opted out
	SUBSTATUS_BLOCKED_DOMAIN       = "blocked_domain"        // Domain is blocked
)
Batch Email Validation

Submit multiple emails for validation in a single batch operation.

package main

import (
	"fmt"

	"github.com/Clustox/emailverifygo"
)

func main() {
	emailverifygo.SetApiKey("<YOUR_API_KEY>")

	emails := []string{
		"user1@example.com",
		"user2@example.com",
		"user3@example.com",
		"user4@example.com",
	}
	
	response, error_ := emailverifygo.ValidateBatch("<Title>", emails) //Tittle and emails are required fields

	if error_ != nil {
		fmt.Println("error occurred: ", error_.Error())
	} else {
		fmt.Println("Response", response)
		fmt.Println("Status", response.Status)
		fmt.Println("TaskID", response.TaskID) // IMPORTANT! SAVE IT to later fetch the results
		fmt.Println("CountSubmitted", response.CountSubmitted)
		fmt.Println("CountRejected", response.CountRejected)
		fmt.Println("CountProcessing", response.CountProcessing)
		fmt.Println("Count Duplicate Removed", response.CountDuplicatesRemoved)
	}
}
Retrieve Batch Validation Results

Retrieve the results of a previously submitted batch validation using the Task ID.

package main
import (
	"fmt"
	"github.com/Clustox/emailverifygo"
)
	
func main() {
	emailverifygo.SetApiKey("<YOUR_API_KEY>")

	response, error_ := emailverifygo.GetBatchResults(<TASK_ID>) // TASK ID received in bulk validate, must be integer

	if error_ != nil {
		fmt.Println("error occurred: ", error_.Error())
	} else {
		fmt.Println("Response", response)
		fmt.Println("CountChecked", response.CountChecked)
		fmt.Println("Count Total", response.CountTotal)
		fmt.Println("Title", response.Name)
		fmt.Println("Status", response.Status)
		fmt.Println("Task Id", response.TaskID)
		fmt.Println("Progress Percentage", response.ProgressPercentage)
		fmt.Println("Results", response.Results) // results can be {[]} when verification under process

		// Way to fetch emails and their result
		for _, res := range response.Results.EmailBatch {
     	   fmt.Printf("Email: %s, Status: %s, SubStatus: %s\n", res.Address, res.Status, res.SubStatus)
        }
	}
}
Find Email by Name and Domain

Find email addresses associated with a person at a specific domain.

package main

import (
	"fmt"

	"github.com/Clustox/emailverifygo"
)

func main() {
	emailverifygo.SetApiKey("<YOUR_API_KEY>")

	response, error_ := emailverifygo.FindEmail("<NAME>", "DOMAIN.COM")

	if error_ != nil {
		fmt.Println("error occurred: ", error_.Error())
	} else {
		fmt.Println("Response", response)
		fmt.Println("Email", response.Email) // WILL BE 'null' WHEN EMAIL NOT FOUND
		fmt.Println("Status", response.Status) // STATUS CAN BE found or not_found
	}
}

Testing

The package includes several levels of tests to ensure everything works correctly:

Unit Tests

Run the basic unit tests (uses mocked responses, no API key required):

go test -v

Documentation

Index

Constants

View Source
const (
	MOCK_VALID_RESPONSE = `{
		"email": "valid@example.com",
		"status": "valid",
		"sub_status": "permitted"
	}`

	MOCK_INVALID_RESPONSE = `{
		"email": "invalid@example.com",
		"status": "invalid",
		"sub_status": "mailbox_not_found"
	}`

	MOCK_BATCH_RESPONSE = `` /* 158-byte string literal not displayed */

	MOCK_BATCH_RESULTS_RESPONSE = `` /* 521-byte string literal not displayed */

	MOCK_FINDER_RESPONSE = `{
		"email": "john.doe@example.com",
		"status": "found"
	}`

	MOCK_FINDER_NOT_FOUND_RESPONSE = `{
		"email": "null",
		"status": "not_found"
	}`

	MOCK_ACCOUNT_BALANCE_RESPONSE = `{
		"api_status": "enabled",
		"daily_credits_limit": 150,
		"remaining_credits": 15000
	}`

	MOCK_ERROR_RESPONSE = `{
		"error": "Invalid API key"
	}`
)

Mock responses for testing (these are just examples and will be replaced by httpmock)

View Source
const (
	ENDPOINT_VALIDATE        = "/api/v1/validate"
	ENDPOINT_VALIDATE_BATCH  = "/api/v1/validate-batch"
	ENDPOINT_EMAIL_FINDER    = "/api/v1/finder"
	ENDPOINT_ACCOUNT_BALANCE = "/api/v1/check-account-balance"
	ENDPOINT_BATCH_RESULT    = "/api/v1/get-result-bulk-verification-task"
)

API endpoints

View Source
const (
	STATUS_VALID       = "valid"       // The email is valid and deliverable
	STATUS_INVALID     = "invalid"     // The email is invalid or undeliverable
	STATUS_CATCH_ALL   = "catch_all"   // The domain has a catch-all policy
	STATUS_DO_NOT_MAIL = "do_not_mail" // The email should not be mailed to
	STATUS_UNKNOWN     = "unknown"     // The status could not be determined
	STATUS_ROLE_BASED  = "role_based"  // The email is a role-based address (e.g., info@, support@)
	STATUS_SKIPPED     = "skipped"     // The validation was skipped for this email
)

Email validation status constants

View Source
const (
	SUBSTATUS_PERMITTED              = "permitted"              // Email is permitted for sending
	SUBSTATUS_FAILED_SYNTAX_CHECK    = "failed_syntax_check"    // Email failed syntax validation
	SUBSTATUS_MAILBOX_QUOTA_EXCEEDED = "mailbox_quota_exceeded" // Mailbox is full
	SUBSTATUS_MAILBOX_NOT_FOUND      = "mailbox_not_found"      // Mailbox does not exist
	SUBSTATUS_NO_DNS_ENTRIES         = "no_dns_entries"         // Domain has no DNS entries
	SUBSTATUS_DISPOSABLE             = "disposable"             // Email is from a disposable domain
	SUBSTATUS_NONE                   = "none"                   // No specific sub-status
	SUBSTATUS_OPT_OUT                = "opt_out"                // User has opted out
	SUBSTATUS_BLOCKED_DOMAIN         = "blocked_domain"         // Domain is blocked
)

Email validation sub-status constants

Variables

View Source
var (
	// URI used to make requests to the EmailVerify API
	URI = Getenv(`EMAIL_VERIFY_URI`, `https://app.emailverify.io`)

	// API_KEY the API key used in order to make the requests
	API_KEY string = os.Getenv("EMAIL_VERIFY_API_KEY")
)

Global variables

View Source
var ErrMissingAPIKey = errors.New("API key not set. Use SetApiKey() or LoadEnvFromFile() to set it")

ErrMissingAPIKey is returned when the API key is not set

Functions

func DoGetRequest

func DoGetRequest(url string, object APIResponse) error

DoGetRequest performs a GET request to the API

func DoPostRequest

func DoPostRequest(url string, payload io.Reader, object APIResponse) error

DoPostRequest performs a POST request to the API

func ErrorFromResponse

func ErrorFromResponse(response *http.Response) error

ErrorFromResponse parses an error response from the API This handles the inconsistent error message formats returned by the API

func GetBaseURI

func GetBaseURI() string

GetBaseURI returns the current base URI for the API

func Getenv

func Getenv(key, fallback string) string

Getenv gets an environment variable or returns a default value if it's not set

func LoadEnvFromFile

func LoadEnvFromFile() bool

LoadEnvFromFile loads environment variables from a .env file and sets the API key and URI. It returns true if the file was loaded successfully, false otherwise. It won't print any messages to stdout, so it's suitable for library use.

func PrepareURL

func PrepareURL(endpoint string, params url.Values) (string, error)

PrepareURL prepares the URL for a request by attaching the API key and params

func SetApiKey

func SetApiKey(newApiKey string)

SetApiKey sets the API key for all future requests

func SetURI

func SetURI(newURI string)

SetURI updates the base URI for the API Useful for testing against staging environments

Types

type APIResponse

type APIResponse interface{}

APIResponse is an interface for all API response types

type AccountBalanceResponse

type AccountBalanceResponse struct {
	APIStatus             string `json:"api_status"`
	DailyCreditsLimit     int    `json:"daily_credits_limit"`
	ReferralCredits       int    `json:"referral_credits,omitempty"`
	RemainingCredits      int    `json:"remaining_credits,omitempty"`
	RemainingDailyCredits int    `json:"remaining_daily_credits,omitempty"`
	BonusCredits          int    `json:"bonus_credits,omitempty"`
}

AccountBalanceResponse represents the response from the account balance API Different fields may be present depending on the account type.

func GetAccountBalance

func GetAccountBalance() (*AccountBalanceResponse, error)

type BatchResultResponse

type BatchResultResponse struct {
	CountChecked       int                         `json:"count_checked,omitempty"`
	CountTotal         int                         `json:"count_total,omitempty"`
	TaskID             int                         `json:"task_id,omitempty"`
	Name               string                      `json:"name,omitempty"`
	Status             string                      `json:"status,omitempty"`
	ProgressPercentage float64                     `json:"progress_percentage,omitempty"`
	Results            BatchValidateResultsWrapper `json:"results,omitempty"`
}

func GetBatchResults

func GetBatchResults(taskID int) (*BatchResultResponse, error)

GetBatchResults retrieves the results of a previously submitted batch validation task

Parameters:

  • taskID: The ID of the batch validation task to retrieve results for

Returns:

  • *BatchValidateResponse: The batch validation results
  • error: Any error that occurred during retrieval

API Reference: GET /api/v1/get-result-bulk-verification-task

type BatchValidateRequest

type BatchValidateRequest struct {
	Title      string         `json:"title"`
	Key        string         `json:"key"`
	EmailBatch []EmailAddress `json:"email_batch"`
}

BatchValidateRequest represents the structure of the batch validation request

type BatchValidateResponse

type BatchValidateResponse struct {
	Status                 string `json:"status,omitempty"`                   // For initial submit response
	TaskID                 int    `json:"task_id"`                            // Task ID for batch validation
	CountSubmitted         int    `json:"count_submitted,omitempty"`          // For initial submit response
	CountDuplicatesRemoved int    `json:"count_duplicates_removed,omitempty"` // For initial submit response
	CountRejected          int    `json:"count_rejected_emails,omitempty"`    // For initial submit response
	CountProcessing        int    `json:"count_processing,omitempty"`         // For initial submit response
}

BatchValidateResponse represents the structure of a batch validate response

func ValidateBatch

func ValidateBatch(title string, emails []string) (*BatchValidateResponse, error)

ValidateBatch submits a batch of emails for Verification

Parameters:

  • title: The name for this batch validation task
  • emails: A slice of email addresses to validate

Returns:

  • *BatchValidateResponse: The initial batch submission response
  • error: Any error that occurred during submission

API Reference: POST /api/v1/validate-batch

type BatchValidateResultsWrapper

type BatchValidateResultsWrapper struct {
	EmailBatch []EmailBatchResult `json:"email_batch"`
}

BatchValidateResultsWrapper wraps the email_batch results from the API

type EmailAddress

type EmailAddress struct {
	Address string `json:"address"`
}

EmailAddress represents one email address unit to be validated in a batch

type EmailBatchError

type EmailBatchError struct {
	Error   string `json:"error"`
	Address string `json:"address"`
}

EmailBatchError an error unit received in the response, that can be associated with an email sent to the batch validate endpoint

type EmailBatchResult

type EmailBatchResult struct {
	Address   string `json:"address"`
	Status    string `json:"status"`
	SubStatus string `json:"sub_status"`
}

EmailBatchResult represents a single result in the batch validation

type FindEmailResponse

type FindEmailResponse struct {
	Email  string `json:"email"`  // The email address found, or "null" if not found
	Status string `json:"status"` // "found" or "not_found"
}

FindEmailResponse response structure for the Email Finder API

func FindEmail

func FindEmail(name, domain string) (*FindEmailResponse, error)

FindEmail uses a combined name parameter and domain to find a valid business email

Parameters:

  • name: The full name of the person to search for (e.g., "John Smith")
  • domain: The domain to search for the email on

Returns:

  • *FindEmailResponse: The email finder result
  • error: Any error that occurred during the request

API Reference: GET /api/v1/finder

func (*FindEmailResponse) IsFound

func (f *FindEmailResponse) IsFound() bool

IsFound checks if an email was found

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface for making HTTP requests

type ValidateResponse

type ValidateResponse struct {
	Email     string `json:"email"`      // The email address being validated
	Status    string `json:"status"`     // Status of the email (valid, invalid, etc.)
	SubStatus string `json:"sub_status"` // Detailed status information
}

ValidateResponse contains the fields that are returned by the API for single email validation requests.

func Validate

func Validate(email string) (*ValidateResponse, error)

Validate performs validation on a single email address

Parameters:

  • email: The email address to validate

Returns:

  • *ValidateResponse: The validation result
  • error: Any error that occurred during validation

API Reference: GET /api/v1/validate

func (*ValidateResponse) IsValid

func (v *ValidateResponse) IsValid() bool

IsValid returns true if the email status is "valid"

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL