Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

email_address

> 编程语言
Open source

The EmailAddress Gem to work with and validate email addresses.

339 stars0 likes1 views
WebsiteGitHub

About

The EmailAddress Gem to work with and validate email addresses.

Email Address

The email_address ruby gem is an opinionated validation library for email addresses. The RFC 5322 address specification defines them as extensions to the email header syntax, not as a useful method for creating email transport systems with user accounts, mailboxes, and routing.

The library follows "real world" email address patterns for end-user addresses.

  • "Conventional" format (the default) fits most user email accounts as created by major email service providers and software. Only 7-bit ASCII characters are supported in the local (left) part.
  • "Relaxed" format loosely follows conventional, allowing a looser punctuation format.
  • "Standard" format follows the RFC. This is provided for non-user addresses, such as uniquely-generated destinations for consumption between automated systems.

RFC "Standard" Addresses allow syntaxes that most developers do not want:

  • Mailboxes are case-sensitive.
  • Double-quoted tokens can contain spaces, "@" symbols, and unusual punctuation.
  • Parenthetical comment fields can appear at the beginning or end of the local (left) part.
  • Addresses do not have to have fully-qualified domain names
  • The Host part (after the "@") can be an IP Address

Additionally, this library respects "address tags", a convention not specified by the RFC, with which email providers and software append an identifier or route to the mailbox, usually after a "+" symbol.

Configuration options include specialized address formats for the largest ESP (Email service providers) to validate against their formats.

If you have false negatives with "conventional" format, try the local_format: :relaxed option. To validate to the RFC only, use the local_format: :standard option. When possible, confirm the address with the user if conventional check fails but relaxed succeeds.

Remember: the only true way to validate an email address is to successfully send email to it. SMTP checks can help, but should only be done politely to avoid blacklisting your application. Several (unaffiliated) services exist to do this for you.

Finally, there are conveniences to handle storage and management of address digests for PII removal or sharing addresses without revealing them.

The gem requires ruby only, but includes a, optional Ruby on Rails helper for those who need to use it with ActiveRecord.

Looking for a Javascript version of this library? Check out the email_address npm module.

Quick Start

Install the gem to your project with bundler:

bundle add email_address

or with the gem command:

To quickly validate email addresses, use the valid? and error helpers. valid? returns a boolean, and error returns nil if valid, otherwise a basic error message.

ruby
EmailAddress.valid? "[email protected]" #=> true
EmailAddress.error "[email protected]" #=> "Invalid Host/Domain Name"

EmailAddress deeply validates your email addresses. It checks:

  • Host name format and DNS setup
  • Mailbox format according to "conventional" form. This matches most used user email accounts, but is a subset of the RFC specification.

It does not check:

  • The mail server is configured to accept connections
  • The mailbox is valid and accepts email.

By default, MX records are required in DNS. MX or "mail exchanger" records tell where to deliver email for the domain. Many domains run their website on one provider (ISP, Heroku, etc.), and email on a different provider (such as G Suite). Note that example.com, while a valid domain name, does not have MX records.

ruby
EmailAddress.valid? "[email protected]" #=> false
EmailAddress.valid? "[email protected]", host_validation: :syntax #=> true

Most mail servers do not yet support Unicode mailboxes, so the default here is ASCII.

ruby
EmailAddress.error "Pelé@google.com" #=> "Invalid Recipient/Mailbox"
EmailAddress.valid? "Pelé@google.com", local_encoding: :unicode #=> true

Background

The email address specification is complex and often not what you want when working with personal email addresses in applications. This library introduces terms to distinguish types of email addresses.

  • Normal - The edited form of any input email address. Typically, it is lower-cased and minor "fixes" can be performed, depending on the configurations and email address provider.

    =>

  • Conventional - Most personal account addresses are in this basic format, one or more "words" separated by a single simple punctuation character. It consists of a mailbox (user name or role account) and an optional address "tag" assigned by the user.

    miles.o'

  • Relaxed - A less strict form of Conventional, same character set, must begin and end with an alpha-numeric character, but order within is not enforced.

  • Standard - The RFC-Compliant syntax of an email address. This is useful when working with software-generated addresses or handling existing email addresses, but otherwise not useful for personal addresses.

    madness!."()<>[]:,;@\"!#$%&'*+-/=?^_`{}| ~.a(comment )"@example.org

  • Base - A unique mailbox without tags. For gmail, is uses the incoming punctation, essential when building an MD5, SHA1, or SHA256 to match services like Gravatar, and email address digest interchange.

  • Canonical - An unique account address, lower-cased, without the tag, and with irrelevant characters stripped.

    =>

  • Reference - The MD5 of the Base format, used to share account references without exposing the private email address directly.

    => => 1429a1dfc797d6e93075fef011c373fb

  • Redacted - A form of the email address where it is replaced by a SHA1-based version to remove the original address from the database, or to store the address privately, yet still keep it accessible at query time by converting the queried address to the redacted form.

    => {bea3f3560a757f8142d38d212a931237b218eb5e}@gmail.com

  • Munged - An obfuscated version of the email address suitable for publishing on the internet, where email address harvesting could occur.

    => cl*****@gm*****

