PHP (Hypertext Preprocessor) is an easier programming language used for faster development. In this article, we will learn, How to Send Email using PHP Script.
1. Send Email using PHP
Lets create a php file sendEmail.php in your web document root with following content. Change the $to_email with your recipient email address, $subject and $body as per your need, Keep as it is for testing purpose, $from_email with sender email address.
vim /var/www/html/sendEmail.php
Add below content
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $subject = "Simple Email Test via PHP"; $body = "Hi,nn This is test email send by PHP Script"; if ( mail($to_email, $subject, $body, $headers)) { echo("Email successfully sent to $to_email..."); } else { echo("Email sending failed..."); } ?> |
Now we can test it by access in a web browser or simply execute it from the command line like below.
php sendEmail.php
2. Send Email using PHP with HTML Form
Lets create a PHP script file sendEmail.php in your web document root of your domain with following content. This will show a simple form in the browser, using that we can also send an email for testing purpose.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php if (!isset($_POST["submit"])) { ?> <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> To: <input type="text" name="to_email"><br> From: <input type="text" name="from_email"><br> Subject: <input type="text" name="subject"><br> Message: <textarea rows="10" cols="20" name="message"></textarea><br> <input type="submit" name="submit" value="Send Email"> </form> <?php } else { if (isset($_POST["to_email"])) { $to_email = $_POST["to_email"]; $from_email = $_POST["from_email"]; $subject = $_POST["subject"]; $body = $_POST["message"]; if ( mail($to_email, $subject, $body, $headers)) { echo("Email successfully sent to $to_email..."); } else { echo("Email sending failed..."); } } } ?> |
Now Access in web browser and fill the all fields and hit Send Email button to finally send the email.
http://localhost/sendEmail.php
For more details visit php official website for details about mail function.
how to send mail from localhost without using FTP server in php
Thanks please post how to send email using google SMTP.
thanks, it really worked
Thanks for this script. It works fine
thanks for the sugestion
Thanks please post how to send email using google SMTP.
Hi Rahul,
Should the line endings in the script be “\r\n” ?
Also, on Debian 9 with php-mail installed to provide PEAR’s Mail:: package how would this be used to send SMTP email?
Cheers,
Noel