Send email from your gmail account via PHP

Posted on Posted in Blog

In my previous blog post, I presented how a PHP script can retrieve email from an IMAP server. The example I presented that time uses the gmail server, but actually it doesn’t matter what server is used. All the user has to do is alter the $host variable in the script.

Now, lets take a look at another code which could be used to send an email from the gmail server. This code could be used in PHP servers that doesn’t have the mail() function but requires the user to send emails to clients.

One particular application I did used several gmail accounts to send a lot of emails to prospective clients. It seems that emails actually coming from gmail are not marked SPAM by other email servers; unlike those coming from your mail server with headers altered to reflect that the email comes from gmail. So this script is helpful when we send bulk emails to other people.

However, this function needs your server to have php_openssl extension and fsockopen function as requirements for it to run. So check first whether your PHP server loads these two.

The extension php_openssl is used since communication between the script and the gmail server uses SSL (Secure Sockets Layer). The fsockopen is used also since we’re connecting through a different port (465) using TCP/IP (Transmission Control Protocol/Internet Protocol).

Let us get to the meat of the function:
[php]
rn”;
$header .= “To: <{$recepient}>rn”;
$header .= “Date: ” . date(“r”) . “rn”;
$header .= “Subject: ” . $title . “rn rn”;
$message = $header . str_replace (array(“rn”, “n”), “rn”, $message) . “rn.rn”;

$smtpConnect = fsockopen($host, $port);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “HELO veba-software.comrn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “AUTH LOGINrn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, base64_encode($username) . “rn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, base64_encode($password) . “rn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “MAIL FROM: <{$username}>rn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “RCPT TO: <{$recepient}>rn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “DATArn”);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, $message);
$smtpResponse = fgets($smtpConnect, 4096);
fputs($smtpConnect, “QUITrn”);
$smtpResponse = fgets($smtpConnect, 4096);

}
?>
[/php]

The responses of the SMTP server ($smtResponse) should be checked to see if an error is found. The current code does not perform response checking.

As you may see, commands sent to the mail server contains the “carriage return plus line feed” to signify end of command.

This is another blog post from veba-software.com. I hope you can find use of this.

Leave a Reply

Your email address will not be published. Required fields are marked *