Back to blog
Dec 2020·2 min readAI-translated

Validating Email Addresses

#done#integritaet#integrity#php#spam#validation#validieren

One commonly used method (admittedly by me too) to protect yourself from email spam is simply not to enter a valid email address when registering. I have signed up as sapdojapjdspefjfejfos@dfioshdfiosfho.de countless times when I knew no validation mail would be sent, or when I just needed a bit of information quickly without wanting to give out my email address and expose myself to the risk of spam. That's perfectly legitimate - but as site operators we want to have only valid email addresses in our system.

What can we do to ensure that?

Clearly, one common approach is to send out a verification mail. The user has to validate their email address via double opt-in, using a link that is sent to them. Only after validation does the user get access to the desired data. This approach has a significant downside, too: even if the user provides a valid email address, they may not expect to receive a validation mail, and they get annoyed that they have to click yet another link, which they then may not do at all, preferring to go without the information.

What can you do if you want to skip this verification mail but still want some protection against users entering an invalid email address?

Step 1: Validate the email syntax

Email addresses (at least on the internet, for communication via the usual mail servers over SMTP) follow the pattern localpart@domainpart.tld for example my-fancy-mailaddress@devdave.de

To get at least rudimentary protection here, the email address can be validated via

if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
  echo "Email address valid";
}

Inputs like

  • asdadasd
  • asddasd@asdasd
  • .asd§@dfsdf

are already filtered out this way.

Step 2: Validate the MX record

This is what this article is really about. The MX record (Mail Exchange Resource Record) states under which FQDN (fully qualified domain name) the mail server can be reached. My MX record, for example, points to the Uberspace mail server, because I process and, if needed, forward my mail via Uberspace. If no MX record is stored for a domain, or the domain simply can't be found, the recipient can't receive any email via that domain either (sounds logical, and it is). How do we check this?

$valid = checkdnsrr($email_address, "MX");
echo "Email address " . ($valid ? "" : "in") . "valid";

If checkdnsrr (short for Check DNS Resource Record) doesn't find a valid MX record, the email address is invalid and should be requested again.

Don't feel like spam, but still want to receive mail? Ever thought about temporary email addresses?

NewerThe Null-Conditional OperatorOlderReturning MySQL NULL as 0