Search code examples
phphtmlemailsend

Sending PHP mail with HTML


Hi guys I am trying to send HTML email with php. When I click on button on one page it loads php file and sends it data that should go in mail. That data is HTML code, I also use same variable/code to generate content in that PHP file. Content is generated perfectly but E-mail is empty, altought i send same variable that I use to make content on that page. Code is

                            <?php 
                            $message=$_POST["email"];
                            echo $message;//Use variable to generate content
                            if (isset($_POST['button1'])) 
                            {          

                                    $to = 'test@gmail.com';                                                                            
                                    $subject = 'Subject';
                                    $headers[] = 'MIME-Version: 1.0';
                                    $headers[] = 'Content-type: text/html; charset=iso-8859-1';
                                    mail($to, $subject, $message, implode("\r\n", $headers));
                            }                            
                            ?>
                            <form method="POST" action=''>
                           <input type="submit" name="button1"  value="Send mail" class="btn">

EDIT: If i type html code manualy it works.


Solution

  • Your headers seems to be ok according documentation (https://secure.php.net/manual/en/function.mail.php) #4.

    The field "email" you are using in line 2 of code is not included in the form!

    <?php
    
    function mailX($to, $subject, $message, $headers) {
        var_dump($message);
    }
    
    if (array_key_exists('button1', $_POST)) {
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-type: text/html; charset=iso-8859-1';
    
        mailX(
            'test@gmail.com',
            'Subject',
            array_key_exists('email', $_POST) && !empty($_POST['email']) ? $_POST['email'] : 'Empty message!',
            implode("\r\n", $headers)
        );
    }
    
    ?>
    <form method="POST">
        <input type="text" name="email">
        <input type="submit" class="btn" name="button1" value="Send mail">
    </form>
    

    You should really avoid sending HTML entered by the user via E-Mail this can cause xss-injection as they could do things like e.g.

    <script>alert('TEST');</script>
    

    I would suggest you to use a library like PHPMailer (https://github.com/PHPMailer/PHPMailer) or SwiftMailer (https://swiftmailer.symfony.com/) both are free/open-source. You have easy possiblity to send the mails through SMTP (which is required by some hosters to avoid spam), also the libraries optimizes your headers according the settings to be valid/compatible with most (web)mail-clients.