Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»PHP»3 Sample PHP Scripts for Sending Emails

    3 Sample PHP Scripts for Sending Emails

    By RahulAugust 5, 20223 Mins Read

    PHP (Hypertext Preprocessor) is an easier programming language used for faster development. The PHP mail() function allows sending emails directly from a script. This function returns true for the successful delivery of email, otherwise returns false.

    Advertisement

    PHP mail() function uses sendmail_path value from ini file. For Unix systems the default value is used as /usr/sbin/sendmail or /usr/lib/sendmail. Systems not running with Sendmail should set this directive to other mail replacements like /var/qmail/bin/sendmail for Qmail.

    In this article, you will learn 3 methods of sending emails using sample PHP scripts.

    1. Simple PHP script for sending emails
    2. Send email using PHP with HTML format
    3. Sending emails using PHP via remote SMTP server

    1. Simple PHP Script for Sending Emails

    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 purposes, $from_email with a sender email address.

    nano sendEmail.php 
    

    Add the following sample PHP code for sending emails:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?php
       $to_email = "[email protected]";
       $subject = "Simple Email Test via PHP";
       $body = "Hi,\n This is test email send by PHP Script";
       $headers = "From: [email protected]";
     
       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 
    
    Output:
    Email successfully sent to [email protected]

    2. Send Email using PHP in HTML Format

    In the previous example, we executed the PHP script via the command line. Let’s try another example to create a web form and send an email with a PHP script.

    Assuming you already have a website hosted on a server enabled with PHP. Create a PHP script sendEmail.php under the website 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 purposes.

    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 sendEmail.php in the web browser

     http://localhost/sendEmail.php
    
    PHP email() function example
    A sample web form for sending email with PHP

    A form will be displayed with input fields. Fill in all the fields and hit the Send Email button to submit the form. On submission, the PHP script added in the form will send the email.

    3. Sending Emails using PHP via Remote SMTP Server

    You can also use a remote SMTP server for sending emails using PHP applications. In order to use these options, you must have remote SMTP server access like Gmail, Amazon SES, Sendgrid, etc. We will use the PHPMailer module in PHP script for sending emails via a remote SMTP server.

    First of all, You need to Install the phpmailer module using composer under your application.

    composer require phpmailer/phpmailer 
    

    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
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    <?php
     
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    require 'vendor/autoload.php';
     
    $mail = new PHPMailer(true);
    try {
        //Server settings
        // $mail->SMTPDebug = 2; //Uncomment to view debug log
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = '[email protected]';
        $mail->Password = '_password_';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
     
        $mail->setFrom('[email protected]', 'Admin');
        $mail->addAddress('[email protected]', 'Recipient1');
        $mail->addAddress('[email protected]');
        $mail->addReplyTo('[email protected]', 'noreply');
        $mail->addCC('[email protected]');
        $mail->addBCC('[email protected]');
     
        //Attachments
        $mail->addAttachment('/backup/test.log');
     
        //Content
        $mail->isHTML(true);
        $mail->Subject = 'Mail Subject Here!';
        $mail->Body    = 'Mail body content goes here';
     
        $mail->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    }

    Conclusion

    In this tutorial, You have learned 3 methods of sending emails via PHP scripts. You can get more information about PHP mail() function from its official website.

    mail PHP smtp
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    PHP Arrays: A Beginner’s Guide

    Running Laravel Queue Worker as a Systemd Service

    How to Change PHP Session Timeout

    View 12 Comments

    12 Comments

    1. shoji on March 20, 2022 7:07 am

      Stop provide insecure email sending, whoever gonna use this it will be easily hackable. at least show them how to escape or stop giving vulnerable code

      Reply
    2. Amit Sharma on February 10, 2022 7:42 am

      Thanks For This Useful article

      Reply
    3. Gabriele Giles on April 22, 2021 8:30 pm

      Hi. How do l make my submit button to work? How do l write the php and can l write the php code inside my index.html file? I have my hosting and domain with namecheap.

      Reply
    4. Sourav Das on October 2, 2019 5:24 pm

      how to send mail from localhost without using FTP server in php

      Reply
      • anurag tripathi on April 18, 2021 12:08 pm

        no you cant send email on localhost

        Reply
    5. Takinmall on September 15, 2019 10:03 am

      Thanks please post how to send email using google SMTP.

      Reply
    6. Frank on September 12, 2019 8:17 am

      thanks, it really worked

      Reply
      • Lefan Billips on September 28, 2021 7:01 pm

        didnt work AT ALL where u tested it??

        Reply
    7. Ayo Celestine on August 21, 2019 7:41 pm

      Thanks for this script. It works fine

      Reply
    8. Zubair shah on June 27, 2019 4:07 pm

      thanks for the sugestion

      Reply
    9. Raj on June 16, 2019 7:28 pm

      Thanks please post how to send email using google SMTP.

      Reply
    10. Noel Springer on July 24, 2018 1:33 am

      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

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Configure Postfix to Use Gmail SMTP on Ubuntu & Debian
    • PHP Arrays: A Beginner’s Guide
    • Deploying Flask Application on Ubuntu (Apache+WSGI)
    • OpenSSL: Working with SSL Certificates, Private Keys and CSRs
    • How to Create and Read List in Python
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.