Search code examples
phpemailinvite

Sending invitations to email addresses taken from text inputs


I'm trying to figure out a html/php code that enables the user to send invitations for email addresses that he enters. The user has to only type in the email address then click the button "invite", after that the invitation will be sent. I have five input fields by which I need to write a php code to take the inserted email addresses and send invitations for

here is my index.php file:

<form method="post" action="test.php">
 <input name="email" type="email" size="30" placeholder="email address of friend 1"><br> 
<input name="email2" type="email" size="30" placeholder="email address of friend 2"><br>
<input name="email3" type="email" size="30" placeholder="email address of friend 3"><br>
<input name="email4" type="email" size="30" placeholder="email address of friend 4"><br>
<input name="email5" type="email" size="30" placeholder="email address of friend 5"><br><br>

<input name="sendername" type="text" size="30" placeholder="Your Name"><br>

<input type="submit" name="invite" value="Invite"> </form>

I wrote this code in the test.php file to process the code for the first email, but it gives me the return message " message couldn't be sent" any advice ?

<?php 

if(isset($_POST['invite'])) {

    // CHANGE THE TWO LINES BELOW

 $to = $_POST['email'];;

   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:[email protected]\r\n";
   $retval=@mail ($to,$subject,$message,$header);

   if( $retval == true )  
   {  echo "Message sent successfully...";
   }
   else
   { echo "Message could not be sent...";
   }


}


?>

Solution

  • After indulging more into this issue and attempting to resolve it, I figured out how to do the job. Briefly I had to use foreach() supplied with an if statement to loop over the email array. my final code looks like this :

    <?php
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);
        if(isset($_POST['invite'])) {
    
            // CHANGE THE TWO LINES BELOW
    
            $to=$_POST['email'];
            $subject="This is subject";
            $message="This is simple text message.";
            $email='[email protected]';
            $header='From: '.$email."\r\n".'Reply-To: '.$email."\r\n".'X-Mailer: PHP/'.phpversion();
    
            if (is_array($to )){
            foreach($to as $value) {
             @mail($value,$subject,$message,$header);
        }
    
            }
               {  
                      echo "Message sent successfully...";
            } 
    
    
        }
    ?>