PHP Mail Script

Posted by Tully on Wed 29 July 2009

Today I wrote a command line PHP mail script. You are able to do this manually with programs such as Netcat or Telnet, but this just makes it easier and quicker. Once you run the script from the command line it will ask you for the required fields for emailing.

PHP Email Script

<?php
if ($argc > 1) {
    echo "This script does not take any arguments.\n";
    exit;
}

function read ($length='255') {
    if (!isset ($GLOBALS['StdinPointer'])) {
        $GLOBALS['StdinPointer'] = fopen ("php://stdin","r");
    }
    $line = fgets ($GLOBALS['StdinPointer'],$length);
    return trim ($line);
}

echo "\n";
echo "Enter Mail Server IP Address: ";
$host = read(30) . "\n";

echo "RCPT: ";
$rcpt = read(40) . "\n";

echo "Mail From: ";
$from = read(40) . "\n";

echo "Subject: ";
$subject = read(25) . "\n";

echo "Message: ";
$message = read(500) . "\n";

if ( (strlen($host) < 5)  || (strlen($rcpt) < 10) || 
    (strlen($from) < 10) || (strlen($subject) < 2) || 
    (strlen($message) < 5) ) {
    echo "You need to enter all fields properly.\n";
    exit;
}

$fp = fsockopen($host,25,$errstr,$errno,100);

if (!$fp) {
    echo "$errstr ($errno)";
} else {
    $out  = "helo h4x0r\r\n";
    $out .= "mail from:$from\r\n";
    $out .= "rcpt to:$rcpt\r\n";
    $out .= "data\r\n";
    $out .= "Subject:$subject\r\n\r\n";
    $out .= "$message\r\n.\r\n";
    fwrite($fp, $out);
    fclose($fp);
}