[php] How to configure PHP to send e-mail?

I need to send mail to the users of my website using php script. I have tried using mail function in php.
My code is as follows:

  $to = "[email protected]";
  $subject = "Test mail";
  $message = "My message";
  $from = "[email protected]";
  $headers = "From:" . $from;
  mail($to,$subject,$message,$headers);

When I try running the program this is what I get:

 Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set().

Please tell me what address to include in the $from variable. Do I need a smtp server for this? How do I send mails using a localhost? Please tell me what exactly to edit in the php.ini file

I am new to all this.. Please help me..

This question is related to php email smtp

The answer is


Here's the link that gives me the answer and we use gmail:

Install the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

Modify the php.ini file to use it (commented out the other lines):

mail function

For Win32 only.

SMTP = smtp.gmail.com
smtp_port = 25
For Win32 only.
sendmail_from = <e-mail username>@gmail.com

For Unix only.

You may supply arguments as well (default: sendmail -t -i).

sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

sendmail

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

You won't be able to send a message through other people mail servers. Check with your host provider how to send emails. Try to send an email from your server without PHP, you can use any email client like Outook. Just after it works, try to configure PHP.ini with your email client SMTP (sending e-mail) configuration.


configure your php.ini like this

SMTP = smtp.gmail.com

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury

; SMTP = smtp.gmail.com

; smtp_port = 465

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer


Use PHPMailer instead: https://github.com/PHPMailer/PHPMailer

How to use it:

require('./PHPMailer/class.phpmailer.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';

$body = 'This is the message';

$mail->IsSMTP();
$mail->Host       = 'smtp.gmail.com';

$mail->SMTPSecure = 'tls';
$mail->Port       = 587;
$mail->SMTPDebug  = 1;
$mail->SMTPAuth   = true;

$mail->Username   = '[email protected]';
$mail->Password   = '123!@#';

$mail->SetFrom('[email protected]', $name);
$mail->AddReplyTo('[email protected]','no-reply');
$mail->Subject    = 'subject';
$mail->MsgHTML($body);

$mail->AddAddress('[email protected]', 'title1');
$mail->AddAddress('[email protected]', 'title2'); /* ... */

$mail->AddAttachment($fileName);
$mail->send();

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = '[email protected]';
    $subject = "New Message on YourWebsite.com";
    $body = '<html>
                <body>
                    <h2>Title</h2>
                    <br>
                    <p>Name:<br>'.$name.'</p>
                    <p>Email:<br>'.$email.'</p>

                </body>
            </html>';

//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";

//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
    echo '<br>';
    echo "Success. Thanks for Your Message.";
} else {
    echo 'Error.';
}
}
?>

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="name" placeholder="Your Name"><br>
            <input type="text" name="email" placeholder="Your Email"><br>
            <button type="submit">Subscribe</button>
        </form>
    </body>
</html>

You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.

If you own a server or VPS upload the script and it will work fine.


To fix this, you must review your PHP.INI, and the mail services setup you have in your server.

But my best advice for you is to forget about the mail() function. It depends on PHP.INI settings, it's configuration is different depending on the platform (Linux or Windows), and it can't handle SMTP authentication, which is a big trouble in current days. Too much headache.

Use "PHP Mailer" instead (https://github.com/PHPMailer/PHPMailer), it's a PHP class available for free, and it can handle almost any SMTP server, internal or external, with or without authentication, it works exactly the same way on Linux and Windows, and it won't depend on PHP.INI settings. It comes with many examples, it's very powerful and easy to use.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to smtp

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error PHPMailer - SMTP ERROR: Password command failed when send mail from my server php function mail() isn't working Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" SmtpException: Unable to read data from the transport connection: net_io_connectionclosed How to configure SMTP settings in web.config Send mail via CMD console Mail not sending with PHPMailer over SSL using SMTP