Search code examples
ruby-on-railsrubygmailemail-client

check mail address whether is under gmail client <Ruby>


Gmail able to let users to create whatever email style such as [email protected] [email protected] [email protected]

and many more. currently, I'm using this contacts gem which is from https://github.com/liangzan/contacts , but when I login using account like [email protected] cannot get my contacts since the email address not @gmail or @googlemail as I read the code.

So,how do I check the email address whether is under gmail address?


Solution

  • You can check their MX records to see if they are hosted by a googlemail server.

    This method will return true if it finds a googlemail server in the domain's mx records. It uses google's dns server (8.8.8.8)

    require 'resolv'
    
    def isGmailAddress?(address)
      domain = address.split("@").last
      Resolv::DNS.open({:nameserver=>["8.8.8.8"]}) do |r|
        mx = r.getresources(domain,Resolv::DNS::Resource::IN::MX)
        if mx.any? {|server| server.exchange.to_s.include? "googlemail" or server.exchange.to_s.include? "gmail-smtp-in.l.google.com"} then
          return true
        end
        return false
      end
    end
    
    p isGmailAddress?("[email protected]")
    

    look at http://ruby-doc.org/stdlib-1.9.2/libdoc/resolv/rdoc/Resolv.html