WordPress, outbound email hack

I spoke about this in Milwaukee. It is a very ugly hack, but it works.

This hack bypasses the firewall that blocks outgoing SMTP by using an external server and sending the emails to through http. The following is the code for it.

For the WordPress side, I created a plugin with the following code that overrode the wp_mail function

if ( !function_exists( 'wp_mail' ) ) :

function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
    $url = 'http://www.malfunctioned.com/emailer.php';
    
    $outhead = "";
    if (is_array ($headers )) { 
        foreach ($headers as $n => $v) {
            if ($outhead != "") { $outhead .= "\r\n"; }
            if (substr ($v, 0, 5) == "From:") { 
                $outhead .= "From: Email Out <noreply@somesite.com>";
            } else { 
                $outhead .= $v;
            }
        }
    }

    $myvars = 'to=' . urlencode($to) . '&subject=' . urlencode($subject) . '&message=' . urlencode($message) . '&headers=' . urlencode($outhead) . '';

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_POST, 1);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt( $ch, CURLOPT_HEADER, 0);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec( $ch );

    return true;
}

endif 

For the remote server, I have an apache/php server, with a stand alone script called emailer.php…  this is the code for it:

<?php 

// only allow access from the specific ip
if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1' && $_SERVER['REMOTE_ADDR'] != '38.113.180.228' ) {
 print "Failed: invalid IP";
 exit (0);
}

if ($_SERVER['REQUEST_METHOD'] == "POST") {
 $vars = $_POST;
} else { 
 $vars = $_GET;
}

error_reporting(0);

list ($to, $subject, $message, $headers) = array ($vars['to'], $vars['subject'], $vars['message'], $vars['headers']);
// Note to self:  check input before passing to the "mail" function
//  For now, this script has limited access, so, its ok

$loc = gethostbyaddr ($_SERVER['REMOTE_ADDR']);
if ($loc == "") { 
 $loc = "Unknown.com";
}

if (!preg_match ("/from:([^\n]*)\n/i", $headers)) { 
 $headers .= "From: EmailRelay@" . $loc;
}

mail($to, $subject, $message, $headers);

print "Success";

?>

Comments are closed, but trackbacks and pingbacks are open.