Email Validation 3 C# Code Snippet

using EV3Service;
using System.ServiceModel;

namespace email_validation_3_dot_net.SOAP
{
    /// <summary>
    /// Provides functionality to call the ServiceObjects Email Validation SOAP service's ValidateEmailAddress operation,
    /// validating an email address with options for corrections and timeout, with fallback to a backup endpoint for reliability.
    /// </summary>
    public class ValidateEmailAddressValidation
    {
        private const string LiveBaseUrl = "https://sws.serviceobjects.com/ev3/api.svc/soap";
        private const string BackupBaseUrl = "https://swsbackup.serviceobjects.com/ev3/api.svc/soap";
        private const string TrialBaseUrl = "https://trial.serviceobjects.com/ev3/api.svc/soap";

        private readonly string _primaryUrl;
        private readonly string _backupUrl;
        private readonly int _timeoutMs;
        private readonly bool _isLive;

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateEmailAddress"/> class, configuring primary and backup URLs based on the environment.
        /// </summary>
        /// <param name="isLive">Indicates whether to use live or trial endpoints.</param>
        /// <exception cref="InvalidOperationException">Thrown if primary or backup URLs are not set.</exception>
        public ValidateEmailAddressValidation(bool isLive)
        {
            _timeoutMs = 10000;
            _isLive = isLive;

            _primaryUrl = isLive ? LiveBaseUrl : TrialBaseUrl;
            _backupUrl = isLive ? BackupBaseUrl : TrialBaseUrl;

            if (string.IsNullOrWhiteSpace(_primaryUrl))
                throw new InvalidOperationException("Primary URL not set.");
            if (string.IsNullOrWhiteSpace(_backupUrl))
                throw new InvalidOperationException("Backup URL not set.");
        }

        /// <summary>
        /// Asynchronously calls the ServiceObjects Email Validation SOAP endpoint to validate an email address.
        /// Attempts the primary endpoint first and falls back to the backup endpoint if the primary call fails or returns a fatal error (Error.TypeCode == "3").
        /// Enforces a timeout to prevent hangs.
        /// </summary>
        /// <param name="emailAddress">The email address to validate (e.g., "example@domain.com").</param>
        /// <param name="allowCorrections">Whether to allow corrections to the email address (e.g., "true" or "false").</param>
        /// <param name="timeout">The timeout duration for the validation request in milliseconds.</param>
        /// <param name="licenseKey">The license key for accessing the service.</param>
        /// <returns>A <see cref="Task{ValidateEmailResponse}"/> containing email validation details or an error.</returns>
        /// <exception cref="Exception">Thrown if both primary and backup endpoints fail.</exception>
        public async Task<ValidateEmailResponse> ValidateEmailAddress(string EmailAddress, string AllowCorrections, string Timeout, string LicenseKey)
        {
            EV3LibraryClient clientPrimary = null;
            EV3LibraryClient clientBackup = null;

            try
            {
                clientPrimary = new EV3LibraryClient();
                clientPrimary.Endpoint.Address = new EndpointAddress(_primaryUrl);
                clientPrimary.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                ValidateEmailResponse response = await clientPrimary.ValidateEmailAddressAsync(
                    EmailAddress, AllowCorrections, Timeout, LicenseKey).ConfigureAwait(false);

                if (_isLive && !IsValid(response))
                {
                    throw new InvalidOperationException("Primary endpoint returned null or a fatal TypeCode=1 error for ValidateEmailAddress");
                }
                return response;
            }
            catch (Exception primaryEx)
            {
                try
                {
                    clientBackup = new EV3LibraryClient();
                    clientBackup.Endpoint.Address = new EndpointAddress(_backupUrl);
                    clientBackup.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(_timeoutMs);

                    return await clientBackup.ValidateEmailAddressAsync(
                        EmailAddress, 
                        AllowCorrections, 
                        Timeout, 
                        LicenseKey
                    ).ConfigureAwait(false);
                }
                catch (Exception backupEx)
                {
                    throw new Exception(
                        $"Both primary and backup endpoints failed for ValidateEmailAddress.\n" +
                        $"Primary error: {primaryEx.Message}\n" +
                        $"Backup error: {backupEx.Message}");
                }
                finally
                {
                    clientBackup?.Close();
                }
            }
            finally
            {
                clientPrimary?.Close();
            }
        }
        private static bool IsValid(ValidateEmailResponse response) => response?.Error == null || response.Error.TypeCode != "3";
    }
}

