How to send mail in php using sendmail
To send mail using PHP and the sendmail
command, you can use the mail()
function in PHP. Here's an example of how to do it:
Step 1: Configure your PHP settings
Make sure that the sendmail_path
directive is set in your PHP configuration file (php.ini
). This directive specifies the path to the sendmail
command.
For example, if you have sendmail
installed in the default location (/usr/sbin/sendmail
), you can set the sendmail_path
directive as follows:
sendmail_path = /usr/sbin/sendmail -t
Step 2: Use the mail()
function
Use the mail()
function to send an email. The mail()
function takes four arguments:
to
: The recipient's email address.subject
: The subject of the email.message
: The body of the email.headers
: An optional array of headers to include in the email.
Here's an example of how to use the mail()
function:
<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email sent using PHP and sendmail.';
$headers = array(
'From' => '[email protected]',
'Reply-To' => '[email protected]',
'Content-Type' => 'text/plain; charset=UTF-8'
);
if (mail($to, $subject, $message, implode("\r\n", $headers))) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email.';
}
?>
Step 3: Run the script
Save the script to a file (e.g., sendmail.php
) and run it using your web server or a command-line PHP interpreter.
When you run the script, it will send an email to the specified recipient using the sendmail
command.
Tips and considerations
- Make sure that the
sendmail
command is installed and configured correctly on your system. - The
mail()
function returnstrue
if the email is sent successfully, andfalse
otherwise. You can use this return value to handle errors. - You can customize the
headers
array to include additional headers, such asCC
,BCC
, or custom headers. - If you're using a web server, make sure that the PHP script has the necessary permissions to write to the mail queue.