1

I am having some trouble with setting up a mail form for my site. Currently, when I press submit on the form, the email that gets sent to me only shows the text portion of it and it does not show the variable! So in my email it would only show "This message is from"

I am fairly new to PHP - hopefully someone can take a look and maybe point out something I am not getting??

Thanks!

<? 
if(isset($_POST['message']) && ($_POST['message'] != '')){
    $name = $_POST["name"];
    $subject = "New Request";

    $recipient = "[email protected]";
    $message = $_POST["message"];

    $mailBody = 'This message is from  $name \n $message;

    mail($recipient, $subject, $mailBody);
}
?>
1

3 Answers 3

4

First concat your varriable name with string.as you have passed in single quotes so php consider it as a string.

Try below code :

<? 
if(isset($_POST['message']) && ($_POST['message'] != '')){
    $name = $_POST["name"];
    $subject = "New Request";

    $recipient = "[email protected]";
    $message = $_POST["message"];

    $mailBody = 'This message is from  '.$name."\r\n". $message;


    mail($recipient, $subject, $mailBody);
}
?>

Also to know difference about single quotes and double quotes you can refer below link :
What is the difference between single-quoted and double-quoted strings in PHP?

Sign up to request clarification or add additional context in comments.

2 Comments

Don't you need double quotes with \r\n for them to be a line break and not just print those characters out?
@magnuseriksson yes there is typo updated the answer , thanks
1

You should use double quoted string Also take a look at this

<? 
if(isset($_POST['message']) && ($_POST['message'] != '')){
    $name = $_POST["name"];
    $subject = "New Request";

    $recipient = "[email protected]";
    $message = $_POST["message"];

    $mailBody = 'This message is from  '.$name."\r\n". $message;

    mail($recipient, $subject, $mailBody);
}
?>

Comments

0
$mailBody = 'This message is from  '.$name.' \r\n'. $message;

OR

$mailBody = "This message is from $name\r\n$message";

The first line which you have written the variables are inside the single quote which is taking your variable as text, where as without quote or inside double quotes are able to take those as variable.

Please go through : What is the difference between single-quoted and double-quoted strings in PHP?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.