Question

I'm using PHP's SwiftMailer library to bulk send emails (following CANSPAM and RFCs).

Everything works fine until I run across a domain that does not have a corresponding MX entry in the DNS. At that point, my script just hangs -- I'm assuming it's because sendmail hasn't returned. This can last just a few minutes, or it can last many hours.

I have confirmed that the addresses my script (slash sendmail) hang on are those without a DNS MX entry. Everything else sends fine.

Is there a way I can check if the DNS MX exists inside of PHP before I attempt to send the message? Is this scalable (i.e., will that extra lookup on the DNS really slow me down, or will it be fine b/c then the MX is cached locally for sendmail to use in delivering the message)?

Thanks for your help

--- UPDATE --- I tried the solutions below, which helped me narrow down what the problem is. It seems it's not a question of whether or not the MX entry exists. The problem is that the DNS lookup is taking forever to return. Is there a simple way I can set the timeout, so if DNS doesn't return in < 5s, I can move on?

Was it helpful?

Solution

getmxrr(substr($email,strrpos($email,'@')+1),$hosts);
if (!$hosts)
    echo 'No MX record found';

You can also try this to prevent blocking (there are no options for adjusting getmxrr timeout):

if (!@fsockopen(substr($email,strrpos($email,'@')+1),25,$errno,$errstr,5))
    echo 'No MX record found';

OTHER TIPS

You can use getmxrr:

if (getmxrr($hostname, $mxhosts)) {
   // MX record exists
   var_dump($mxhosts);
}

DNS lookups scale well on repeated requests. The nearest DNS server will cache the looked up values for a period. Using a local DNS cache server can improve performance, but will use more memory (a little or a lot depending on the software and number of addresses cached.

If I remember the RFCs correctly, hosts with an A record should be valid email destinations as well. However, domains with only an A record may not have a mail server at that address. (Same applies to MX targets, but this should be much less frequent, and usually temporary.)

Proper email services should spool the email and retry delivery over time. If your sendmail is not doing this, then you should check its configuration. You will also need to consider what to do with email addresses to which email can not be delivered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top