Other terms:

  • Local - The left-hand side of the "@", representing the user, mailbox, or role, and an optional "tag".

    ; Local part: mailbox+tag

  • Mailbox - The destination user account or role account.

  • Tag - A parameter added after the mailbox, usually after the "+" symbol, set by the user for mail filtering and sub-accounts. Not all mail systems support this.

  • Host (sometimes called Domain) - The right-hand side of the "@" indicating the domain or host name server to delivery the email. If missing, "localhost" is assumed, or if not a fully-qualified domain name, it assumed another computer on the same network, but this is increasingly rare.

  • Provider - The Email Service Provider (ESP) providing the email service. Each provider may have its own email address validation and canonicalization rules.

  • Punycode - A host name with Unicode characters (International Domain Name or IDN) needs conversion to this ASCII-encoded format for DNS lookup.

    "HIRO@こんにちは世界.com" => ""

Wikipedia has a great article on Email Addresses, much more readable than the section within RFC 5322

Usage

Use EmailAddress to do transformations and validations. You can also instantiate an object to inspect the address.

These top-level helpers return edited email addresses and validation check.

ruby
address = "[email protected]"
EmailAddress.valid?(address)    #=> true
EmailAddress.normal(address)    #=> "clark.kent+scoops@gmail.com"
EmailAddress.canonical(address) #=> "clarkkent@gmail.com"
EmailAddress.reference(address) #=> "c5be3597c391169a5ad2870f9ca51901"
EmailAddress.redact(address)    #=> "{bea3f3560a757f8142d38d212a931237b218eb5e}@gmail.com"
EmailAddress.munge(address)     #=> "cl*****@gm*****"
EmailAddress.matches?(address, 'google') #=> 'google' (true)
EmailAddress.error("#[email protected]") #=> "Invalid Mailbox"

Or you can create an instance of the email address to work with it.

ruby
email = EmailAddress.new(address) #=> #
email.normal        #=> "clark.kent+scoops@gmail.com"
email.canonical     #=> "clarkkent@gmail.com"
email.original      #=> "Clark.Kent+scoops@gmail.com"
email.valid?        #=> true

Here are some other methods that are available.

…

ruby class User "[email protected]" user.canonical_email #=> "[email protected]" User.find_by_email("[email protected]") #=> #

…

ruby e1 = EmailAddress.new("[email protected]") e2 = EmailAddress.new("[email protected]") e3 = EmailAddress.new(e2.redact) e1.to_s #=> "[email protected]" e2.to_s #=> "[email protected]" e3.to_s #=> "{bea3f3560a757f8142d38d212a931237b218eb5e}@gmail.com"

e1 == e2 #=> false (Matches by normalized address) e1.same_as?(e2) #=> true (Matches as canonical address) e1.same_as?(e3) #=> true (Matches as redacted address) e1 true (Compares using normalized address)


#### Matching

Matching addresses by simple patterns:

- Top-Level-Domain: .org
- Domain Name: example.com
- Registration Name: hotmail. (matches any TLD)
- Domain Glob: \*.exampl?.com
- Provider Name: google
- Mailbox Name or Glob: user00\*@
- Address or Glob: postmaster@domain\*.com
- Provider or Registration: msn

Usage:

```ruby
e = EmailAddress.new("[email protected]")
e.matches?("gmail.com") #=> true
e.matches?("google")    #=> true
e.matches?(".org")      #=> false
e.matches?("g*com")     #=> true
e.matches?("gmail.")    #=> true
e.matches?("*kent*@")   #=> true

Configuration

You can pass an options hash on the .new() and helper class methods to control how the library treats that address. These can also be configured during initialization by provider and default (see below).

ruby
EmailAddress.new("[email protected]",
                 host_validation: :syntax, host_encoding: :unicode)

Globally, you can change and query configuration options:

ruby
EmailAddress::Config.setting(:host_validation, :mx)
EmailAddress::Config.setting(:host_validation) #=> :mx

Or set multiple settings at once:

ruby
EmailAddress::Config.configure(local_downcase: false, host_validation: :syntax)

You can add special rules by domain or provider. It takes the options above and adds the :domain_match and :exchanger_match rules.

ruby
EmailAddress.define_provider('google',
  domain_match:      %w(gmail.com googlemail.com),
  exchanger_match:   %w(google.com), # Requires host_validation==:mx
  local_size:        5..64,
  mailbox_canonical: ->(m) {m.gsub('.','')})

…

ruby
# ./config/initializers/email_address.rb
EmailAddress::Config.setting( :local_format, :relaxed )
EmailAddress::Config.configure( local_format: :relaxed, ... )
EmailAddress::Config.provider(:github,
       host_match: %w(github.com), local_format: :standard)

Override Error Messaegs

You can override the default error messages as follows:

ruby
EmailAddress::Config.error_messages({
  invalid_address:    "Invalid Email Address",
  invalid_mailbox:    "Invalid Recipient/Mailbox",
  invalid_host:       "Invalid Host/Domain Name",
  exceeds_size:       "Address too long",
  not_allowed:        "Address is not allowed",
  incomplete_domain:  "Domain name is incomplete"}, 'en')

Complete settings and methods are found in the config.rb file within.

Notes

Internationalization

The industry is moving to support Unicode characters in the local part of the email address. Currently, SMTP supports only 7-bit ASCII, but a new SMTPUTF8 standard is available, but not yet widely implemented. To work properly, global Email systems must be converted to UTF-8 encoded d

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyemail-addressemail-validationparserruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言