Trimitere mailuri din PHP cu functia mail()

postat acum 5 ani de Stefanescu Mihai in categorie iNoob

In acest tutorial am sa va invat cum sa trimiteti mailuri cu ajutorul unui formular HTMl si un simplu script PHP. Evident acest lucru se poate face intr-un mod mai complex si mai bine securizat, dar scopul acestui articol este pur si simplu demonstratic pentru persoanele ce doresc sa invete si nu stiu de unde sa inceapa.

In primul rand avem nevoie de un formular HTML cu 3 inputuri de tip text si un input de tip textarea. Iata cum arata codul meu pana acum:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<ul style="list-style: none; width: 270px;">
    <li style="margin: 6px 0px 6px 0px;">
        Sender: <input type="text" name="sender" style="float: right;"/>
    </li>
    
    <li style="margin: 6px 0px 6px 0px;">
        Receiver: <input type="text" name="receiver" style="float: right;"/>
    </li>
    
    <li style="margin: 6px 0px 6px 0px;">
        Subject: <input type="text" name="subject" style="float: right;"/>
    </li>
    
    <li style="margin: 6px 0px 6px 0px;height: 90px;">
        Message: <textarea cols='20' rows='4' name='message' style="float: right;"></textarea>
    </li>
    
    <li style="margin: 6px 0px 6px 0px;">
    <input type='submit' value='Submit!' style='float: right;'/>
    </li>
</ul>    
</form>

C-am asa arata fisierul meu php pana acum, un simplu form HTML. Cred ca singurul lucru pe care trebuie sa il explic pana acum este $_SERVER[‘PHP_SELF’] care este de fapt o variabila ce returneaza numele scriputlui curent ce este executat. In codul de mai sus el returneaza numele fisierului meu php, si anume send_mail_via_mail_function.php.

Acum am sa scriu codul ce proceseaza informatiile din acest formular deasupra, deci fisierul meu va avea urmatoarea structura:

<?php
//Codul ce proceseaza formularul va fi scris aici
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<ul style="list-style: none; width: 270px;">
	<li style="margin: 6px 0px 6px 0px;">
		Sender: <input type="text" name="sender" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
		Receiver: <input type="text" name="receiver" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
		Subject: <input type="text" name="subject" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;height: 90px;">
		Message: <textarea cols='20' rows='4' name='message' style="float: right;"></textarea>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
	<input type='submit' value='Submit!' style='float: right;'/>
	</li>
</ul>	
</form>

Acum, in primul rand trebuie sa verifica daca formularul a fost trimis prin metoda POST, iar pentru asta folosim urmatorul cod:

if($_SERVER['REQUEST_METHOD'] === 'POST'){ }

In interiorul acestui if verifica daca toate campurile din formular au fost completate:

 if ( !empty($_POST['sender']) && !empty($_POST['receiver']) && !empty($_POST['subject']) && !empty($_POST['message']) ) {
//cod ce necesita procesare
}else{
echo "Te rog completeaza toate campurile din formular!";
}

Din punct de vedere al securitatii nu pot sa va spun decat un lucru: NEVER TRUST USER INPUT!

Deci mereu sa verificati informatiile primite de la utilizator. Daca as incepe acum sa vorbesc despre securitate ar trebuii sa scriu cateva zeci de randuri si tot nu as termina, deci am sa ma limitez la cateva recomandari. Va recomand sa cititi despre functia filter_input_array

Probabil in viitorul apropiat am sa scriu un articol despre securitate in PHP, dar pentru moment sa continuam cu trimiterea de mailuri.

Ok, puse cap la cap asa arata codul meu final:

<?php

if($_SERVER['REQUEST_METHOD'] === 'POST'){

  if ( !empty($_POST['sender']) && !empty($_POST['receiver']) && !empty($_POST['subject']) && !empty($_POST['message']) ) {
	$headers = "MIME-Version: 1.0\r \n";
    $headers .= "Content-Type: text/html; charset=utf-8\r \n";
    $headers .= "From: ".$_POST['sender']." \r \n";

    if (mail($_POST['receiver'], $_POST['subject'], $_POST['message'], $headers)) {
        echo "Email Trimis!<br /><br />";
    } else {
        echo "E-mailul nu a putut fi trimis .<br /><br />";
    }
	}else{
		echo "Te rog completeaza toate campurile";
	}
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<ul style="list-style: none; width: 270px;">
	<li style="margin: 6px 0px 6px 0px;">
		Sender: <input type="text" name="sender" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
		Receiver: <input type="text" name="receiver" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
		Subject: <input type="text" name="subject" style="float: right;"/>
	</li>

	<li style="margin: 6px 0px 6px 0px;height: 90px;">
		Message: <textarea cols='20' rows='4' name='message' style="float: right;"></textarea>
	</li>

	<li style="margin: 6px 0px 6px 0px;">
	<input type='submit' value='Submit!' style='float: right;'/>
	</li>
</ul>	
</form>

Completezi campurile si apesi Submit!, o data ce mail-ul a fost trimis va fi afisat mesajul “Email Trimis!” altfel va fi afisat mesajul “E-mailul nu a putut fi trimis .”

Sper ca ati inteles ceva din acest articol scris in graba, dar ma puteti contacta pentru orice nelamurire si am sa va ajut!

Sunt un tanar programator din Bucuresti ce lucreaza in PHP/Mysql (MySqli/PDO), Laravel, CodeIgniter, MySQL, PostgreSQL, Wordpress, HTML5/CSS3, Sass, Photoshop si multe altele.
Google+ Community Facebook Group
Acest articol a fost mutat de pe vechea platforma.
Pentru orice eroare aparuta la mutare va rog sa ma contactati!

Comentariu postate de minecraft free download pc la data de 15.05.2019
Magnificent goods from you, man. I have understand your stuff previous to and you're just extremely great. I actually like what you've acquired here, certainly like what you are saying and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I cant wait to read far more from you. This is actually a terrific web site.
Comentariu postate de mojang minecraft download la data de 16.05.2019
I blog frequently and I genuinely thank you for your content. This article has really peaked my interest. I will bookmark your site and keep checking for new details about once a week. I subscribed to your Feed too.
Comentariu postate de free minecraft download la data de 17.05.2019
Thanks on your marvelous posting! I certainly enjoyed reading it, you may be a great author.I will ensure that I bookmark your blog and may come back from now on. I want to encourage you to continue your great writing, have a nice afternoon!
Comentariu postate de minecraft download free pc la data de 17.05.2019
It's appropriate time to make some plans for the future and it's time to be happy. I've read this post and if I could I desire to suggest you few interesting things or tips. Maybe you could write next articles referring to this article. I desire to read more things about it!
Comentariu postate de minecraft download free la data de 17.05.2019
Great article! This is the kind of info that are meant to be shared across the web. Shame on Google for no longer positioning this put up higher! Come on over and visit my website . Thanks =)