Code Examples
Production-ready code examples for integrating GoEmailVerify into your applications.
cURL / Bash Examples
Single Email Validation
#!/bin/bash
API_KEY="sk_live_your_api_key_here"
BASE_URL="https://goemailverify.com"
# Validate a single email
curl -X POST "$BASE_URL/api/validate/single" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "john.doe@example.com"
}'
# Response:
# {
# "email": "john.doe@example.com",
# "status": "VALID",
# "score": 95,
# "reason": "All checks passed",
# "domainAge": 730,
# "emailAge": "ESTABLISHED",
# "humanNameScore": "LIKELY_HUMAN"
# }
Batch Validation
# Validate multiple emails (max 100)
curl -X POST "$BASE_URL/api/validate/batch" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"emails": [
"user1@example.com",
"user2@example.com",
"user3@example.com"
]
}'
CSV Upload & Job Monitoring
#!/bin/bash
API_KEY="sk_live_your_api_key_here"
BASE_URL="https://goemailverify.com"
# Upload CSV file
RESPONSE=$(curl -X POST "$BASE_URL/api/jobs/upload" \
-H "Authorization: Bearer $API_KEY" \
-F "file=@emails.csv")
# Extract job ID
JOB_ID=$(echo $RESPONSE | jq -r '.jobId')
echo "Job created: $JOB_ID"
# Poll job status
while true; do
STATUS=$(curl -s "$BASE_URL/api/jobs/$JOB_ID/status" \
-H "Authorization: Bearer $API_KEY" | jq -r '.status')
echo "Status: $STATUS"
if [ "$STATUS" = "COMPLETED" ]; then
echo "Job completed!"
break
elif [ "$STATUS" = "FAILED" ]; then
echo "Job failed!"
exit 1
fi
sleep 5
done
# Download results
curl -o results.csv "$BASE_URL/api/jobs/$JOB_ID/download" \
-H "Authorization: Bearer $API_KEY"
echo "Results saved to results.csv"
Check Credit Balance
# Get current credit balance
curl -X GET "$BASE_URL/api/credits/balance" \
-H "Authorization: Bearer $API_KEY"
# Response:
# {
# "totalCredits": 10000,
# "usedCredits": 2500,
# "remainingCredits": 7500
# }
Python Examples
Setup & Configuration
import requests
import time
from typing import Dict, List
API_KEY = "sk_live_your_api_key_here"
BASE_URL = "https://goemailverify.com"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
Single Email Validation
def validate_email(email: str) -> Dict:
"""Validate a single email address."""
response = requests.post(
f"{BASE_URL}/api/validate/single",
headers=headers,
json={"email": email}
)
response.raise_for_status()
return response.json()
# Usage
result = validate_email("test@example.com")
print(f"Status: {result['status']}")
print(f"Score: {result['score']}")
print(f"Reason: {result['reason']}")
Batch Validation
def validate_batch(emails: List[str]) -> List[Dict]:
"""Validate multiple emails (max 100)."""
response = requests.post(
f"{BASE_URL}/api/validate/batch",
headers=headers,
json={"emails": emails}
)
response.raise_for_status()
return response.json()
# Usage
emails = [
"user1@example.com",
"user2@example.com",
"user3@example.com"
]
results = validate_batch(emails)
for result in results:
print(f"{result['email']}: {result['status']}")
CSV Upload with Job Monitoring
def upload_csv(file_path: str) -> str:
"""Upload CSV file and return job ID."""
with open(file_path, 'rb') as f:
files = {'file': f}
response = requests.post(
f"{BASE_URL}/api/jobs/upload",
headers={"Authorization": f"Bearer {API_KEY}"},
files=files
)
response.raise_for_status()
return response.json()['jobId']
def check_job_status(job_id: str) -> Dict:
"""Check job status."""
response = requests.get(
f"{BASE_URL}/api/jobs/{job_id}/status",
headers=headers
)
response.raise_for_status()
return response.json()
def wait_for_completion(job_id: str, poll_interval: int = 5) -> Dict:
"""Wait for job to complete and return final status."""
while True:
status = check_job_status(job_id)
print(f"Status: {status['status']} - Processed: {status.get('processedCount', 0)}/{status.get('totalEmails', 0)}")
if status['status'] == 'COMPLETED':
return status
elif status['status'] == 'FAILED':
raise Exception(f"Job failed: {status.get('errorMessage')}")
time.sleep(poll_interval)
def download_results(job_id: str, output_path: str):
"""Download job results to file."""
response = requests.get(
f"{BASE_URL}/api/jobs/{job_id}/download",
headers=headers,
stream=True
)
response.raise_for_status()
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
# Complete workflow
def process_email_list(input_csv: str, output_csv: str):
"""Complete workflow: upload, wait, download."""
print(f"Uploading {input_csv}...")
job_id = upload_csv(input_csv)
print(f"Job created: {job_id}")
print("Waiting for completion...")
final_status = wait_for_completion(job_id)
print(f"Job completed! Valid: {final_status['validCount']}, Invalid: {final_status['invalidCount']}")
print(f"Downloading results to {output_csv}...")
download_results(job_id, output_csv)
print("Done!")
# Usage
process_email_list("input.csv", "output.csv")
Async Processing with asyncio
import asyncio
import aiohttp
async def validate_email_async(session: aiohttp.ClientSession, email: str) -> Dict:
"""Validate email asynchronously."""
async with session.post(
f"{BASE_URL}/api/validate/single",
headers=headers,
json={"email": email}
) as response:
response.raise_for_status()
return await response.json()
async def validate_many_emails(emails: List[str]) -> List[Dict]:
"""Validate multiple emails concurrently."""
async with aiohttp.ClientSession() as session:
tasks = [validate_email_async(session, email) for email in emails]
return await asyncio.gather(*tasks)
# Usage
emails = ["user1@example.com", "user2@example.com", "user3@example.com"]
results = asyncio.run(validate_many_emails(emails))
for result in results:
print(f"{result['email']}: {result['status']}")
Error Handling & Retry Logic
import time
from requests.exceptions import RequestException
def validate_with_retry(email: str, max_retries: int = 3) -> Dict:
"""Validate email with exponential backoff retry."""
for attempt in range(max_retries):
try:
response = requests.post(
f"{BASE_URL}/api/validate/single",
headers=headers,
json={"email": email},
timeout=30
)
# Handle rate limiting
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 60))
print(f"Rate limited. Waiting {retry_after} seconds...")
time.sleep(retry_after)
continue
response.raise_for_status()
return response.json()
except RequestException as e:
if attempt == max_retries - 1:
raise
# Exponential backoff
wait_time = 2 ** attempt
print(f"Attempt {attempt + 1} failed. Retrying in {wait_time}s...")
time.sleep(wait_time)
# Usage
try:
result = validate_with_retry("test@example.com")
print(f"Success: {result['status']}")
except Exception as e:
print(f"Failed after retries: {e}")
Java Examples
Setup & Configuration
import java.net.http.*;
import java.net.URI;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GoEmailVerifyClient {
private static final String API_KEY = "sk_live_your_api_key_here";
private static final String BASE_URL = "https://goemailverify.com";
private static final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30))
.build();
private static final ObjectMapper mapper = new ObjectMapper();
}
Single Email Validation
public static ValidationResult validateEmail(String email) throws Exception {
String requestBody = String.format("{\"email\":\"%s\"}", email);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/api/validate/single"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse response = client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() != 200) {
throw new RuntimeException("API error: " + response.body());
}
return mapper.readValue(response.body(), ValidationResult.class);
}
// Usage
ValidationResult result = validateEmail("test@example.com");
System.out.println("Status: " + result.getStatus());
System.out.println("Score: " + result.getScore());
CSV Upload & Job Monitoring
import java.nio.file.*;
import java.util.concurrent.TimeUnit;
public static String uploadCsv(Path filePath) throws Exception {
// Note: For multipart upload, use a library like Apache HttpClient
// This is a simplified example
byte[] fileBytes = Files.readAllBytes(filePath);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/api/jobs/upload"))
.header("Authorization", "Bearer " + API_KEY)
.POST(HttpRequest.BodyPublishers.ofByteArray(fileBytes))
.build();
HttpResponse response = client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
Map result = mapper.readValue(
response.body(),
new TypeReference
Async Processing with CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.List;
import java.util.stream.Collectors;
public static CompletableFuture validateEmailAsync(String email) {
String requestBody = String.format("{\"email\":\"%s\"}", email);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/api/validate/single"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
try {
return mapper.readValue(response.body(), ValidationResult.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
public static List validateManyEmails(List emails) {
List> futures = emails.stream()
.map(GoEmailVerifyClient::validateEmailAsync)
.collect(Collectors.toList());
return futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
}
// Usage
List emails = Arrays.asList(
"user1@example.com",
"user2@example.com",
"user3@example.com"
);
List results = validateManyEmails(emails);
results.forEach(r -> System.out.println(r.getEmail() + ": " + r.getStatus()));
JavaScript / Node.js Examples
Setup with Axios
const axios = require('axios');
const API_KEY = 'sk_live_your_api_key_here';
const BASE_URL = 'https://goemailverify.com';
const client = axios.create({
baseURL: BASE_URL,
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
timeout: 30000
});
Single Email Validation
async function validateEmail(email) {
try {
const response = await client.post('/api/validate/single', {
email: email
});
return response.data;
} catch (error) {
console.error('Validation error:', error.message);
throw error;
}
}
// Usage
validateEmail('test@example.com')
.then(result => {
console.log(`Status: ${result.status}`);
console.log(`Score: ${result.score}`);
})
.catch(error => console.error(error));
Batch Validation
async function validateBatch(emails) {
const response = await client.post('/api/validate/batch', {
emails: emails
});
return response.data;
}
// Usage
const emails = [
'user1@example.com',
'user2@example.com',
'user3@example.com'
];
validateBatch(emails)
.then(results => {
results.forEach(r => {
console.log(`${r.email}: ${r.status}`);
});
});
CSV Upload with Monitoring
const fs = require('fs');
const FormData = require('form-data');
async function uploadCsv(filePath) {
const form = new FormData();
form.append('file', fs.createReadStream(filePath));
const response = await client.post('/api/jobs/upload', form, {
headers: form.getHeaders()
});
return response.data.jobId;
}
async function checkJobStatus(jobId) {
const response = await client.get(`/api/jobs/${jobId}/status`);
return response.data;
}
async function waitForCompletion(jobId, pollInterval = 5000) {
while (true) {
const status = await checkJobStatus(jobId);
console.log(`Status: ${status.status} - ${status.processedCount}/${status.totalEmails}`);
if (status.status === 'COMPLETED') {
return status;
} else if (status.status === 'FAILED') {
throw new Error(`Job failed: ${status.errorMessage}`);
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
}
async function downloadResults(jobId, outputPath) {
const response = await client.get(`/api/jobs/${jobId}/download`, {
responseType: 'stream'
});
const writer = fs.createWriteStream(outputPath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
// Complete workflow
async function processEmailList(inputCsv, outputCsv) {
console.log(`Uploading ${inputCsv}...`);
const jobId = await uploadCsv(inputCsv);
console.log(`Job created: ${jobId}`);
console.log('Waiting for completion...');
const finalStatus = await waitForCompletion(jobId);
console.log(`Completed! Valid: ${finalStatus.validCount}, Invalid: ${finalStatus.invalidCount}`);
console.log(`Downloading to ${outputCsv}...`);
await downloadResults(jobId, outputCsv);
console.log('Done!');
}
// Usage
processEmailList('input.csv', 'output.csv')
.catch(error => console.error('Error:', error));
Error Handling & Retry Logic
async function validateWithRetry(email, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.post('/api/validate/single', {
email: email
});
return response.data;
} catch (error) {
// Handle rate limiting
if (error.response?.status === 429) {
const retryAfter = parseInt(error.response.headers['retry-after'] || '60');
console.log(`Rate limited. Waiting ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
continue;
}
// Last attempt - throw error
if (attempt === maxRetries - 1) {
throw error;
}
// Exponential backoff
const waitTime = Math.pow(2, attempt) * 1000;
console.log(`Attempt ${attempt + 1} failed. Retrying in ${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
}
// Usage
validateWithRetry('test@example.com')
.then(result => console.log('Success:', result.status))
.catch(error => console.error('Failed after retries:', error.message));
Complete Workflow Example
Here's a complete real-world example that validates emails during user registration:
Python Flask Example
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
API_KEY = "sk_live_your_api_key_here"
BASE_URL = "https://goemailverify.com"
@app.route('/api/register', methods=['POST'])
def register_user():
data = request.json
email = data.get('email')
# Validate email in real-time
try:
response = requests.post(
f"{BASE_URL}/api/validate/single",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"email": email},
timeout=10
)
result = response.json()
# Only accept VALID emails
if result['status'] != 'VALID':
return jsonify({
'error': 'Invalid email address',
'reason': result['reason']
}), 400
# Check advanced signals
if result.get('humanNameScore') == 'HIGHLY_LIKELY_BOT':
return jsonify({
'error': 'Email validation failed',
'reason': 'Suspicious email pattern detected'
}), 400
# Email is valid - proceed with registration
# ... save user to database ...
return jsonify({
'success': True,
'message': 'Registration successful'
})
except Exception as e:
# Fallback: allow registration but flag for manual review
return jsonify({
'success': True,
'message': 'Registration successful (pending verification)'
})
if __name__ == '__main__':
app.run()
Node.js Express Example
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
const API_KEY = 'sk_live_your_api_key_here';
const BASE_URL = 'https://goemailverify.com';
app.post('/api/register', async (req, res) => {
const { email } = req.body;
try {
// Validate email in real-time
const response = await axios.post(
`${BASE_URL}/api/validate/single`,
{ email },
{
headers: { 'Authorization': `Bearer ${API_KEY}` },
timeout: 10000
}
);
const result = response.data;
// Only accept VALID emails
if (result.status !== 'VALID') {
return res.status(400).json({
error: 'Invalid email address',
reason: result.reason
});
}
// Check advanced signals
if (result.humanNameScore === 'HIGHLY_LIKELY_BOT') {
return res.status(400).json({
error: 'Email validation failed',
reason: 'Suspicious email pattern detected'
});
}
// Email is valid - proceed with registration
// ... save user to database ...
res.json({
success: true,
message: 'Registration successful'
});
} catch (error) {
// Fallback: allow registration but flag for manual review
res.json({
success: true,
message: 'Registration successful (pending verification)'
});
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Ready to Integrate?
Get Your API Key100 free credits • Start integrating in minutes