How to use the value of a variable to send an e-mail

Hi everyone,

I have problems with sending an e-mail. Everything works fine till I want to replace the “example@example.com” part for a variable with the value of an input field.

Here is my code:
This works:

    $mail->setFrom('example@example.com', 'Berkan Ozcakir'); //Verzender
    $mail->addAddress('example@example.com', 'Jan');		     //Ontvanger

This doesn’t work:

    $mail->setFrom('example@example.com', 'Berkan Ozcakir'); //Verzender
    $mail->addAddress($_SESSION['email'], 'Jan');		     //Ontvanger

This is the other file:

	$email = htmlspecialchars($_POST['inputemail']);
	$_SESSION['email'] = $email;

Can somebody help me out with this problem?

Habe you called start_session() in both files before you use $_SESSION?

Yes I did.
The $_SESSION[‘mail’] works. I tested it with echo and it gave me the value of the input. So that is not the problem I think.

Then it’s probably the htmlspecialchars. Could you try the code without that?

1 Like

htmlspecialchars was like you said the problem.
I just delete that part and it worked.

Thank you so much for your help. I was trying to fix this problem the whole day!

Do you also know why this solved the problem? :slight_smile:

1 Like

If you are concerned about the safety of the user input email address, you could replace the htmlspecialchars() with a filter_var() using an email validate or sanitize filter.
htmlspecialchars() is only really for escaping for output to html and may break things like URLs and email addresses.

1 Like

I just read about it: the reaction of SamA74

What I did understand is that htmlspecialchars() breaks URL’s and in my case it broke my e-mail adres.
Please correct me if I’m wrong.:blush:

It changes the email so it safe to display on website and avoid Cross Site Scripting where an attacker inserts stuff that gets executed by the browser.

So for example when you apply htmlspecialchars to an email address it will replace the @ with an html entity (() that is rendered fine in the browser (which is why it looked OK when you output the variable) but can not be used as a real email address.

Hope that helps :slightly_smiling_face:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.