Phase 2 part 5: find people and verify emails with Hunter.io
Review gets Find people (Domain Search by the departments, seniority and count set in Settings → Lead sources), Find their email (Email Finder for a named person at a company), and Verify (one, or every unchecked address in New). Every call is kept in enrich_runs (schema 9) with its result and credits, and shown on the card. Nothing runs on a schedule. Sources are shown by name (Hunter.io, origami.chat, explee.com). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
// Package hunter finds and verifies work email addresses through Hunter.io's
|
||||
// API (https://hunter.io/api-documentation/v2). Searches and verifications
|
||||
// use the account's credits; the account call is free.
|
||||
package hunter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const apiBase = "https://api.hunter.io/v2"
|
||||
|
||||
var (
|
||||
// ErrUnauthorized means the key was refused.
|
||||
ErrUnauthorized = errors.New("Hunter.io refused the API key")
|
||||
// ErrNoCredits means the plan's searches or verifications are used up.
|
||||
ErrNoCredits = errors.New("Hunter.io says this month's credits are used up (HTTP 429)")
|
||||
// ErrRateLimited means too many calls too quickly.
|
||||
ErrRateLimited = errors.New("Hunter.io's rate limit was reached; try again in a minute")
|
||||
)
|
||||
|
||||
// Client calls the API with one key.
|
||||
type Client struct {
|
||||
key, base string
|
||||
http *http.Client
|
||||
// Pause between polls of a verification that's still running.
|
||||
poll time.Duration
|
||||
}
|
||||
|
||||
func New(key string) *Client {
|
||||
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: 40 * time.Second}, poll: 5 * time.Second}
|
||||
}
|
||||
|
||||
// WithBase points the client at another server (for tests), and polls
|
||||
// without waiting.
|
||||
func (c *Client) WithBase(u string) *Client {
|
||||
c.base = strings.TrimRight(u, "/")
|
||||
c.poll = time.Millisecond
|
||||
return c
|
||||
}
|
||||
|
||||
// get calls path and decodes the response's "data" into out. It returns
|
||||
// the credits the call used (the X-Credits-Used header) and the status.
|
||||
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) (credits float64, status int, err error) {
|
||||
u := c.base + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
req.Header.Set("X-API-KEY", c.key)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
|
||||
if err != nil {
|
||||
return 0, res.StatusCode, err
|
||||
}
|
||||
credits, _ = strconv.ParseFloat(res.Header.Get("X-Credits-Used"), 64)
|
||||
switch res.StatusCode {
|
||||
case http.StatusOK, http.StatusAccepted:
|
||||
case http.StatusUnauthorized:
|
||||
return 0, res.StatusCode, ErrUnauthorized
|
||||
case http.StatusTooManyRequests:
|
||||
return 0, res.StatusCode, ErrNoCredits
|
||||
case http.StatusForbidden:
|
||||
return 0, res.StatusCode, ErrRateLimited
|
||||
default:
|
||||
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: HTTP %d: %s", path, res.StatusCode, errorDetail(raw))
|
||||
}
|
||||
if res.StatusCode == http.StatusAccepted {
|
||||
return credits, res.StatusCode, nil
|
||||
}
|
||||
var env struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return credits, res.StatusCode, fmt.Errorf("Hunter.io %s: %w", path, err)
|
||||
}
|
||||
if len(env.Data) == 0 || string(env.Data) == "null" {
|
||||
return credits, res.StatusCode, nil
|
||||
}
|
||||
return credits, res.StatusCode, json.Unmarshal(env.Data, out)
|
||||
}
|
||||
|
||||
// errorDetail is the first error's details, or the start of the body.
|
||||
func errorDetail(raw []byte) string {
|
||||
var e struct {
|
||||
Errors []struct {
|
||||
ID string `json:"id"`
|
||||
Details string `json:"details"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if json.Unmarshal(raw, &e) == nil && len(e.Errors) > 0 {
|
||||
if e.Errors[0].Details != "" {
|
||||
return e.Errors[0].Details
|
||||
}
|
||||
return e.Errors[0].ID
|
||||
}
|
||||
return strings.TrimSpace(string(raw[:min(len(raw), 300)]))
|
||||
}
|
||||
|
||||
// Quota is what's left of one kind of request this period.
|
||||
type Quota struct {
|
||||
Used float64 `json:"used"`
|
||||
Available float64 `json:"available"`
|
||||
Remaining float64 `json:"remaining"`
|
||||
}
|
||||
|
||||
// Account is the key owner's plan and what's left of it.
|
||||
type Account struct {
|
||||
Email string `json:"email"`
|
||||
PlanName string `json:"plan_name"`
|
||||
ResetDate string `json:"reset_date"`
|
||||
Requests struct {
|
||||
Credits *Quota `json:"credits"` // only on single-pool plans
|
||||
Searches Quota `json:"searches"`
|
||||
Verifications Quota `json:"verifications"`
|
||||
} `json:"requests"`
|
||||
}
|
||||
|
||||
// Left describes what's left, for the settings page.
|
||||
func (a *Account) Left() string {
|
||||
if q := a.Requests.Credits; q != nil {
|
||||
return fmt.Sprintf("%s of %s credits left", num(q.Remaining), num(q.Available))
|
||||
}
|
||||
return fmt.Sprintf("%s of %s searches and %s of %s verifications left",
|
||||
num(a.Requests.Searches.Remaining), num(a.Requests.Searches.Available),
|
||||
num(a.Requests.Verifications.Remaining), num(a.Requests.Verifications.Available))
|
||||
}
|
||||
|
||||
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
|
||||
|
||||
// Account checks the key. It costs nothing.
|
||||
func (c *Client) Account(ctx context.Context) (*Account, error) {
|
||||
var a Account
|
||||
if _, _, err := c.get(ctx, "/account", nil, &a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// Verification is Hunter's last check of an address.
|
||||
type Verification struct {
|
||||
Date string `json:"date"`
|
||||
Status string `json:"status"` // valid, accept_all, unknown (invalid ones aren't returned)
|
||||
}
|
||||
|
||||
// Email is a person Domain Search found.
|
||||
type Email struct {
|
||||
Value string `json:"value"`
|
||||
Type string `json:"type"` // personal or generic
|
||||
Confidence int `json:"confidence"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Position string `json:"position"`
|
||||
Seniority string `json:"seniority"`
|
||||
Department string `json:"department"`
|
||||
DecisionMaker bool `json:"decision_maker"`
|
||||
LinkedIn string `json:"linkedin"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Verification Verification `json:"verification"`
|
||||
}
|
||||
|
||||
// DomainQuery says whom to look for at a domain.
|
||||
type DomainQuery struct {
|
||||
Domain string
|
||||
Limit int // 1 to 100; on the free plan at most 10
|
||||
Seniority []string // junior, senior, executive
|
||||
Departments []string // executive, it, finance, management, sales, …
|
||||
}
|
||||
|
||||
// DomainResult is what Domain Search found.
|
||||
type DomainResult struct {
|
||||
Organization string `json:"organization"`
|
||||
Pattern string `json:"pattern"`
|
||||
AcceptAll bool `json:"accept_all"`
|
||||
Emails []Email `json:"emails"`
|
||||
Credits float64 `json:"-"`
|
||||
}
|
||||
|
||||
// DomainSearch finds people with personal addresses at a domain. It costs a
|
||||
// search when anything is found.
|
||||
func (c *Client) DomainSearch(ctx context.Context, q DomainQuery) (*DomainResult, error) {
|
||||
v := url.Values{"domain": {q.Domain}, "type": {"personal"}}
|
||||
if q.Limit > 0 {
|
||||
v.Set("limit", strconv.Itoa(q.Limit))
|
||||
}
|
||||
if len(q.Seniority) > 0 {
|
||||
v.Set("seniority", strings.Join(q.Seniority, ","))
|
||||
}
|
||||
if len(q.Departments) > 0 {
|
||||
v.Set("department", strings.Join(q.Departments, ","))
|
||||
}
|
||||
var out DomainResult
|
||||
credits, _, err := c.get(ctx, "/domain-search", v, &out)
|
||||
out.Credits = credits
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// Found is the address Email Finder found for a person.
|
||||
type Found struct {
|
||||
Email string `json:"email"`
|
||||
Score int `json:"score"`
|
||||
Position string `json:"position"`
|
||||
LinkedInURL string `json:"linkedin_url"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Verification Verification `json:"verification"`
|
||||
Credits float64 `json:"-"`
|
||||
}
|
||||
|
||||
// FindEmail looks for a person's address at a domain. It costs a search
|
||||
// only when an address is found; Email is "" otherwise.
|
||||
func (c *Client) FindEmail(ctx context.Context, domain, first, last string) (*Found, error) {
|
||||
v := url.Values{"domain": {domain}}
|
||||
if first != "" && last != "" {
|
||||
v.Set("first_name", first)
|
||||
v.Set("last_name", last)
|
||||
} else {
|
||||
v.Set("full_name", strings.TrimSpace(first+" "+last))
|
||||
}
|
||||
var out Found
|
||||
credits, _, err := c.get(ctx, "/email-finder", v, &out)
|
||||
out.Credits = credits
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// Checked is the result of verifying an address.
|
||||
type Checked struct {
|
||||
Status string `json:"status"` // valid, invalid, accept_all, webmail, disposable, unknown
|
||||
Score int `json:"score"`
|
||||
Credits float64 `json:"-"`
|
||||
}
|
||||
|
||||
// Verify checks whether an address receives mail. Hunter answers 202 while
|
||||
// a check runs (up to about 20 seconds); Verify asks again until it's done,
|
||||
// which is counted once.
|
||||
func (c *Client) Verify(ctx context.Context, email string) (*Checked, error) {
|
||||
var out Checked
|
||||
for attempt := 0; ; attempt++ {
|
||||
credits, status, err := c.get(ctx, "/email-verifier", url.Values{"email": {email}}, &out)
|
||||
out.Credits += credits
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if status != http.StatusAccepted {
|
||||
return &out, nil
|
||||
}
|
||||
if attempt >= 6 {
|
||||
return nil, errors.New("Hunter.io is still checking " + email + "; try again later")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(c.poll):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package hunter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClient(t *testing.T) {
|
||||
verifyCalls := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-KEY") != "k" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"errors":[{"id":"authentication_failed","code":401,"details":"No user found"}]}`))
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
switch r.URL.Path {
|
||||
case "/account":
|
||||
w.Write([]byte(`{"data":{"email":"pat@example.com","plan_name":"Free","reset_date":"2026-12-01",
|
||||
"requests":{"searches":{"used":3,"available":25,"remaining":22},"verifications":{"used":1,"available":50,"remaining":49}}}}`))
|
||||
case "/domain-search":
|
||||
if q.Get("domain") != "acme.example" || q.Get("type") != "personal" || q.Get("limit") != "5" ||
|
||||
q.Get("seniority") != "executive,senior" || q.Get("department") != "it" {
|
||||
t.Errorf("domain search query: %v", q)
|
||||
}
|
||||
w.Header().Set("X-Credits-Used", "1")
|
||||
w.Write([]byte(`{"data":{"organization":"Acme","pattern":"{first}","emails":[{"value":"pat@acme.example","type":"personal",
|
||||
"confidence":94,"first_name":"Pat","last_name":"Lee","position":"CTO","department":"it",
|
||||
"verification":{"date":"2026-11-01","status":"valid"}}]},"meta":{"results":1}}`))
|
||||
case "/email-finder":
|
||||
if q.Get("first_name") != "Ann" || q.Get("last_name") != "Ray" {
|
||||
t.Errorf("finder query: %v", q)
|
||||
}
|
||||
w.Write([]byte(`{"data":{"email":null,"score":null}}`))
|
||||
case "/email-verifier":
|
||||
verifyCalls++
|
||||
if verifyCalls == 1 {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Credits-Used", "0.5")
|
||||
w.Write([]byte(`{"data":{"status":"accept_all","score":70,"email":"pat@acme.example"}}`))
|
||||
case "/quota":
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte(`{"errors":[{"id":"not_found","code":404,"details":"Nothing here"}]}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
ctx := context.Background()
|
||||
c := New("k").WithBase(srv.URL)
|
||||
|
||||
a, err := c.Account(ctx)
|
||||
if err != nil || a.PlanName != "Free" || a.Left() != "22 of 25 searches and 49 of 50 verifications left" {
|
||||
t.Fatalf("account: %+v %v", a, err)
|
||||
}
|
||||
res, err := c.DomainSearch(ctx, DomainQuery{Domain: "acme.example", Limit: 5, Seniority: []string{"executive", "senior"}, Departments: []string{"it"}})
|
||||
if err != nil || len(res.Emails) != 1 || res.Credits != 1 || res.Emails[0].Verification.Status != "valid" || res.Emails[0].Position != "CTO" {
|
||||
t.Fatalf("domain search: %+v %v", res, err)
|
||||
}
|
||||
f, err := c.FindEmail(ctx, "acme.example", "Ann", "Ray")
|
||||
if err != nil || f.Email != "" {
|
||||
t.Fatalf("finder: %+v %v", f, err)
|
||||
}
|
||||
v, err := c.Verify(ctx, "pat@acme.example")
|
||||
if err != nil || v.Status != "accept_all" || v.Credits != 0.5 || verifyCalls != 2 {
|
||||
t.Fatalf("verify: %+v %v (%d calls)", v, err, verifyCalls)
|
||||
}
|
||||
if _, _, err := c.get(ctx, "/quota", nil, &struct{}{}); !errors.Is(err, ErrNoCredits) {
|
||||
t.Errorf("quota: %v", err)
|
||||
}
|
||||
if _, _, err := c.get(ctx, "/nope", nil, &struct{}{}); err == nil || err.Error() != "Hunter.io /nope: HTTP 404: Nothing here" {
|
||||
t.Errorf("404: %v", err)
|
||||
}
|
||||
if _, err := New("bad").WithBase(srv.URL).Account(ctx); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Errorf("bad key: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user