Simple email script

I need to try and get a simple script to email a form and attach a file to it, if they choose to attach a file. Basically its a simple vacancy form where you can attach a CV. I have no experience in coding fom and stuff, so any help would be good. I usually pay to get this done, but the  budget does not allow for this, so i might have to try do it myself :0/

Thanks for any help.
LVL 2
SideasAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lucki_lukeCommented:
Hey,

Heres a simple form:

<form enctype="multipart/form-data" action="email.php" method="post">
Name: <input type="text" name="name" /><br />
E-Mail: <input type="text" name="email" /><br />
Subject: <input type="text" name="subject" /><br />
Body:  <textarea name="body" cols="30" rows="10"></textarea><br />
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
CV: <input type="file" name="cv" /><br />
Name: <input type="button" />
</form>

For the mailing funciton I would suggest you to download a library like PHPMailer because attachments and other stuff are not so easy.
http://phpmailer.sourceforge.net/
Then the email.php:
<?php
// every input inside the form is now available in the $_POST variable (except the file)

require("class.phpmailer.php");

$attachment = false;
if($_FILES['cv']['name'] =! ''){
      $uploaddir = '/var/www/uploads/';
      $uploadfile = $uploaddir . basename($_FILES['cv']['name']);
      
      if (move_uploaded_file($_FILES['cv']['tmp_name'], $uploadfile)) {
            // everything worked fine up to now
            $attachment = true;
      } else {
            // somethings wrong
            echo "Failed uploading file!";
      }
}

$mail = new PHPMailer();

$mail->From     = $_POST['email'];
$mail->FromName = $_POST['name'];
$mail->Mailer   = "mail";
$mail->AddAddress("yourname@site.com", "Receiver"));
$mail->Subject = $_POST['subject'];
$mail->Body    = $_POST['body'];
if($attachment === true)
      $mail->AddAttachment($uploadfile, $_FILES['cv']['name']);
if(!$mail->Send())
{
   echo "There was an error sending the message";
   exit;
}
?>

Using the PHPMailer class to send the mail is quite easy as seen above.
If you have any questions left please ask.

Lukas

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Aamir SaeedCommented:
If you find it difficult to use any library, you can use this simple code


      <div style="height:15px"></div>

      <table width="80%" align="center" border="1" class="Tb1">
            <tr>
                  <td>
                        <form action="email.php?submit=yes" method="post" enctype="multipart/form-data" name="compose">
                        <table width="93%" align="center" border="1" class="Tb1">
                              <tr class="headerrow">
                                    <td colspan="2">
                                          Send Email                                    </td>                  
                              </tr>
                              <tr class="oddrow">
                                    <td>
                                          To:                                    </td>
                                    <td>
                                          <input type="text" tabindex="1" name="receiver" size="50">                                    </td>
                              </tr>
                              <tr class="evenrow">
                                    <td>
                                          Subject:                                    </td>
                                    <td>
                                          <input type="text" name="subject" size="50">                                    </td>
                              </tr>
                              <tr class="oddrow">
                                    <td>
                                          Message:                                    </td>
                                    <td>
                                          <textarea name="message" cols="45" rows="10"></textarea>                                    </td>
                              </tr>
                              <tr class="oddrow">
                                <td>Attatchment: </td>
                                <td><input id="fileatt" type="file" name="fileatt"  tabindex="" /></td>
                          </tr>
                              <tr class="evenrow">
                                    <td align="center" colspan="2">
                                          <input type="submit" name="send" value="Send" class="buttons">                                    </td>                                    
                              </tr>
                        </table>                        
                        </form>                  </td>
                  <form name="combo_box" action="send_email.php" method="post">
                  </form>
            </tr>
</table>      
<?
      if($_GET['submit'] == 'yes')
      {
            // Message Receiver
            $reciever = $_POST['receiver'];
            
            // Message Sender
            $subject = $_POST['subject'];
            
            // Message
            $message = $_POST['message'];
            
            // Obtain file upload vars
            $fileatt            = $_FILES['fileatt']['tmp_name'];
            $fileatt_type      = $_FILES['fileatt']['type'];
            $fileatt_name      = $_FILES['fileatt']['name'];            // Converting String of Receiver Name into Array

            $recievernames = explode(",", $reciever);

            // Iterating Receiver Name's Array
            $i = 0;
            while($recievernames[$i])
            {
                  $email = $recievernames[$i];
                  
                  $headers = "From: aamir@post.com";

                   if (is_uploaded_file($fileatt)) {
                        $file = fopen($fileatt,'rb');
                        $data = fread($file,filesize($fileatt));
                        fclose($file);
                  
                        // Base64 encode the file data
                        $data = chunk_split(base64_encode($data));
                    }                  

                    // Generate a boundary string
                    $semi_rand = md5(time());
                    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
                    
                    // Add the headers for a file attachment
                    $headers .= "\nMIME-Version: 1.0\n" .
                                      "Content-Type: multipart/mixed;\n" .
                                      " boundary=\"{$mime_boundary}\"";
                  
                    // Add a multipart boundary above the plain message
                    $message = "This is a multi-part message in MIME format.\n\n" .
                                     "--{$mime_boundary}\n" .
                                     "Content-Type: text/plain;\n charset=\"iso-8859-1\"\n" .
                                     "Content-Transfer-Encoding: 7bit\n\n" .
                                     $message . "\n\n" .
                                     "--{$mime_boundary}\n";

                    // Add file attachment(s) to the message
                    if ($fileatt_name > "") {
                        $message .= "Content-Type: {$fileatt_type};\n" .
                                           " name=\"{$fileatt_name}\"\n" .
                                            "Content-Transfer-Encoding: base64\n" .
                                           "Content-Disposition: attachment;\n" .
                                           " filename=\"{$fileatt_name}\"\n\n" .
                                            $data . "\n" .
                                            "--{$mime_boundary}\n";
                        }
                  
                  // Mail it
                  mail($email, $subject, $message, $headers);                  

                  $i++;
            }            
                        
      }      