Email Validation 3 Python Code Snippet

from suds.client import Client
from suds import WebFault
from suds.sudsobject import Object


class ValidateEmailAddressSoap:
    
  def __init__(self, license_key: str, is_live: bool, timeout_ms: int = 30000):
        """
        license_key: Service Objects EV3 license key.
        is_live: Whether to use live or trial endpoints
        timeout_ms: SOAP call timeout in milliseconds
        """
        if not license_key:
            raise ValueError("LicenseKey cannot be empty or null.")

        self._timeout_s = timeout_ms / 1000.0  
        self._is_live = is_live
        self.license_key = license_key

        # WSDL URLs
        self._primary_wsdl = (
            'https://sws.serviceobjects.com/ev3/api.svc?wsdl'
            if is_live else
            'https://trial.serviceobjects.com/ev3/api.svc?wsdl'
        )
        self._backup_wsdl = (
            'https://swsbackup.serviceobjects.com/ev3/api.svc?wsdl'
            if is_live else
            'https://trial.serviceobjects.com/ev3/api.svc?wsdl'
        )

  def validate_email_address(self, email_address: str, allow_corrections: str, timeout:str) -> Object:
        """
        Call EV3 ValidateEmailAddress SOAP  API to retrieve the information.
        
        Parameters:
            email_address: The email address to validate.
            allow_corrections: "true" or "false" - whether the API can return a corrected email.
            timeout: Timeout value in string format (passed to the service).

        Returns:
            suds.sudsobject.Object: SOAP response containing validation details or error.
        """

        # Common kwargs for both calls
        call_kwargs = dict(
            EmailAddress=email_address,
            AllowCorrections=allow_corrections,
            Timeout=timeout,
            LicenseKey=self.license_key,
        )

        # Attempt primary
        try:
            client = Client(self._primary_wsdl)

             # Override endpoint URL if needed:
            response = client.service.ValidateEmailAddress(**call_kwargs)

            # If response invalid or Error.TypeCode == "3", trigger fallback
            if response is None or (hasattr(response, "Error") and response.Error and response.Error.TypeCode == "3"):
                raise ValueError("Primary returned no result or Error.TypeCode=3")

            return response

        except (WebFault, ValueError, Exception) as primary_ex:
            try:
                client = Client(self._backup_wsdl)
                response = client.service.ValidateEmailAddress(**call_kwargs)

                if response is None:
                    raise ValueError("Backup returned no result")
                return response
            except (WebFault, Exception) as backup_ex:
                msg = (
                    "Both primary and backup endpoints failed.\n"
                    f"Primary error: {str(primary_ex)}\n"
                    f"Backup error: {str(backup_ex)}"
                )
                raise RuntimeError(msg)

Email Validation 3 NodeJS Code Snippet

import { soap } from "strong-soap";

/**
 * <summary>
 * A class that provides functionality to call the ServiceObjects Email Validation 3 SOAP service's ValidateEmailAddress endpoint,
 * validating an email address with fallback to a backup endpoint for reliability in live mode.
 * </summary>
 */
