Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DE-1307 Make v4 validation a default one #326

Merged
merged 4 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,17 +165,12 @@ import (
"github.com/mailgun/mailgun-go/v4"
)

// If your plan does not include email validations but you have an account,
// use your Public Validation api key. If your plan does include email validations,
// use your Private API key. You can find both the Private and
// Public Validation API Keys in your Account Menu, under "Settings":
// (https://app.mailgun.com/app/account/security)
// Your plan should include email validations.
// Use your Mailgun API key. You can find the Mailgun API keys in your Account Menu, under "Settings":
// (https://app.mailgun.com/settings/api_security)
var apiKey string = "your-api-key"

func main() {
// To use the /v4 version of validations define MG_URL in the environment
// as `https://api.mailgun.net/v4` or set `v.SetAPIBase("https://api.mailgun.net/v4")`

// Create an instance of the Validator
v := mailgun.NewEmailValidator(apiKey)

Expand Down
47 changes: 21 additions & 26 deletions email_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ type EmailVerification struct {
Result string `json:"result"`
// Engagement results are a macro-level view that explain an email recipient’s propensity to engage.
// https://documentation.mailgun.com/docs/inboxready/mailgun-validate/validate_engagement/
//
// Only for v4. To use the /v4 version of validations define MG_URL in the environment variable
// as `https://api.mailgun.net/v4` or set `v.SetAPIBase("https://api.mailgun.net/v4")`
Engagement *EngagementData `json:"engagement,omitempty"`
}

Expand Down Expand Up @@ -93,9 +90,11 @@ type EmailValidatorImpl struct {
apiKey string
}

// Creates a new validation instance.
// * If a public key is provided, uses the public validation endpoints
// * If a private key is provided, uses the private validation endpoints
// NewEmailValidator creates a new validation instance.
//
// * For ValidateEmail use private key
//
// * For ParseAddresses use public key
func NewEmailValidator(apiKey string) *EmailValidatorImpl {
isPublicKey := false

Expand All @@ -105,16 +104,19 @@ func NewEmailValidator(apiKey string) *EmailValidatorImpl {
}

return &EmailValidatorImpl{
// TODO(vtopc): Don’t use http.DefaultClient - https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779
client: http.DefaultClient,
isPublicKey: isPublicKey,
apiBase: APIBase,
apiBase: "https://api.mailgun.net/v4",
apiKey: apiKey,
}
}

// NewEmailValidatorFromEnv returns a new EmailValidator using environment variables
// If MG_PUBLIC_API_KEY is set, assume using the free validation subject to daily usage limits
// If only MG_API_KEY is set, assume using the /private validation routes with no daily usage limits
//
// * For ValidateEmail set MG_API_KEY
//
// * For ParseAddresses set MG_PUBLIC_API_KEY
func NewEmailValidatorFromEnv() (*EmailValidatorImpl, error) {
apiKey := os.Getenv("MG_PUBLIC_API_KEY")
if apiKey == "" {
Expand Down Expand Up @@ -167,27 +169,15 @@ func (m *EmailValidatorImpl) getAddressURL(endpoint string) string {
// ValidateEmail performs various checks on the email address provided to ensure it's correctly formatted.
// It may also be used to break an email address into its sub-components. If user has set the
func (m *EmailValidatorImpl) ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error) {
if strings.HasSuffix(m.APIBase(), "/v4") {
return m.validateV4(ctx, email, mailBoxVerify)
if m.isPublicKey {
return EmailVerification{}, errors.New("ValidateEmail: public key is not supported anymore, use private key")
}
return m.validateV3(ctx, email, mailBoxVerify)
}

func (m *EmailValidatorImpl) validateV3(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error) {
r := newHTTPRequest(m.getAddressURL("validate"))
r.setClient(m.Client())
r.addParameter("address", email)
if mailBoxVerify {
r.addParameter("mailbox_verification", "true")
if strings.HasSuffix(m.APIBase(), "/v4") {
return m.validateV4(ctx, email, mailBoxVerify)
}
r.setBasicAuth(basicAuthUser, m.APIKey())

var res EmailVerification
err := getResponseFromJSON(ctx, r, &res)
if err != nil {
return EmailVerification{}, err
}
return res, nil
return EmailVerification{}, errors.New("ValidateEmail: v3 is not supported anymore, use v4")
}

func (m *EmailValidatorImpl) validateV4(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error) {
Expand Down Expand Up @@ -221,6 +211,11 @@ func (m *EmailValidatorImpl) validateV4(ctx context.Context, email string, mailB

// ParseAddresses takes a list of addresses and sorts them into valid and invalid address categories.
// NOTE: Use of this function requires a proper public API key. The private API key will not work.
//
// NOTE: Only for v3. To use the /v3 version of validations define MG_URL in the environment variable
// as `https://api.mailgun.net/v3` or set `v.SetAPIBase("https://api.mailgun.net/v3")`
//
// Deprecated: /v3/address/parse is deprecated use ValidateEmail instead.
func (m *EmailValidatorImpl) ParseAddresses(ctx context.Context, addresses ...string) ([]string, []string, error) {
r := newHTTPRequest(m.getAddressURL("parse"))
r.setClient(m.Client())
Expand Down
21 changes: 0 additions & 21 deletions email_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,6 @@ import (
"github.com/mailgun/mailgun-go/v4"
)

func TestEmailValidationV3(t *testing.T) {
v := mailgun.NewEmailValidator(testKey)
// API Base is set to `http://server/v3`
v.SetAPIBase(server.URL())
ctx := context.Background()

ev, err := v.ValidateEmail(ctx, "[email protected]", false)
ensure.Nil(t, err)

ensure.True(t, ev.IsValid)
ensure.DeepEqual(t, ev.MailboxVerification, "")
ensure.False(t, ev.IsDisposableAddress)
ensure.False(t, ev.IsRoleAddress)
ensure.True(t, ev.Parts.DisplayName == "")
ensure.DeepEqual(t, ev.Parts.LocalPart, "foo")
ensure.DeepEqual(t, ev.Parts.Domain, "mailgun.com")
ensure.DeepEqual(t, ev.Reason, "no-reason")
ensure.True(t, len(ev.Reasons) == 0)
ensure.DeepEqual(t, ev.Risk, "unknown")
}

func TestEmailValidationV4(t *testing.T) {
v := mailgun.NewEmailValidator(testKey)
// API Base is set to `http://server/v4`
Expand Down
Loading