?>            
SideasAuthor Commented:
Hi guys,

Got so far on both of these but didn't get them working :-/

lucki_luke i got to here
http://www.idealogyltd.com/Email-form/email-form.html
I did put the sourceforge script up you can see it is there. http://www.idealogyltd.com/Email-form/

i_m_aamir i got to this point
http://www.idealogyltd.com/Email-form/email-form-2.html

Any help on both be great. I not sure what might be going wrong so don't know where to look. I guess its simple but as i don't know this stuff i cant figure it out.

Thanks again for trying to help a noob.
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

lucki_lukeCommented:
Hi,

sorry, had a small mistake in my script:

$mail->AddAddress("yourname@site.com", "Receiver")); // otherwise parse error
must be
$mail->AddAddress("yourname@site.com", "Receiver");

and in the form I made something very stupid:
Name: <input type="button" />
should be
<input type="submit" value="Submit" />

The problem with your other form (i_m_aamirs approach) is that the file extension has to be .php not .html .

Lukas

btw: you mixed the links ;) mine was email-form-2.html and i_m_aamirs is email-form.html
Aamir SaeedCommented:
lucki_luke: is right

->The problem with your other form (i_m_aamirs approach) is that the file extension has to be .php not .html .

I think you are facing problem in using my code. If you would like i can configure this on your site.

For this you have to send me FTP Info.

ucitianz@yahoo.com

BOL!
SideasAuthor Commented:
I think i have amended them both correctly, now i get an error like so.

Warning: main(class.phpmailer.php): failed to open stream: No such file or directory in /data/webroot/default/Email-form/email.php on line 4
Fatal error: main(): Failed opening required 'class.phpmailer.php' (include_path='.:') in /data/webroot/default/Email-form/email.php on line 4

Think this is down to my URL or something. I guess this is quite hard.

Thanks for the offer ucitianz i cannot get you FTP access, company would not let it happen. Hopefully you guys can figure it out from there!
lucki_lukeCommented:
No, not hard.
Well this is because your phpmailer class is in a different directory, so you should write instead of
require("class.phpmailer.php");

require("phpmailer/class.phpmailer.php");

as your phpmailer stuff is in this directory.
SideasAuthor Commented:
Hi,

Changed this, error on line 35 now

Parse error: parse error, unexpected $ in /data/webroot/default/Email-form/email.php on line 35

Sorry about this!
lucki_lukeCommented:
Hm shouldnt be... (i dont get this error)

your email.php should look like this:

<?php
// every input inside the form is now available in the $_POST variable (except the file)

require("phpmailer/class.phpmailer.php");

$attachment = false;
if($_FILES['cv']['name'] != ''){ // accidentally i mixed the operators in previous code
     $uploaddir = '/var/www/uploads/';
     $uploadfile = $uploaddir . basename($_FILES['cv']['name']);
     
     if (move_uploaded_file($_FILES['cv']['tmp_name'], $uploadfile)) {
          // everything worked fine up to now
          $attachment = true;
     } else {
          // somethings wrong
          echo "Failed uploading file!";
     }
}

$mail = new PHPMailer();

$mail->From     = $_POST['email'];
$mail->FromName = $_POST['name'];
$mail->Mailer   = "mail";
$mail->AddAddress("yourname@site.com", "Receiver");
$mail->Subject = $_POST['subject'];
$mail->Body    = $_POST['body'];
if($attachment === true)
     $mail->AddAttachment($uploadfile, $_FILES['cv']['name']);
if(!$mail->Send())
{
   echo "There was an error sending the message";
   exit;
}
?>
SideasAuthor Commented:
Hi,

That seems to have fixed it :0) not sure why it wasn't working, code looked the same.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.