class ValidateEmailAddressSoap {
    /**
     * <summary>
     * Initializes a new instance of the ValidateEmailAddressSoap class with the provided input parameters,
     * setting up primary and backup WSDL URLs based on the live/trial mode.
     * </summary>
     * <param name="emailAddress" type="string">The email address to validate.</param>
     * <param name="licenseKey" type="string">Your license key to use the service.</param>
     * <param name="isLive" type="boolean">Determines whether to use the live or trial service.</param>
     * <param name="timeoutSeconds" type="number">Timeout, in seconds, for the call to the service.</param>
     * <returns type="Promise<EV3Response>">A promise that resolves to an EV3Response object.</returns>
     * <exception cref="Error">Thrown if the license key is empty or null.</exception>
     */
    constructor(emailAddress, allowCorrections, licenseKey, isLive, timeout, timeoutSeconds) {

        this.args = {
            EmailAddress: emailAddress,
            AllowCorrections: allowCorrections,
            Timeout: timeout,
            LicenseKey: licenseKey
        };

        this.isLive = isLive;
        this.timeoutSeconds = timeoutSeconds;

        this.LiveBaseUrl = "https://sws.serviceobjects.com/ev3/api.svc?wsdl";
        this.BackupBaseUrl = "https://swsbackup.serviceobjects.com/ev3/api.svc?wsdl";
        this.TrialBaseUrl = "https://trial.serviceobjects.com/ev3/api.svc?wsdl";

        this._primaryWsdl = this.isLive ? this.LiveBaseUrl : this.TrialBaseUrl;
        this._backupWsdl = this.isLive ? this.BackupBaseUrl : this.TrialBaseUrl;
    }

    /**
     * <summary>
     * Asynchronously calls the ValidateEmailAddress SOAP endpoint, attempting the primary endpoint
     * first and falling back to the backup if the response is invalid (Error.TypeCode == '3') in live mode
     * or if the primary call fails.
     * </summary>
     * <returns type="Promise<EV3Response>">A promise that resolves to an EV3Response object containing email validation details or an error.</returns>
     * <exception cref="Error">Thrown if both primary and backup calls fail, with detailed error messages.</exception>
     */
    async validateEmailAddress() {
        try {
            const primaryResult = await this._callSoap(this._primaryWsdl, this.args);

            if (this.isLive && !this._isValid(primaryResult)) {
                console.warn("Primary returned Error.TypeCode == '3', falling back to backup...");
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            }
            return primaryResult;
        } catch (primaryErr) {
            try {
                const backupResult = await this._callSoap(this._backupWsdl, this.args);
                return backupResult;
            } catch (backupErr) {
                throw new Error(`Both primary and backup calls failed:\nPrimary: ${primaryErr.message}\nBackup: ${backupErr.message}`);
            }
        }
    }

    /**
     * <summary>
     * Performs a SOAP service call to the specified WSDL URL with the given arguments,
     * creating a client and processing the response into an EV3Response object.
     * </summary>
     * <param name="wsdlUrl" type="string">The WSDL URL of the SOAP service endpoint (primary or backup).</param>
     * <param name="args" type="Object">The arguments to pass to the ValidateEmailAddress method.</param>
     * <returns type="Promise<EV3Response>">A promise that resolves to an EV3Response object containing the SOAP response data.</returns>
     * <exception cref="Error">Thrown if the SOAP client creation fails, the service call fails, or the response cannot be parsed.</exception>
     */
    _callSoap(wsdlUrl, args) {
        return new Promise((resolve, reject) => {
            soap.createClient(wsdlUrl, { timeout: this.timeoutSeconds * 1000 }, (err, client) => {
                if (err) return reject(err);

                client.ValidateEmailAddress(args, (err, result) => {
                    if (err) return reject(err);
                    const rawData = result.ValidateEmailAddressResult;
                    try {
                        if (!rawData) {
                            return reject(new Error("SOAP response is empty or undefined."));
                        }
                        resolve(rawData);
                    } catch (parseErr) {
                        reject(new Error(`Failed to parse SOAP response: ${parseErr.message}`));
                    }
                });
            });
        });
    }

    /**
     * <summary>
     * Checks if a SOAP response is valid by verifying that it exists and either has no Error object
     * or the Error.Number is not equal to '3'.
     * </summary>
     * <param name="response" type="EV3Response">The EV3Response object to validate.</param>
     * <returns type="boolean">True if the response is valid, false otherwise.</returns>
     */
    _isValid(response) {
        return response && (!response.Error || response.Error.TypeCode !== '3');
    }
}

export { ValidateEmailAddressSoap };