Search code examples
phpphpmailer

How can i make subject and body message to be given from inputs in phpmailer


This is index.php Right now all i can do is give values to the $mail->Subject and $mail->body but i want it to be dynamic for example Here i want to give 2 inputs for subject and message and pass it on $mail->Subject and $mail->Body since the post method is on ajax im unable to pass two values from input fields to the send_mail.php any help would be appreciated

<?php
    //index.php
    
    $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
    $query = "SELECT * FROM customer ORDER BY customer_id";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
       
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <br />
    <div class="container">
      
        <br />
        <div class="table-responsive">
    
            <table class="table table-bordered table-striped">
                <tr>
                    <th>Customer Name</th>
                    <th>Email</th>
                    <th>Select</th>
                    <th>Action</th>
                </tr>
                <?php
                $count = 0;
                foreach($result as $row)
                {
                    $count = $count + 1;
                    echo '
                        <tr>
                            <td>'.$row["customer_name"].'</td>
                            <td>'.$row["customer_email"].'</td>
                            <td>
                                <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
                            </td>
                            <td>
                            <button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
                            </td>
                        </tr>
                        ';
                }
                ?>
                <tr>
                    <td colspan="3"></td>
                    <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
                </tr>
            </table>
        </div>
    </div>
    </body>
    </html>
    
    <script>
        $(document).ready(function(){
            $('.email_button').click(function(){
                $(this).attr('disabled', 'disabled');
                var id  = $(this).attr("id");
                var action = $(this).data("action");
                var email_data = [];
                if(action == 'single')
                {
                    email_data.push({
                        email: $(this).data("email"),
                        name: $(this).data("name")
                    });
                }
                else
                {
                    $('.single_select').each(function(){
                        if($(this).prop("checked") == true)
                        {
                            email_data.push({
                                email: $(this).data("email"),
                                name: $(this).data('name')
                            });
                        }
                    });
                }
    
                $.ajax({
                    url:"send_mail.php",
                    method:"POST",
                    data:{email_data:email_data},
                    beforeSend:function(){
                        $('#'+id).html('Sending...');
                        $('#'+id).addClass('btn-danger');
                    },
                    success:function(data){
                        if(data == 'ok')
                        {
                            $('#'+id).text('Success');
                            $('#'+id).removeClass('btn-danger');
                            $('#'+id).removeClass('btn-info');
                            $('#'+id).addClass('btn-success');
                        }
                        else
                        {
                            $('#'+id).text(data);
                        }
                        $('#'+id).attr('disabled', false);
                    }
                })
    
            });
        });
    </script>

And this is send_mail.php

<?php
//send_mail.php

if(isset($_POST['email_data']))
{
    require 'class/class.phpmailer.php';
    $output = '';
    foreach($_POST['email_data'] as $row)
    {
        $mail = new PHPMailer;
        $mail->IsSMTP();                                
        $mail->Host = 'smtp.gmail.com';     
        $mail->Port = '587';                                
        $mail->SMTPAuth = true;                         
        $mail->Username = 'xx';                 
        $mail->Password = 'xx';                 
        $mail->SMTPSecure = 'tls';                          
        $mail->From = 'xx';         
        $mail->FromName = 'xx';                 
        $mail->AddAddress($row["email"], $row["name"]); 
        $mail->WordWrap = 50;                           
        $mail->IsHTML(true);                            
        $mail->Subject = 'i want input to be passed here'; 
        //An HTML or plain text message body
        $mail->Body = 'and the body message to be passed here';

        $mail->AltBody = '';

        $result = $mail->Send();                        //Send an Email. Return true on success or false on error

//        if($result["code"] == '400')
//        {
//            $output .= html_entity_decode($result['full_error']);
//        }

    }
    if($output == '')
    {
        echo 'ok';
    }
    else
    {
        echo $output;
    }
}

?>

Solution

  • I am assuming You want to add two inputs for subject and message for each email data.

    You can add 2 fields and in ajax set it along with email data and pass it to send_mail.php.

    JS Code

    <script>
        $(document).ready(function(){
            $('.email_button').click(function(){
                $(this).attr('disabled', 'disabled');
                var id  = $(this).attr("id");
                var action = $(this).data("action");
                var email_data = [];
                if(action == 'single')
                {
                    email_data.push({
                        email: $(this).data("email"),
                        name: $(this).data("name"),
                        subject: $(this).data("subject"), //or can be grab from input
                        message: $(this).data("message")
                    });
                }
                else
                {
                    $('.single_select').each(function(){
                        if($(this).prop("checked") == true)
                        {
                            email_data.push({
                                email: $(this).data("email"),
                                name: $(this).data('name'),
                                subject: $(this).data("subject"), //or can be grab from input
                        message: $(this).data("message")
                            });
                        }
                    });
                }
    
                $.ajax({
                    url:"send_mail.php",
                    method:"POST",
                    data:{email_data:email_data},
                    beforeSend:function(){
                        $('#'+id).html('Sending...');
                        $('#'+id).addClass('btn-danger');
                    },
                    success:function(data){
                        if(data == 'ok')
                        {
                            $('#'+id).text('Success');
                            $('#'+id).removeClass('btn-danger');
                            $('#'+id).removeClass('btn-info');
                            $('#'+id).addClass('btn-success');
                        }
                        else
                        {
                            $('#'+id).text(data);
                        }
                        $('#'+id).attr('disabled', false);
                    }
                })
    
            });
        });
    </script>
    

    In send_mail.php replace following lines

    $mail->Subject = 'i want input to be passed here'; 
    //An HTML or plain text message body
    $mail->Body = 'and the body message to be passed here';
    

    With This

    $mail->Subject = $row["subject"]; 
    $mail->Body = $row["message"];
    

    Hope it will answer your question.