Last active
August 29, 2015 14:07
-
-
Save stevenkaras/600c3ea8377524784602 to your computer and use it in GitHub Desktop.
Email Validation class
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
require 'resolv' | |
require 'net/smtp' | |
class EmailValidator | |
# Note that obsolete syntax support has been stripped | |
Pattern = %r{ | |
# From RFC 5322 s 3.2.1 | |
(?<quoted-pair> \\ [\x21-\x7e \t]){0} | |
# From RFC 5322 s 3.2.3 | |
# NOTE: Omitting CFWS patterns | |
(?<atext> [a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~\u007f-\uffff]){0} | |
(?<atom> \g<atext>+){0} | |
(?<dot-atom-text> \g<atext>+ (?:\. \g<atext>+)*){0} | |
(?<dot-atom> \g<dot-atom-text>){0} | |
(?<specials> [()\[\]<>:;@\\,."]){0} | |
# Derived from RFC 1034 s 3.5 | |
(?<domain> \g<label> (?: \. \g<label>)*){0} | |
(?<label> [a-zA-Z] (?: \g<ldh-str> [a-zA-Z0-9])? ){0} | |
(?<ldh-str> [a-zA-Z0-9\-]*){0} | |
# From RFC 5322 s 3.4.1 | |
(?<addr-spec> \g<local-part> @ \g<domain>){0} | |
(?<local-part> \g<dot-atom>){0} | |
\A \g<addr-spec> \Z | |
}x | |
def email_domain_valid?(domain) | |
Resolv::DNS.open do |dns| | |
return ! dns.getresources(domain, Resolv::DNS::Resource::IN::MX).empty? | |
end | |
end | |
def mailbox_exists?(address, domain) | |
Net::SMTP.start(domain) do |smtp| | |
smtp.rcptto(address) | |
end | |
return true | |
rescue Net::SMTPFatalError | |
return false | |
end | |
def email_valid?(address) | |
match = Pattern.match(address) | |
return unless match | |
email_domain_valid?(match[:domain]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment