Update: I just found a valid_email2 stone that looks very good.
Do not use regex to validate email addresses. It is a trap. There are many more valid email address formats than you think. Anyway! Gem mail (it is required by ActionMailer, so you have one) will analyze email addresses - with the right parser - for you:
require 'mail' a = Mail::Address.new(' foo@example.com ')
This will Mail::Field::ParseError if it doesn't match the email address. (We don’t do things like MX address lookups or something like that.)
If you need good experience with the Rails validator, you can do app/models/concerns/email_validatable.rb :
require 'mail' module EmailValidatable extend ActiveSupport::Concern class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) begin a = Mail::Address.new(value) rescue Mail::Field::ParseError record.errors[attribute] << (options[:message] || "is not an email") end end end end
and then in your model you can:
include EmailValidatable validates :email, email: true
As Ivo Dzechcharov’s commentary below mentions, he passes everything through which the valid “To:” address passes. So something like Foo Bar < foo.bar@example.com > valid. It may be a problem for you; it cannot be; In the end, this is indeed the correct address.
If you only need the address part:
a = Mail::Address.new('Foo Bar < foobar@example.com >') a.address => " foobar@example.com "
As Bjorn Weinbrenne notes below, there are more valid RFC2822 addresses than you might expect (I’m pretty sure that all of the listed addresses meet the requirements and can receive mail depending on the system configuration) - that’s why I don’t recommend trying regular expressions, but I use compatible parser.
If it really matters to you whether you can send an email to the address, then it is best - in fact - to send a message with a confirmation link.