Search code examples
phphtmlphpmailerhtml-email

HTML sent via PHP mail() function not showing correctly in mail


I have set up a mail() function that's pretty straight forward in PHP:

$to = $_POST['address_to_send'];
$subject = "New Message";
$message = $_POST['content_to_send'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: [email protected]" . "\r\n";

echo $message;
mail($to,$subject,$message,$headers);

The echo shows my lovely formatted HTML exactly the way I want it and it sends the email as expected to the correct address with the correct subject and the correct from address.

However, the actual content of the email is blank.

The content is being generated using PHP but do not think this should make a difference, as the echo is showing just the HTML formatted correctly.

Edit

After testing, the echo only works locally on WAMP and not live on my server.

Tried using a var_dump() instead to try figure out what was going on and although in WAMP it gives me my string it is empty when it's live on the server.

So I think it is to do with how I'm firing the mail function.

I have a form like so (generated in PHP):

<form action='purchase_orders.php?id=$order_id' method='POST'>
<button onclick='send_po($i)'>Send to $email</button><br />
<input type='hidden' id='po_content_to_send' name='po_content_to_send'>
<input type='hidden' id='po_address_to_send' name='po_address_to_send' value='$email'>
</form>

This fires the following function in JS:

function send_po(po){
    var po_to_send = document.getElementById('purchase_order_'+po).innerHTML;
    document.getElementById('po_content_to_send').value = po_to_send;
    this.form.submit();
}

This adds the content of the DIV in question to the hidden input before submitting the form which should trigger this PHP:

if(isset($_POST['po_content_to_send']) && isset($_POST['po_address_to_send'])){
    $to = $_POST['po_address_to_send'];
    $subject = "New Purchase Order";
    $message = $_POST['po_content_to_send'];
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: [email protected]" . "\r\n";
    var_dump($message);
    //mail($to,$subject,$message,$headers);
}

Solution

  • I needed return false; on my button it was submitting before the value could get filled by the JS.