Using Gmail As An SMTP Server With PHP
Contents
Introduction
You can use Gmail as an outgoing SMTP server. Google has provided instructions for many email clients. This tutorial shows how you can use PHP to send emails using Gmail's SMTP service. You might find this useful when you want to test an application from your local machine, but you do not have an SMTP server installed.
Check that your php.ini file has enabled SSL. On Windows you need to make sure this line is there and not commented out:
extension=php_openssl.dll
If you're using XAMPP, it might come with 2 php.ini files but only one will take effect.
Sample Code
The sample code shown here uses the PHP Mail package, which most PHP hosts should have installed.
In the code below, you would replace username@gmail
and to@gmail.com
with your own Gmail username and target email address respectively.
If your message is successfully sent, "Message successfully sent" will be displayed, otherwise you should see an error message.
<?php require_once "Mail.php"; $from = "username@gmail.com"; $to = "to@gmail.com"; $subject = "Hi!"; $body = "Hi,\n\nHow are you?"; /* SMTP server name, port, user/passwd */ $smtpinfo["host"] = "ssl://smtp.gmail.com"; $smtpinfo["port"] = "465"; $smtpinfo["auth"] = true; $smtpinfo["username"] = "username@gmail.com"; $smtpinfo["password"] = "abcdefg"; $headers = array ('From' => $from,'To' => $to,'Subject' => $subject); $smtp = &Mail::factory('smtp', $smtpinfo ); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo("<p>" . $mail->getMessage() . "</p>"); } else { echo("<p>Message successfully sent!</p>"); } ?>
Related Links
- How to Send Email from a PHP Script Using SMTP Authentication - The code shown here was adapted from the one on this page.