Reputation:
I am new to php and in my project I have used php mail function, but while sending mail from database it shows an error like:
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP"
By searching on stackoverflow and google, I come to know that XAMPP does not provide SMTP server and I will have to install a SMTP server.
I am really confused.So, Which SMTP server I should install?
Upvotes: 1
Views: 15638
Reputation: 145
For this example, I will use PHPMailer.
So first, you have to download the source code of PHPMailer. Only 3 files are necessary :
Put these 3 files in the same folder. Then create the main script (I called it 'index.php').
Content of index.php :
<?php
//Load PHPMailer dependencies
require_once 'PHPMailerAutoload.php';
require_once 'class.phpmailer.php';
require_once 'class.smtp.php';
/* CONFIGURATION */
$crendentials = array(
'email' => '[email protected]', //Your GMail adress
'password' => 'XXXXXXXX' //Your GMail password
);
/* SPECIFIC TO GMAIL SMTP */
$smtp = array(
'host' => 'smtp.gmail.com',
'port' => 587,
'username' => $crendentials['email'],
'password' => $crendentials['password'],
'secure' => 'tls' //SSL or TLS
);
/* TO, SUBJECT, CONTENT */
$to = ''; //The 'To' field
$subject = 'This is a test email sent with PHPMailer';
$content = 'This is the HTML message body <b>in bold!</b>';
$mailer = new PHPMailer();
//SMTP Configuration
$mailer->isSMTP();
$mailer->SMTPAuth = true; //We need to authenticate
$mailer->Host = $smtp['host'];
$mailer->Port = $smtp['port'];
$mailer->Username = $smtp['username'];
$mailer->Password = $smtp['password'];
$mailer->SMTPSecure = $smtp['secure'];
//Now, send mail :
//From - To :
$mailer->From = $crendentials['email'];
$mailer->FromName = 'Your Name'; //Optional
$mailer->addAddress($to); // Add a recipient
//Subject - Body :
$mailer->Subject = $subject;
$mailer->Body = $content;
$mailer->isHTML(true); //Mail body contains HTML tags
//Check if mail is sent :
if(!$mailer->send()) {
echo 'Error sending mail : ' . $mailer->ErrorInfo;
} else {
echo 'Message sent !';
}
You can also add 'CC', 'BCC' fields etc...
Examples and documentation can be found on Github.
If you need to use another SMTP server, you can modify the values in $smtp
.
Note : you may have a problem sending the mail, like 'Warning: stream_socket_enable_crypto(): this stream does not support SSL/crypto'.
In such case, you must enable the OpenSSL extension. Check your phpinfo()
, look for the value of 'Loaded Configuration File' (in my case : E:\Program Files\wamp\bin\apache\apache2.4.2\bin\php.ini) and in this file, uncomment the line extension=php_openssl.dll
. Then, restart your XAMPP server.
Upvotes: 4