Send an email using PHP mail() function
In this article, we will explain to you how to send an email using PHP mail() function with simple text or html.
Core php mail function, php mail function, php mail() function,Sending Emails in PHP, How to Setup the PHP mail() Function, How to Send Email using PHP mail() Function, php mail function not working, php send email form, Sending email with html content.
Checkout more articles on PHP
PHP provides an in-built mail()
function to send email. In this function, three parameters are required and rest of the parameters are optional.
Syntax:
1 | mail(to, subject, message, [headers], [parameters]); |
Let’s look about the parameters.
- to: It’s required parameter and we have to add receiver email id. Also we can add multiple email ids by comma separated.
- subject: It’s a required parameter. It specified the subject of the email.
- message: It’s also required parameter. It specified the message of the email.
- headers: It’s optional parameter and we can add additional headers i.e. From, CC, BCC that must be separated by (/r/n).
- parameters: It’s also an optional parameter and used to pass additional parameters.
This function returns true if email sent successfully and false if email failed.
Sending simple email
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $subject = "Test Mail"; $message = "Hi, This is a test mail using php"; if (mail($to, $subject, $message)) { echo("Your email successfully sent"); } else { echo("Your email is not sent"); } ?> // Output: Your email successfully sent |
Sending email with html message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $subject = "Test Mail"; $message = "Hi, This is a test mail using php"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html\r\n"; if ( mail($to, $subject, $message, $headers)) { echo("Your email successfully sent"); } else { echo("Your email is not sent"); } ?> // Output: Your email successfully sent |
Note: PHP mail() function will not work in Local server. If you want to make it work then you have to configure SMTP authentication.
That’s it for today.
Thank you for reading. Happy Coding!