Using the Truemail gem to validate e-mail addresses
The Truemail gem (not to be confused with truemail.io) allows validating email addresses, e.g. when users enter them into a sign-up form. It runs inside your application and does not depend on an external SaaS service.
Truemail supports different validation "layers":
- Regex validation: if the given address is syntactically valid
- DNS validation (called MX validation): if the given domain exists and can receive email
- SMTP validation: connects to the host received from DNS and starts a test delivery to find out if the recipient mailbox actually exists
tl;dr: We suggest you use DNS validation (
config.default_validation_type = :mx), but set
config.not_rfc_mx_lookup_flow = true.
Validation methods explained
Regex validation (1) is pretty straight-forward and basically "free" since you're not making and network connections.
SMTP validation (3) on the other hand means that Truemail will connect to the target mail server and try to start email delivery. If you do this too often, your app servers might be blocked by them which is not what you want. I suggest you do not use this unless you implement some kind of caching and/or throttling, or unless you validate only rarely.
DNS validation (2) is the middle ground. You will be making DNS requests, but that should never be an issue. Your server's DNS resolver might cache them anyway.
Using DNS validation
However, if no MX record exists for a given domain, many MTAs use a fallback mechanism and will try to connect to machines listed in CNAME and A records, as described in RFC 5321.
This will not help if you want to detect typos like "email@example.com" and do not use SMTP validation. While gmail.de is a valid domain, it can not receive email.
Truemail can be asked to respect only MX records by setting the
not_rfc_mx_lookup_flow configuration option.
Note that this means that you might reject valid email addresses where the domain's DNS records were lacking an MX entry.
I have validated all known emails from a production application with a very "typo-heavy" user base (108k+ emails with 5.2k+ unique domains) and found no false positives. So I suggest you configure Truemail to do exactly that, if you want to avoid users entering invalid email domains:
Truemail.configure do |config| config.verifier_email = 'firstname.lastname@example.org' config.default_validation_type = :mx config.not_rfc_mx_lookup_flow = true end
Note that Truemail has configuration options to set up an allowlist or denylist if you want to allow (or deny) any domains without further checking.