Created
          October 10, 2020 12:21 
        
      - 
      
- 
        Save michaelDpierce/58f8bffc7aad7da98288f70de1345fa1 to your computer and use it in GitHub Desktop. 
    Email Validation with Abstract API for Ruby on Rails
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | class EmailValidationService | |
| require 'ostruct' | |
| require 'rest-client' | |
| require 'json' | |
| attr_reader :error | |
| # @param[Integer] project_id | |
| # @param[String] email | |
| def initialize(project_id, email) | |
| @project_id = project_id | |
| @email = email | |
| self | |
| end | |
| def process | |
| if is_valid_email? @email | |
| verify_email() | |
| else | |
| @error = "Email not valid" | |
| return false | |
| end | |
| end | |
| private | |
| def is_valid_email? email | |
| email =~ URI::MailTo::EMAIL_REGEXP | |
| end | |
| def verify_email | |
| uri = URI( | |
| "https://emailvalidation.abstractapi.com/v1/?"\ | |
| "api_key=#{ENV['ABSTRACT_API_KEY']}&"\ | |
| "email=#{@email}" | |
| ) | |
| response = | |
| RestClient.get( | |
| 'https://emailvalidation.abstractapi.com/v1', | |
| { | |
| params: { api_key: ENV['ABSTRACT_API_KEY'], email: @email } | |
| } | |
| ) | |
| data = JSON.parse(response.body, object_class: OpenStruct) | |
| return { | |
| value: @email, | |
| autocorrect: data.autocorrect, | |
| is_valid_format: data.is_valid_format.value, | |
| is_free_email: data.is_free_email.value, | |
| is_disposable_email: data.is_disposable_email.value, | |
| is_role_email: data.is_role_email.value, | |
| is_catchall_email: data.is_catchall_email.value, | |
| is_mx_found: data.is_mx_found.value, | |
| is_smtp_valid: data.is_smtp_valid.value, | |
| quality_score: data.quality_score, | |
| project_id: @project_id | |
| } | |
| rescue StandardError => error | |
| @error = error | |
| return false | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment