Besides using PHP's mail() function, there are a few other tools you can use to send mail from a PHP script. In this article, we'll show you how you can use PHPMailer to to send email from within PHP.

When sending email from PHPMailer, you will be sending email from an actual email address. If you don't already have an email address setup specifically for sending email, please setup an email address now. In the example below, we created the email address send_from_PHPMailer@bradm.inmotionhosting.com with "password" as the password.

Download the PHPMailer script

First, download PHPMailer using the direct link below:

PHPMailer_5.2.0.zip

After you have downloaded the file, unzip and extract it to your public_html. After unzipping the file we have public_html/PHPMailer_5.2.0. Next you will need to edit your web pages to use the PHPMailer code.

Add the HTML form to your page

Generally, your setup would include a form being sent to a PHP script for processing. In this case, there is a basic HTML file, contact_us.html, that makes up a feedback form. You will need to set the action of your form to "email.php" for the PHP script to process. Below is the code you need for the form in your page.

<form method="post" action="email.php">
  Email: <input name="email" id="email" type="text" /><br />

  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />

  <input type="submit" value="Submit" />
</form>

Add the PHP mail() function code

When the form is filled out, the information is passed over to "email.php"', which currently uses PHP's mail() function to send the message. Below is the PHP code that sends the email from the server.

<?php

  $email = $_REQUEST['email'] ;
  $message = $_REQUEST['message'] ;

  // here we use the php mail function
  // to send an email to:
  // you@yourdomain.com
  mail( "bradm@inmotiontesting.com", "Feedback Form Results",$message, "From: $email" );
?>

Add the PHPMailer code to your site

Because we are using the PHPMailer instead of the generic php mail function, we'll begin to update our "email.php" file. If you look in your PHPMailer folder you'll see a README file that includes sample PHP code. The sample PHP code should look like below:

<?php
require("class.PHPMailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "jswan";  // SMTP username
$mail->Password = "secret"; // SMTP password

$mail->From = "from@example.com";
$mail->FromName = "Mailer";
$mail->AddAddress("josh@example.net", "Josh Adams");
$mail->AddAddress("ellen@example.com");                  // name is optional
$mail->AddReplyTo("info@example.com", "Information");

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = "Here is the subject";
$mail->Body    = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";
?>

The great thing about this example is that it includes comments, which explain what most of the code does.

Final Configuration of the PHPMailer code

We've updated the sample code to work with our initial html contact form (first code example on this page). We updated the code to include additional comments, and the final code we used is below:

<?php

// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("lib/PHPMailer/PHPMailerAutoload.php");

$mail = new PHPMailer();

// set mailer to use SMTP
$mail->IsSMTP();

// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost";  // specify main and backup server

$mail->SMTPAuth = true;     // turn on SMTP authentication

// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@bradm.inmotiontesting.com
// pass: password
$mail->Username = "send_from_PHPMailer@bradm.inmotiontesting.com";  // SMTP username
$mail->Password = "password"; // SMTP password

// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;

// below we want to set the email address we will be sending our email to.
$mail->AddAddress("bradm@inmotiontesting.com", "Brad Markle");

// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);

$mail->Subject = "You have received feedback from your website!";

// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body    = $message;
$mail->AltBody = $message;

if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";
?>

So in the test the user first visits contact_us.html. When they fill in their email address and comment, the information is posted to email.php. email.php calls PHPMailer, and then sends us the data that the user submitted.

Note that PHPMailer is very flexible and has more features than described here. For a listing of the optional variables that you can add, you should read the documentation:

http://PHPMailer.sourceforge.net/docs/

Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address
Name

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

Like this Article?

Related Questions

Here are a few questions related to this article that our customers have asked:
PHPMail - Warning: Wrong datatype... /class.phpmailer.php
Would you like to ask a question about this page? If so, click the button below!
Ask a Question
2012-05-02 9:38 am
This was perfectly presented! Thanks, Brad!
n/a Points
2014-03-05 1:00 am

After module installation I can't get the PHPMailer to send any email; always end up with the SMTP -> ERROR: Failed to connect to server: Connection refused (111)can you please help me out from this??

Staff
8,050 Points
2014-03-05 9:23 am
Within your code, be sure that you have properly configured all of the settings such as the SMTP user and password to reflect a valid user that you have created.
n/a Points
2014-03-19 8:55 am

Hi, I just got off a chat session with Nick W.

I am having an issue getting Drupal 7 module PHPMailer working. It used to work before I moved to IMH. We ran through setup, and I ran the configuration test. The connection went through fine, and all reponses were positive, until the actual data was sent.

Following is the end of the communication.

SMTP -> get_lines(): $data was ""SMTP -> get_lines(): $str is "354 Enter message, ending with "." on a line by itself "SMTP -> get_lines(): $data is "354 Enter message, ending with "." on a line by itself "SMTP -> FROM SERVER:354 Enter message, ending with "." on a line by itselfCLIENT -> SMTP: Date: Wed, 19 Mar 2014 08:31:14 -0400CLIENT -> SMTP: Return-Path:CLIENT -> SMTP: To: mbrett5062@hotmail.comCLIENT -> SMTP: From: Log PowerCLIENT -> SMTP: Reply-To: mhooper@logpower.comCLIENT -> SMTP: Subject: PHPMailer test e-mailCLIENT -> SMTP: Message-ID: <731753829fd5d5027d27dbefccda3bd7@logpower.com>CLIENT -> SMTP: X-Priority: 3CLIENT -> SMTP: X-Mailer: PHPMailer 5.2.5 (https://github.com/Synchro/PHPMailer/)CLIENT -> SMTP: X-Mailer: DrupalCLIENT -> SMTP: MIME-Version: 1.0CLIENT -> SMTP: Content-Transfer-Encoding: 8BitCLIENT -> SMTP: Content-Type: text/plain; format=flowed; delsp=yes; charset=UTF-8CLIENT -> SMTP:CLIENT -> SMTP: Your site is properly configured to send e-mails using the *PHPMailer*CLIENT -> SMTP: library.CLIENT -> SMTP:CLIENT -> SMTP: .SMTP -> get_lines(): $data was ""SMTP -> get_lines(): $str is ""SMTP -> get_lines(): $data is ""SMTP -> get_lines(): timed-out (10 seconds)SMTP -> FROM SERVER:SMTP -> ERROR: DATA not accepted from server:

Staff
8,050 Points
2014-03-19 9:10 am
Your error appears to be related to the connection to the defined SMTP host timing out. Within your script, what do you have defined as the host?
n/a Points
2014-03-19 9:18 am

You can ignore my previous comment. Although the communication was saying server not accepting data, the mail was sent. Everything appears to be working on the site now.

Thanks anyway.

n/a Points
2014-03-25 8:58 am

I need help please, I get the following alert when I try to send an email in the same code

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

<?php

require("/home/drinkinc/public_html/testmail/PHPMailer_v5.1/class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP

$mail->Host = "locaalhost"; // specify main and backup server

$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = "user@example.com"; // SMTP username

$mail->Password = "password"; // SMTP password

$mail->From = "user@example.com";

$mail->FromName = "User";

$mail->AddAddress($_POST['sender_email']); // name is optional

$mail->WordWrap = 50; // set word wrap to 50 characters

$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Here is the subject";

$mail->Body = "This is the HTML message body <b>in bold!</b>";

$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())

{

echo "Message could not be sent. <p>";

echo "Mailer Error: " . $mail->ErrorInfo;

exit;

}

echo "Message has been sent";

?>

Mailer Error: SMTP Error: Could not connect to SMTP host.

Staff
9,962 Points
2014-03-25 9:36 am
Hello dor,

I had to modify the code in your comment before allowing it to go public as you had your email information typed in. But it looks like more than likely the problem you're encountering is coming from this line:

$mail->Host = "locaalhost";



It looks like you have an extra a in the server name, as it it should read:

$mail->Host = "localhost";



A PHP script should understand that when you use localhost in your code you are referring to connecting to the same server the script is running on. But with it mistyped, it would literally try to go out and find a server named locaalhost on the Internet but would be unable to connect to it.

Please let us know if correcting that line fixes this problem for you.

- Jacob
n/a Points
2014-04-11 7:59 am

Please Help, I get this alert after execution.

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

<?php

 

$email = $_REQUEST['email'] ;

$message = $_REQUEST['message'] ;

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

$mail = new PHPMailer();

$mail->IsSMTP();

$mail->Host = "localhost";  

$mail->SMTPAuth = true;     

$mail->Username = "mysite@gmail.com";  // SMTP username

$mail->Password = "password"; // SMTP password

$mail->From = $email;

$mail->AddAddress($email, "MySite");

$mail->WordWrap = 50;// set word wrap to 50 characters

$mail->IsHTML(true);// set email format to HTML

$mail->Subject = "You have received feedback from your website!";

$mail->Body    = $message;

$mail->AltBody = $message;

if(!$mail->Send())

{

   echo "Message could not be sent. <p>";

   echo "Mailer Error: " . $mail->ErrorInfo;

   exit;

}

echo "Message has been sent";

?>

Staff
8,253 Points
2014-04-11 10:57 am
Hello Aman,

Thank you for your question. In your script are you updating the following lines with the correct information?

$mail->Host = "localhost";
If you are running the script from a local server, localhost is correct; if you are running the script on a remote server, enter the correct hostname. For example: remote-domain.com

$mail->Username = "mysite@gmail.com"; // SMTP username
Make sure you are putting a valid SMTP username here.

$mail->Password = "password"; // SMTP password
Make sure you are putting a valid SMTP password here, for the email address.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-04-16 3:47 am

Hello John-Paul,

Thanx for your suggestions but these all things are correct in my code. I have put valid gmail Id and its password and i am using this code on Localhost . So i have set firstly 

$mail->Host = "localhost"; 

and thn 

$mail->Host = "smtp.gmail.com";

but error message remains same that is:

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

So what can i do ?

 

Thanks & Regards,

Aman

Staff
9,962 Points
2014-04-16 12:15 pm
Hello Aman,

If you're using Gmail for your mail server then you're going to need to set things up a bit differently.

I'd try these settings:

$mail->SMTPAuth   = true; 
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;


Please let us know if you're still having issues connecting.

- Jacob
n/a Points
2014-05-10 10:33 am

Hi everyone!

I have the same problem - it mean browser give me an error:

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

 

I use free hosting and my file look that:

<code>

class sendMail{    function sendMail()    {        require_once('phpmailerx/class.phpmailer.php');        $tresc = "TEST";        $podpis = "TEST";        $adresat=$email = "pitokarczyk01@outlook.com";                $mail = new PHPMailer();        $mail->IsSMTP(); // send via SMTP        $mail->SMTPAuth = true; // turn on SMTP authentication        $mail->SMTPSecure = "tls/ssl";        $mail->Host = "smtp.gmail.com";        $mail->Port  = 465;        $mail->Mailer= "smtp";        $mail->Username = "pitokarczyk01@gmail.com"; // SMTP username        $mail->Password = "ther is my password for gmail account"; // SMTP password        $mail->AddReplyTo ($email, $podpis);        $mail->From = $email;        $mail->FromName = $podpis;        $mail->Subject = "Ze strony od: $podpis";        $mail->Body = $tresc;        $mail->WordWrap = 50;        $mail->AddAddress ($adresat);//      $mail->IsHTML (true);        $mail->SetLanguage("pl", "phpmailerx/language/");        $mail->CharSet = 'utf-8';        if(!$mail->Send())        { echo "B??d wysy?ania: " . $mail->ErrorInfo; }        else        { echo "Wiadomo?? zosta?a wys?ana."; }            }            }$test = new sendMail();

</code>

 

What i do wrong?

Staff
16,694 Points
2014-05-12 1:38 pm
Hello Wedelek,

In testing your code, the only thing I had to change was the setting you have as SMTPSecure = "tls/ssl". The phpmailer class checks for either tls or ssl, but not both as a single setting.

Kindest Regards,
Scott M
n/a Points
2014-05-11 3:45 am

How to get SMTP username and password?Do we have to purchase it?

Staff
8,253 Points
2014-05-12 8:56 am
Hello me_techguy,

Thank you for your question. The SMTP username is your full email address, and you setup a password when you create the email account.

You can view your email settings in cPanel at any time.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-05-21 7:42 pm

Please Can you tell me is something wrong with this? sometimes it stops workin. and i get complains from customers..

<?php $send_email_to = "******@yahoo.com";function send_email($name,$email,$email_subject,$email_message){  global $send_email_to;    $headers = "MIME-Version: 1.0" . "\r\n";  $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";  $headers .= "From: ".$email. "\r\n";  $message = "<strong>Email = </strong>".$email."<br>";  $message .= "<strong>Name = </strong>".$name."<br>";  $message .= "<strong>Message = </strong>".$email_message."<br>";  @mail($send_email_to, $email_subject, $message,$headers);  return true;}function validate($name,$email,$message,$subject){  $return_array = array();  $return_array['success'] = '1';  $return_array['name_msg'] = '';  $return_array['email_msg'] = '';  $return_array['message_msg'] = '';  $return_array['subject'] = ''; if($email == '')  {    $return_array['success'] = '0';    $return_array['email_msg'] = 'email is required';  }  else  {    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';    if(!preg_match($email_exp,$email)) {      $return_array['success'] = '0';      $return_array['email_msg'] = 'enter valid email.';      }  }  if($name == '')  {    $return_array['success'] = '0';    $return_array['name_msg'] = 'name is required';  }  else  {     $string_exp = "/^[A-Za-z .'-]+$/";    if (!preg_match($string_exp, $name)) {      $return_array['success'] = '0';     $return_array['name_msg'] = 'enter valid name.';    }  }  if($subject == '')  {    $return_array['success'] = '0';    $return_array['subject_msg'] = 'subject is required';  }    if($message == '')  {    $return_array['success'] = '0';    $return_array['message_msg'] = 'message is required';  }  else  {    if (strlen($message) < 2) {      $return_array['success'] = '0';      $return_array['message_msg'] = 'enter valid message.';    }  }  return $return_array;}$name = $_POST['name'];$email = $_POST['email'];$message = $_POST['message'];$subject = $_POST['subject'];$return_array = validate($name,$email,$message,$subject);if($return_array['success'] == '1'){  send_email($name,$email,$subject,$message);}header('Content-type: text/json');echo json_encode($return_array);die();?>

AND THIS IS THE HTML

 

<fieldset id="contact_form">          <div id="msgs"> </div>          <form id="cform" name="cform" method="post" action="">            <input type="text" id="name" name="name" value="Full Name*" onfocus="if(this.value == 'Full Name*') this.value = ''"                            onblur="if(this.value == '') this.value = 'Full Name*'" />            <input type="text" id="email" name="email" value="Email Address*" onfocus="if(this.value == 'Email Address*') this.value = ''"                            onblur="if(this.value == '') this.value = 'Email Address*'" />            <input type="text" id="subject" name="subject" value="Subject*" onfocus="if(this.value == 'Subject*') this.value = ''"                            onblur="if(this.value == '') this.value = 'Subject*'" />            <textarea id="message" name="message" onfocus="if(this.value == 'Your Message*') this.value = ''"                            onblur="if(this.value == '') this.value = 'Your Message*'">Your Message*</textarea>            <button id="submit" class="button"> Send Message</button>          </form>        </fieldset>

Staff
9,962 Points
2014-05-21 7:46 pm
Hello Dorene,

If the form works for the most part, but sometimes appears to not be sending you messages, I'd guess that more than likely it's a problem with you trying to deliver directly to a free @yahoo.com account.

These PHP mails could be getting filtered as spam by Yahoo or at least greylisted in which they aren't accepted the first time through. I would recommend trying to change the address the PHP form is being sent to, to a email address that is locally on the same domain that your PHP mailer is on to rule out any email deliverability issues.

Please let us know if you continue to have problems.

- Jacob
n/a Points
2014-05-22 10:07 am

Thank you Jacob, Thats what i thought about bafore but your explanation helped a lot! please do you know by any chance how to add the phone number to the contact form? that would help more!!

Staff
8,050 Points
2014-05-22 10:14 am
To do so, you would simply add another filed within your code with this information on it. You could simply copy it from another field that you already have defined and just change the value and id on it.
n/a Points
2014-05-22 7:29 pm

excuse me, but i asked Jacob?  and i know i should add some lines on the html and php. thats weird

Staff
15,973 Points
2014-05-22 9:28 pm
Hello Dorene,

Thanks for the question. The Community Support Staff will answer all questions as each of us has a different schedule in providing support for the comments and questions that appear on our support site. What Jeff says is also correct - you can simply duplicate a field but change the variable name for the purpose of using it for the phone number. For example:

Phone:<input name="phone" id="phone" type="text"/><br />

Then, in the PHP code you need to make sure that the names of the fields are the same as what you put in the form, otherwise it will not gather the information properly.

$phoneField = $_POST ['phone'];

Hopefully, this will provide the information that you need.

Regards,
Arnel C.
n/a Points
2014-05-26 3:00 am

I use filezilla to upload files into my server with encryption as Require FTP over TLS

I have a email address called idaarah@maahireen.com

Alhamdulillah in Microsoft Office Outlook 2007 i use to send & receive emails perfectly with the setup given below for idaarah@maahireen.com:

Incoming mail server: pop.maahireen.com

Outgoing mail server: smtp.maahireen.com

Uder More Settings>Outgoing Server

I have ticked the checkbox My outgoing server SMTP requires authentication. And also have ticked a radio box Use same setting as my incoming mail server.

Under Advanced->Server Port numbers

Incoming server (POP3)=110

Not ticked the checkbox This server requires a encrypted connection (SSL).

Outging server SMTP=25

A dropdown menu Use the following type of encrypted connection=None

I have a domain called maahireen.com

I want to receive email from form entry & file upload from my website.

I get codes from http://www.formmail-maker.com/generator.php

I download a folder it and got a zip folder. I unzip it.

I contains some php files in it. I rename the folder to studentsexamresult .

I opened form.lib.php and make few changes in smtp & upload a folder.

When the form is filled & submitted i receive it in the server. But i donot got mail idaarah@maahireen.com & error comes could not connect to smtp host.

I am publishing the codes but with changed password. I have a request to you for the help. Where i am wrong & what correction i should do. Please help.

the code are below:

form.lib.php

<?php# PHPFMG_ID:'20140525-8200'# Date : 20140525 13:28:42# Generated By Free PHP Formmail Generator : http://phpfmg.sourceforge.net# -----------------------------------------------------------------------------define( 'PAYPAL_ID' , '' ); // Put donation ID here to disable the bottom backlinkdefine( 'PHPFMG_TO' , 'idaarah@maahireen.com' );define( 'PHPFMG_REDIRECT', '' ); define( 'PHPFMG_ID' , '20140525-8200' ); define( 'PHPFMG_ROOT_DIR' , dirname(__FILE__) );define( 'PHPFMG_SAVE_FILE' , PHPFMG_ROOT_DIR . '/form-data-log.php' ); // save submitted data to this filedefine( 'PHPFMG_EMAILS_LOGFILE' , PHPFMG_ROOT_DIR . '/email-traffics-log.php' ); // log email traffics to this fileif( !defined('PHPFMG_ADMIN_URL') ) define( 'PHPFMG_ADMIN_URL' , 'admin.php' ); // might be defined already by wordpress form loader plugindefine( 'PHPFMG_SAVE_ATTACHMENTS' , '' );define( 'PHPFMG_SAVE_ATTACHMENTS_DIR' , PHPFMG_ROOT_DIR . '/uploaded/' );// three options : empty - always mail file as attachment, 0 - always mail file as link, N - mail file as link if filesize larger than N Kilobytesdefine( 'PHPFMG_FILE2LINK_SIZE' , '' );define( 'PHPFMG_UPLOAD_CONTROL' , 'deny' );define( 'PHPFMG_HARMFUL_EXTS' , ".php, .html, .css, .js, .exe, .com, .bat, .vb, .vbs, scr, .inf, .reg, .lnk, .pif, .ade, .adp, .app, .bas, .chm, .cmd, .cpl, .crt, .csh, .fxp, .hlp, .hta, .ins, .isp, .jse, .ksh, .Lnk, .mda, .mdb, .mde, .mdt, .mdw, .mdz, .msc, .msi, .msp, .mst, .ops, .pcd, .prf, .prg, .pst, .scf, .scr, .sct, .shb, .shs, .url, .vbe, .wsc, .wsf, .wsh" );define( 'PHPFMG_HARMFUL_EXTS_MSG' , 'File is potential harmful. Upload is not allowed.' );define( 'PHPFMG_ALLOW_EXTS' , ".jpg, .gif, .png, .bmp" );define( 'PHPFMG_ALLOW_EXTS_MSG' , "Upload is not allowed. Please check your file type." );define( 'PHPFMG_SUBJECT' , "Form for sending file upload for STUDENTS ONLINE EXAM RESULT DATA ENTRY PACKAGE:" );define( 'PHPFMG_CC' , '' );define( 'PHPFMG_BCC', '' );// for auto-response emaildefine( 'PHPFMG_RETURN_ENABLE' , 'Y' );  // 'Y' to enable auto-response email, use '' or 'N' to turn offdefine( 'PHPFMG_YOUR_NAME' , '' ); // name of auto-response mail addressdefine( 'PHPFMG_RETURN_EMAIL' , "" );  define( 'PHPFMG_RETURN_SUBJECT' , "" ); // auto-response mail subjectdefine( 'PHPFMG_RETURN_NO_ATTACHMENT' , '' ); // Y - No attachements will be included for auto-response emaildefine( 'PHPFMG_CHARSET' , 'UTF-8' );define( 'PHPFMG_MAIL_TYPE' , 'text' ); // send mail in html format or plain text.define( 'PHPFMG_ACTION' , 'mailandfile' ); // delivery methoddefine( 'PHPFMG_TEXT_ALIGN' , 'top' ); // field label text alignment: top, right, leftdefine( 'PHPFMG_NO_FROM_HEADER' , '' ); // don't make up From: header.define( 'PHPFMG_SENDMAIL_FROM' , '' ); // force sender's email define( 'PHPFMG_USE_PHPMAILER' , 'Y' ); // Y - use phpmailer as the default// smtp optionsdefine( 'PHPFMG_USE_SMTP' , 'Y' ); // Y - enabledefine( 'PHPFMG_SMTP_HOST' , 'mail.maahireen.com' );define( 'PHPFMG_SMTP_USER' , 'idaarah@maahireen.com' );define( 'PHPFMG_SMTP_PASSWORD' , 'changed password' );define( 'PHPFMG_SMTP_PLAIN_PASSWORD' , '' ); // use this to overwrite above passworddefine( 'PHPFMG_SMTP_PORT' , '25' ); // default 25, use 465 for gmaildefine( 'PHPFMG_SMTP_SECURE' , '' );define( 'PHPFMG_SMTP_DEBUG_LEVEL' , '' ); // empty or 0 - trun off debugif( !class_exists('PHPMailer') && file_exists(PHPFMG_ROOT_DIR.'/phpmailer.php') ){    include_once( PHPFMG_ROOT_DIR.'/phpmailer.php' ); }; define( 'PHPFMG_SIMPLE_CAPTCHA_NAME' , phpfmg_captcha_name() ); // comment this line if you want to disable the simple built-in captcha codedefine( 'HOST_NAME',getEnv( 'SERVER_NAME' ) );define( 'PHP_SELF', getEnv( 'SCRIPT_NAME' ) );define( 'PHPFMG_LNCR', phpfmg_linebreak() );define( 'PHPFMG_ANTI_HOTLINKING' , '' );define( 'PHPFMG_REFERERS_ALLOW', "" ); // Referers - domains/ips that you will allow forms to reside on.define( 'PHPFMG_REFERERS_DENIED_MSG', "You are coming from an <b>unauthorized domain.</b>" ); define( 'PHPFMG_ONE_ENTRY' , '' );define( 'PHPFMG_ONE_ENTRY_METHOD' , '' );phpfmg_init();# -----------------------------------------------------------------------------function phpfmg_thankyou(){    phpfmg_redirect_js();?><!-- [Your confirmation message goes here] -->    <BR>    <b><BR><B STYLE="GREEN">Alhamdulillah! your form has been sent.<BR>Jazaakallah!<BR><BR><B STYLE="BROWN">Support Department.<br>Maahireen</b><br><br>You can close this window.</b>    <br><br><?php} // end of function phpfmg_thankyou()function phpfmg_auto_response_message(){    ob_start();?><?php    $msg = ob_get_contents() ;    ob_end_clean();    return trim($msg);}function phpfmg_mail_template(){    ob_start();?><?php    $msg = ob_get_contents() ;    ob_end_clean();    return trim($msg);}# --- Array of Form Elements ---$GLOBALS['form_mail'] = array();$GLOBALS['form_mail']['field_0'] = array( "name" => "field_0", "text" => "Enter correct Listing Account Account Number-",  "type" => "text", "instruction" => "", "required" => "Required" ) ;$GLOBALS['form_mail']['field_1'] = array( "name" => "field_1", "text" => "Upload STUDENTS ONLINE EXAM RESULT DATA ENTRY PACKAGE file:",  "type" => "attachment", "instruction" => "", "required" => "Required" ) ;$GLOBALS['form_mail']['field_2'] = array( "name" => "field_2", "text" => "Message:",  "type" => "textarea", "instruction" => "You may type your name, mobile no., address, email, message etc. in the box.", "required" => "" ) ;?><?php/** * GNU Library or Lesser General Public License version 2.0 (LGPLv2)*/function phpfmg_init(){  error_reporting( E_ERROR );  ini_set('magic_quotes_runtime', 0);  ini_set( 'max_execution_time', 0 );  ini_set( 'max_input_time', 36000 );    session_start();    if( !isset($_SESSION['HTTP_REFERER']) )    $_SESSION['HTTP_REFERER'] = $_SERVER['HTTP_REFERER'] ;  phpfmg_check_referers();  if ( get_magic_quotes_gpc() && isset($_POST) ) {      phpfmg_stripslashes( $_POST );  };  }function phpfmg_stripslashes(&$var){    if(!is_array($var)) {        $var = stripslashes($var);    } else {        array_walk($var,'phpfmg_stripslashes');    };}function phpfmg_display_form( $title="", $keywords="", $description="" ){    @header( 'Content-Type: text/html; charset=' . PHPFMG_CHARSET );    $phpfmg_send = phpfmg_sendmail( $GLOBALS['form_mail'] ) ;    $isHideForm  = isset($phpfmg_send['isHideForm']) ? $phpfmg_send['isHideForm'] : false;    $sErr        = isset($phpfmg_send['error'])      ? $phpfmg_send['error']      : '';    # FormMail main()    phpfmg_header( $title, $keywords, $description );    if( !$isHideForm ){        phpfmg_form($sErr);    }else{        phpfmg_thankyou();    };    phpfmg_footer();        return;}function phpfmg_linebreak(){    $os = strtolower(PHP_OS);    switch( true ){        case ("\\" == DIRECTORY_SEPARATOR) : // windows            return "\x0d\x0a" ;         case ( strpos($os, 'darwin') !== false ) : // Mac            return "\x0d" ;        default :             return "\x0a" ; // *nix    };}function phpfmg_sendmail( &$form_mail ) {    if( !isset($_POST["formmail_submit"]) ) return ;    $isHideForm = false ;    $sErr = checkPass($form_mail);        $err_captcha = phpfmg_check_captcha();    if( $err_captcha != '' ){        $sErr['fields'][] = 'phpfmg_captcha';        $sErr['errors'][] = ERR_CAPTCHA;    };        if( empty($sErr['fields']) && phpfmg_has_entry() ){        $sErr['fields'][] = 'phpfmg_found_entry';        $sErr['errors'][] = 'Found entry already!';    };    if( empty($sErr['fields']) ){                sendFormMail( $form_mail, PHPFMG_SAVE_FILE ) ;        $isHideForm = true;        // move the redirect to phpfmg_thankyou() to get around the redirection within an iframe problem        /*        $redirect = PHPFMG_REDIRECT;        if( strlen(trim($redirect)) ):            header( "Location: $redirect" );            exit;        endif;        */    };     return array(        'isHideForm' => $isHideForm,        'error'      => $sErr ,            ); }function phpfmg_has_entry(){    if( !file_exists(PHPFMG_SAVE_FILE) ){        return false; // has nothing to check    };        $found = false ;    if( defined('PHPFMG_ONE_ENTRY') && 'Y' == PHPFMG_ONE_ENTRY ){        $query = defined('PHPFMG_ONE_ENTRY_METHOD') && PHPFMG_ONE_ENTRY_METHOD == 'email' && isset($GLOBALS['sender_email'])  ? $GLOBALS['sender_email'] : $_SERVER['REMOTE_ADDR'] ;        if( empty($query) )            return false ;                    $GLOBALS['OneEntry'] = $query;                    $query = '"'. strtolower($query) . '"';         $handle = fopen(PHPFMG_SAVE_FILE,'r');        if ($handle) {           while (!feof($handle)) {               $entry = strtolower(fgets($handle, 4096));               if( strpos($entry,$query) !== false ){                    $found = true ;                    break;               };           };           fclose($handle);        };    };     return $found ;            }function    sendFormMail( $form_mail, $sFileName = ""  ) {     $to        = filterEmail(PHPFMG_TO) ;    $cc        = filterEmail(PHPFMG_CC) ;    $bcc       = filterEmail(PHPFMG_BCC) ;        // simply chop email address to avoid my website being abused    if( false !== strpos( strtolower($_SERVER['HTTP_HOST']),'formmail-maker.com') ){        $cc   = substr($cc, 0, 50);        $bcc = substr($bcc,0, 50);    };                $subject   = PHPFMG_SUBJECT ;     $from      = $to ;    $fromName  = "";    $titleOfSender = '';    $firstName  = "";    $lastName  = "";        $strip     = get_magic_quotes_gpc() ;    $content   = '' ;     $style     = 'font-family:Verdana, Arial, Helvetica, sans-serif; font-size : 13px; color:#474747;padding:6px;border-bottom:1px solid #cccccc;' ;    $tr        = array() ; // html table    $csvValues = array();    $cols      = array();    $replace   = array();    $RecordID  = phpfmg_getRecordID();    $isWritable = is_writable( dirname(PHPFMG_SAVE_ATTACHMENTS_DIR) );                  foreach( $form_mail as $field ){        $field_type = strtolower($field[ "type" ]);        if( 'sectionbreak' == $field_type ){            continue;        };                $field[ "text" ] = stripslashes( $field[ "text" ] );         //$value    = trim( $_POST[ $field[ "name" ] ] );        $value = phpfmg_field_value( $field[ "name" ] );         $value    = $strip ? stripslashes($value) : $value ;        if( 'attachment' == $field_type ){            $value = $isWritable ? phpfmg_file2value( $RecordID, $_FILES[ $field[ "name" ] ] ) : $_FILES[ $field[ "name" ] ]['name'];            //$value = $_FILES[ $field[ "name" ] ]['name'];        };        $content    .= $field[ "text" ] . " \t : " . $value .PHPFMG_LNCR;        $tr[]        = "<tr> <td valign=top style='{$style};width:33%;border-right:1px solid #cccccc;'>" . $field[ "text" ] . "&nbsp;</td> <td valign=top style='{$style};'>" . nl2br($value) . "&nbsp;</td></tr>" ;          $csvValues[] = csvfield( $value );        $cols[]      = csvfield( $field[ "text" ] );        $replace["%".$field[ "name" ]."%"] = $value;                switch( $field_type ){            case "sender's email" :                $from = filterEmail($value) ;                break;            case "sender's name" :                $fromName = filterEmail($value) ;                break;            case "titleofsender" :                $titleOfSender = $value ;                break;            case "senderfirstname" :                $firstName = filterEmail($value) ;                break;            case "senderlastname" :                $lastName = filterEmail($value) ;                break;            default :                // nothing                            };             }; // for        $isHtml = 'html' == PHPFMG_MAIL_TYPE ;         if( $isHtml ) {        $content = "<table cellspacing=0 cellpadding=0 border=0 >" . PHPFMG_LNCR . join( PHPFMG_LNCR, $tr ) . PHPFMG_LNCR . "</table>" ;     };            if( !empty($firstName) && !empty($lastName) ){        $fromName = $firstName . ' ' . $lastName;     };            $fromHeader = filterEmail( ('' != $fromName ? "\"$fromName\"" : '' ) . " <{$from}>",array(",", ";")) ; // no multiple emails are allowed.        $_fields = array(        '%NameOfSender%' => $fromName,        '%FirstNameOfSender%' => $firstName,        '%LastNameOfSender%' => $lastName,        '%EmailOfSender%' => $from,        '%TitleOfSender%' => $titleOfSender,        '%DataOfForm%'   => $content,        '%IP%'   => $_SERVER['REMOTE_ADDR'],        '%Date%'   => date("Y-m-d"),        '%Time%'   => date("H:i:s"),        '%HTTP_HOST%' => $_SERVER['HTTP_HOST'],        '%FormPageLink%' => phpfmg_request_uri(),        '%HTTP_REFERER%' => $_SESSION['HTTP_REFERER'],         '%AutoID%' => $RecordID,        '%FormAdminURL%' => phpfmg_admin_url()    );    $fields = array_merge( $_fields, $replace );        $esh_mail_template = trim(phpfmg_mail_template());     if( !empty($esh_mail_template) ){        $esh_mail_template = phpfmg_adjust_template($esh_mail_template);        $content = phpfmg_parse_mail_body( $esh_mail_template, $fields );    };    $subject = phpfmg_parse_mail_body( $subject, $fields );        if( $isHtml ) {        $content = phpfmg_getHtmlContent( $content );    };    $oldMask = umask(0);    //$sep = ','; //chr(0x09);    $sep = chr(0x09);    $recordCols = phpfmg_data2record( csvfield('RecordID') . $sep . csvfield('Date') . $sep . csvfield('IP') . $sep . join($sep,$cols) );     $record     = phpfmg_data2record( csvfield($RecordID) . $sep . csvfield(date("Y-m-d H:i:s")) . $sep . csvfield($_SERVER['REMOTE_ADDR']) .$sep . join($sep,$csvValues) );    /*    Some hosting companies (like Yahoo and GoDaddy) REQUIRED a registered email address to send out all emails!    The mailer HAS to use the REGISTERED email address as the sender's email address. This is called the sendmail_from.    */    $sendmail_from = $from;    $sender_email  = $from;    $force_sender = defined('PHPFMG_SENDMAIL_FROM') && '' != PHPFMG_SENDMAIL_FROM ;     if( $force_sender ){        ini_set("sendmail_from", PHPFMG_SENDMAIL_FROM);         $sendmail_from = PHPFMG_SENDMAIL_FROM;    };    if( defined('PHPFMG_SMTP') && '' != PHPFMG_SMTP ){        ini_set("SMTP", PHPFMG_SMTP);     };    switch( strtolower(PHPFMG_ACTION) ){        case 'fileonly' :               appendToFile( $sFileName, $record, $recordCols );               break;         case 'mailonly' :              mailAttachments( $to , $subject , $content, $sendmail_from, $fromName, $fromHeader,  $cc , $bcc, PHPFMG_CHARSET ) ;               break;        case 'mailandfile' :        default:              mailAttachments( $to , $subject , $content, $sendmail_from, $fromName, $fromHeader,  $cc , $bcc, PHPFMG_CHARSET ) ;              appendToFile( $sFileName, $record, $recordCols );    }; // switch     mailAutoResponse( $sender_email, $force_sender ? $sendmail_from : $to, $fields ) ;    umask($oldMask);        session_destroy();    session_regenerate_id(true);} function phpfmg_file2value( $recordID, $file ){    $tmp  = $file[ "tmp_name" ] ;     $name = phpfmg_rename_harmful(trim($file[ "name" ])) ;     if( !defined('PHPFMG_FILE2LINK_SIZE') ){        return $name;    };        if( is_uploaded_file( $tmp ) ) {        $size = trim(PHPFMG_FILE2LINK_SIZE) ;        switch( $size ){            case '' :                return $name;            default:                $isHtml = 'html' == PHPFMG_MAIL_TYPE;                $filelink= base64_encode( serialize(array('recordID'=>$recordID, 'filename'=>$name)) );                $url = phpfmg_admin_url() . "?mod=filman&func=download&filelink=" . urlencode($filelink) ;                $isLarger = (filesize($tmp)/1024) > $size ;                $link = $isHtml ? "<a href='{$url}'>$name</a>" : $name . " ( {$url} )";                return $isLarger ? $link : $name ; // email download link when size is larger defined size, otherwise send as attachment         };// switch    }; // if        return $name;}function phpfmg_dir2unix( $dir ){    return str_replace( array("\\", '//'), '/', $dir );}function phpfmg_request_uri(){    $uri = getEnv('REQUEST_URI'); // apache has this    if( false !== $uri && strlen($uri) > 0 ){        return $uri ;    } else {            $uri = ($uri = getEnv('SCRIPT_NAME')) !== false                ? $uri                : getEnv('PATH_INFO') ;        $qs = getEnv('QUERY_STRING'); // IIS and Apache has this        return $uri . ( empty($qs) ? '' : '?' . $qs );        };    return "" ;}// parse full admin url to view large size uploaded file onlinefunction phpfmg_admin_url(){    $http_host = "http://{$_SERVER['HTTP_HOST']}";    switch( true ){        case (0 === strpos(PHPFMG_ADMIN_URL, 'http://' )) :            $url = PHPFMG_ADMIN_URL;            break;        case ( '/' == substr(PHPFMG_ADMIN_URL,0,1) ) :            $url = $http_host . PHPFMG_ADMIN_URL ;            break;        default:            $uri = phpfmg_request_uri();            $pos = strrpos( $uri, '/' );            $vdir = substr( $uri, 0, $pos );            $url  = $http_host . $vdir . '/' . PHPFMG_ADMIN_URL ;    };    return $url;}function phpfmg_ispost(){    return 'POST' == strtoupper($_SERVER["REQUEST_METHOD"])  || 'POST' == strtoupper(getEnv('REQUEST_METHOD'))  ;}function phpfmg_is_mysite(){    return false !== strpos( strtolower($_SERVER['HTTP_HOST']),'formmail-maker.com'); // accessing form at mysite}// don't allow hotlink form to my website. To avoid people create phishing form. function phpfmg_hotlinking_mysite(){    $yes = phpfmg_is_mysite()            && ( empty($_SERVER['HTTP_REFERER']) || false === strpos( strtolower($_SERVER['HTTP_REFERER']),'formmail-maker.com') ) ; // doesn't have referer of mysite    if( $yes ){        die( "<b>Access Denied.</b>        <br><br>        You are visiting a form hotlinkink from <a href='http://www.formmail-maker.com'>formmail-maker.com</a> which is not allowed.         Please read the <a href='http://www.formmail-maker.com/web-form-mail-faq.php'>FAQ</a>.           " );    }; }function phpfmg_check_referers(){    phpfmg_hotlinking_mysite(); // anti phishing        $debugs = array();    $debugs[] = "Your IP: " . $_SERVER['REMOTE_ADDR'];    $debugs[] = "Referer link: " . $_SERVER['HTTP_REFERER'];    $debugs[] = "Host of referer: $referer";        $check = defined('PHPFMG_ANTI_HOTLINKING') && 'Y' == PHPFMG_ANTI_HOTLINKING;    if( !$check ) {        $debugs[] = "Referer is empty. No need to check hot linking.";        //echo "<pre>" . join("\n",$debugs) . "</pre>\n";        //appendToFile( PHPFMG_EMAILS_LOGFILE, date("Y-m-d H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . " \n" .  join("\n",$debugs)  ) ;            return true;    };    // maybe post from local file    if( !isset($_SERVER['HTTP_REFERER']) && phpfmg_ispost() ){        appendToFile( PHPFMG_EMAILS_LOGFILE, date("Y-m-d H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . " \n phpfmg_ispost " .  join("\n",$debugs)  ) ;            die( PHPFMG_REFERERS_DENIED_MSG );    };          $url     = parse_url($_SERVER['HTTP_REFERER']);    $referer = str_replace( 'www.', '', strtolower($url['host']) );    if( empty($referer) ) {        return true;    };        $hosts   = explode(',',PHPFMG_REFERERS_ALLOW);    $http_host =  strtolower($_SERVER['HTTP_HOST']);    $referer = $http_host ;     $hosts[] = str_replace('www.', '', $http_host );    $debugs[] = "Hosts Allow: " . PHPFMG_REFERERS_ALLOW;        $allow = false ;    foreach( $hosts as $host ){        $host = strtolower(trim($host));        $debugs[] = "check host: $host " ;        if( false !== strpos($referer, $host) || false !== strpos($referer, 'www.'.$host) ){            $allow = true;            $debugs[] = " -> allow (quick exit)";             break;        }else{            $debugs[] = " -> deny";         };    };        //echo "<pre>" . join("\n",$debugs) . "</pre>\n";    //appendToFile( PHPFMG_EMAILS_LOGFILE, date("Y-m-d H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . " \n" .  join("\n",$debugs)  ) ;            if( !$allow ){        die( PHPFMG_REFERERS_DENIED_MSG );    };}function phpfmg_getRecordID(){    if( !isset($GLOBALS['RecordID']) ){        $GLOBALS['RecordID'] = date("Ymd") . '-'.  substr( md5(uniqid(rand(), true)), 0,4 );    };    return $GLOBALS['RecordID'];}function phpfmg_data2record( $s, $b=true ){    $from = array( "\r", "\n");     $to   = array( "\\r", "\\n" );    return $b ? str_replace( $from, $to, $s ) : str_replace( $to, $from, $s ) ; }function csvfield( $str ){    $str = str_replace( '"', '""', $str );    return '"' . trim($str) . '"';}                                                                                                                                                                                   function    mailAttachments( $to = "" , $subject = "" , $message = "" , $from="", $fromName = "" , $fromHeader ="", $cc = "" , $bcc = "", $charset = "UTF-8", $type = 'FormMail' ){          if( ! strlen( trim( $to ) ) ) return "Missing \"To\" Field." ;     $isAutoResponse = $type == 'AutoResponseEmail' ;    // added PHPMailer SMTP support at Mar 12, 2011    $isSMTP = defined('PHPFMG_USE_SMTP') && 'Y' == PHPFMG_USE_SMTP && defined('PHPFMG_SMTP_HOST') && '' != PHPFMG_SMTP_HOST;        // due to security issues, in most case, the smtp will fail on my website. It only works on user's own server    // so just disable the smtp here      if( phpfmg_is_mysite() ){        $isSMTP = false ;    };        $attachments = array();    $noAutoAttachements = $isAutoResponse && defined('PHPFMG_RETURN_NO_ATTACHMENT') && 'Y' == PHPFMG_RETURN_NO_ATTACHMENT ;     $use_phpmailer = defined('PHPFMG_USE_PHPMAILER') && 'Y' == PHPFMG_USE_PHPMAILER ;     $boundary = "====_My_PHP_Form_Generator_" . md5( uniqid( srand( time() ) ) ) . "====";      $content_type = 'html' == PHPFMG_MAIL_TYPE ? "text/html" : "text/plain" ;         // setup mail header infomation     $headers =  'Y' == PHPFMG_NO_FROM_HEADER ? '' :  "From: {$fromHeader}" .PHPFMG_LNCR;    if ($cc) $headers .= "CC: $cc".PHPFMG_LNCR;      if ($bcc) $headers .= "BCC: $bcc".PHPFMG_LNCR;      //$headers .= "Content-type: {$content_type}; charset={$charset}" .PHPFMG_LNCR ;     $plainHeaders = $headers ; // for no attachments header    $plainHeaders .= 'MIME-Version: 1.0' . PHPFMG_LNCR;    $plainHeaders .= "Content-type: {$content_type}; charset={$charset}" ;        //create mulitipart attachments boundary     $sError = "" ;     $nFound = 0;     if( false && isset($GLOBALS['phpfmg_files_content']) && '' != $GLOBALS['phpfmg_files_content'] ){                // use previous encoded content        $sEncodeBody = $GLOBALS['phpfmg_files_content'] ;        $nFound = $GLOBALS['phpfmg_nFound'] ;            }else{        $file2link_size = trim(PHPFMG_FILE2LINK_SIZE) ;        $isSave = ('' != $file2link_size || defined('PHPFMG_SAVE_ATTACHMENTS') && 'Y' == PHPFMG_SAVE_ATTACHMENTS);        if( $isSave ){            if( defined('PHPFMG_SAVE_ATTACHMENTS_DIR') ){                if( !is_dir(PHPFMG_SAVE_ATTACHMENTS_DIR) ){                    $ok = @mkdir( PHPFMG_SAVE_ATTACHMENTS_DIR, 0777 );                    if( !$ok ) $isSave = false;                };            };        };        $isWritable = is_writable( dirname(PHPFMG_SAVE_ATTACHMENTS_DIR) );                  // parse attachments content        foreach( $_FILES as $aFile ){             $sFileName = $aFile[ "tmp_name" ] ;             $sFileRealName = phpfmg_rename_harmful($aFile[ "name" ]) ;             if( is_uploaded_file( $sFileName ) ):                                 $isSkip = '' != $file2link_size && ( (filesize($sFileName)/1024) > $file2link_size );                // save uploaded file                if( $isWritable && $isSave ){                    $tofile = PHPFMG_SAVE_ATTACHMENTS_DIR . phpfmg_getRecordID() . '-' . basename($sFileRealName);                    if( @copy( $sFileName, $tofile) ) {                        $sFileName = $tofile; // to fix problem : in some windows php, the uploaded temp file might not be mailed as attachment                        chmod($tofile,0777);                    };                };                if( $isSkip )                    continue; // mail file as link                                 $attachments[] = array('file' => $sFileName, 'name' => $aFile[ "name" ] );                                if( !$use_phpmailer && !$isSMTP && ($fp = @fopen( $sFileName, "rb" )) ) :                       $sContent = fread( $fp, filesize( $sFileName ) );                    fclose($fp);                     $sFName = basename( $sFileRealName ) ;                     $sMIME = getMIMEType( $sFName ) ;                                          $bPlainText = ( $sMIME == "text/plain" ) ;                     if( $bPlainText ) :                         $encoding = "" ;                     else:                         $encoding = "Content-Transfer-Encoding: base64".PHPFMG_LNCR;                          $sContent = chunk_split( base64_encode( $sContent ) );                      endif;                                          $sEncodeBody .=     PHPFMG_LNCR."--$boundary" .PHPFMG_LNCR.                                          "Content-Type: $sMIME;" .  PHPFMG_LNCR.                                        "\tname=\"$sFName\"" . PHPFMG_LNCR.                                         $encoding .                                          "Content-Disposition: attachment;" . PHPFMG_LNCR.                                          "\tfilename=\"$sFName\"" . PHPFMG_LNCR. PHPFMG_LNCR.                                         $sContent . PHPFMG_LNCR ;                     $nFound ++;                                                                 else:                     $sError .= "<br>Failed to open file $sFileName.\n" ;                 endif; // if( $fp = fopen( $sFileName, "rb" ) ) :                              else:                 $sError .= "<br>File $sFileName doesn't exist.\n" ;             endif; //if( file_exists( $sFileName ) ):         }; // end foreach                 $sEncodeBody .= PHPFMG_LNCR.PHPFMG_LNCR."--$boundary--" ;                 $GLOBALS['phpfmg_files_content'] = $sEncodeBody ;        $GLOBALS['phpfmg_nFound'] = $nFound ;            }; // if        $headers .= "MIME-Version: 1.0".PHPFMG_LNCR."Content-type: multipart/mixed;".PHPFMG_LNCR."\tboundary=\"$boundary\"";      $txtMsg = PHPFMG_LNCR."This is a multi-part message in MIME format." .PHPFMG_LNCR .                PHPFMG_LNCR."--$boundary" .PHPFMG_LNCR .               "Content-Type: {$content_type};".PHPFMG_LNCR.              "\tcharset=\"$charset\"" .PHPFMG_LNCR.PHPFMG_LNCR .                $message . PHPFMG_LNCR;             if( $noAutoAttachements ) $sEncodeBody = '' ;        $body    = $nFound ? $txtMsg . $sEncodeBody : $message ;    $headers = $nFound ? $headers : $plainHeaders ;         $errmsg = "";    if( $isSMTP || $use_phpmailer ){        if( $noAutoAttachements ) $attachments = false ;        $errmsg = phpfmg_phpmailer( $to, $subject, $body, $from, $fromName, $cc  , $bcc , $charset, $attachments );            }else{            if ( !mail( $to, $subject, $body, $headers  ) )            $errmsg = "Failed to send mail";    };    $ok = $errmsg == "" ;    $status = $ok ? "\n[Email sent]" : "\n[{$errmsg}]" ;    phpfmg_log_mail( $to, $subject, ($ok ? 'Email sent' : 'Failed to send mail') . "\n" . ($nFound ? $headers  . $txtMsg : $headers . $message), '', $type . $status ); // no log for attachments         return $sError ;         } function    phpfmg_phpmailer( $to, $subject, $message, $from, $fromName, $cc = "" , $bcc = "", $charset = "UTF-8",$attachments = false ){        $mail             = new PHPMailer();    $mail->Host       = PHPFMG_SMTP_HOST; // SMTP server    $mail->Username   = PHPFMG_SMTP_USER;    $mail->Password   = PHPFMG_SMTP_PLAIN_PASSWORD != '' ? PHPFMG_SMTP_PLAIN_PASSWORD : base64_decode(PHPFMG_SMTP_PASSWORD);    $mail->SMTPAuth   = PHPFMG_SMTP_PASSWORD != "";     $mail->SMTPSecure = PHPFMG_SMTP_SECURE;                     $mail->Port       = PHPFMG_SMTP_PORT == "" ? 25 : PHPFMG_SMTP_PORT;              if( defined('PHPFMG_SMTP_DEBUG_LEVEL') && PHPFMG_SMTP_DEBUG_LEVEL != "" ){        $mail->SMTPDebug  = (int)PHPFMG_SMTP_DEBUG_LEVEL ;     };    $mail->From       = $from;    $mail->FromName   = $fromName;    $mail->Subject    = $subject;    $mail->Body       = $message;    $mail->CharSet = $charset;        if( !phpfmg_is_mysite() && (defined('PHPFMG_USE_SMTP') && 'Y' == PHPFMG_USE_SMTP) ){        $mail->IsSMTP();     };        $mail->IsHTML('html' == PHPFMG_MAIL_TYPE);    $mail->AddAddress($to);        if( ''!= $cc ){        $CCs = explode(',',$cc);        foreach($CCs as $c){            $mail->AddCC( $c );        };    };        if( ''!= $bcc ){        $BCCs = explode(',',$bcc);        foreach($BCCs as $b){            $mail->AddBCC( $b );        };    };          if( is_array($attachments) ){        foreach($attachments as $f){            $mail->AddAttachment( $f['file'], basename($f['name']) );        };    };        return $mail->Send() ? "" : $mail->ErrorInfo;     } function mailAutoResponse( $to, $from, $fields = false ){    if( !formIsEMail($to) ) return ERR_EMAIL ; // one more check for spam robot    $enable = defined('PHPFMG_RETURN_ENABLE') && PHPFMG_RETURN_ENABLE === 'Y';    $body = trim(phpfmg_auto_response_message());    if( !$enable || empty($body) ){       return false ;    };        $subject = PHPFMG_RETURN_SUBJECT;    $isHtml = 'html' == PHPFMG_MAIL_TYPE ;    $body = phpfmg_adjust_template($body);    $body = phpfmg_parse_mail_body($body,$fields);    $subject = phpfmg_parse_mail_body( $subject, $fields );    if( $isHtml ) {        $body = phpfmg_getHtmlContent( $body );    };            $body = str_replace( "0x0d", '', $body );             $body = str_replace( "0x0a", PHPFMG_LNCR, $body );        if( defined('PHPFMG_RETURN_EMAIL') && formIsEMail(PHPFMG_RETURN_EMAIL) ){        $from = PHPFMG_RETURN_EMAIL;    };    $fromHeader = ( PHPFMG_YOUR_NAME == "" ?  "" : "\"".PHPFMG_YOUR_NAME . "\"" ) . " <{$from}>";     return mailAttachments( $to , $subject , $body, filterEmail($from), PHPFMG_YOUR_NAME, $fromHeader, '' , '', PHPFMG_CHARSET, 'AutoResponseEmail' );    }function phpfmg_log_mail( $to='', $subject='', $body='', $headers = '', $type='' ){    $sep = PHPFMG_LNCR . str_repeat('----',20) . PHPFMG_LNCR ;     appendToFile( PHPFMG_EMAILS_LOGFILE, date("Y-m-d H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . "\t{$type}"  . $sep . "To: {$to}\r\nSubject: {$subject}\r\n" . $headers . $body  . "<br>" . PHPFMG_LNCR . $sep . PHPFMG_LNCR ) ;}function phpfmg_getHtmlContent( $body ){    $html = "<html><title>Your Form Mail Content | htttp://phpfmg.sourceforge.net</title><style type='text/css'>body, td{font-family : Verdana, Arial, Helvetica, sans-serif;font-size : 13px;}</style><body>"            . $body ."</body></html>";            return $html ;}  function phpfmg_adjust_template( $body ){    $isHtml = 'html' == PHPFMG_MAIL_TYPE ;    if( $isHtml ){        $body = preg_match( "/<[^<>]+>/", $body ) ? $body : nl2br($body);     };    return $body;}function phpfmg_parse_mail_body( $body, $fields = false ){    if( !is_array($fields) )        return $body ;        $yes = function_exists( 'str_ireplace' );    foreach( $fields as $name => $value ){        $body = $yes ? str_ireplace( $name, $value ,$body )                      : str_replace ( $name, $value ,$body );    };     return trim($body);}# filter line breaks to avoid emails injectingfunction filterEmail($email, $chars = ''){    $email = trim(str_replace( array("\r","\n"), '', $email ));    if( is_array($chars) ) $email = str_replace( $chars, '', $email );    $email = preg_replace( '/(cc\s*\:|bcc\s*\:)/i', '', $email );    return $email;}function mailReport( $content = "", $file = '' ){    $content = "Dear Sir or Madam,Your online form at " . HOST_NAME . PHP_SELF . " failed to save data to file. Please make sure the web user has permission to write to file \"{$file}\". If you don't know how to fix it, please forward this email to technical support team of your web hosting company or your Administrator.PHPFMG - PHP FormMail Generator";    mail(PHPFMG_TO, "Error@" . HOST_NAME . PHP_SELF, $content );}function    remove_newline( $str = "" ){    return str_replace( array("\r\n", "\r", "\n"), array('\r\n', '\r', '\n'), $str );}function    checkPass( $form_mail = array() ){    $names = array();    $labels = array();        foreach( $form_mail as $field ){        $type     = strtolower( $field[ "type" ]  );        //$value    = trim( $_POST[ $field[ "name" ] ] );        $value = phpfmg_field_value( $field[ "name" ] );        $required = strtolower($field[ "required" ]) ;        $text     = stripslashes( $field[ "text" ] );                // simple check the field has something keyed in.        if( !strlen($value) && (  $required == "required" ) && $type != "attachment" ){            $names[] = $field[ "name" ];            $labels[]  = $text;            //return ERR_MISSING . $text  ;            continue;        };           // verify the special case        if(             ( strlen($value) || $type == "attachment" )             &&  $required == "required"         ):                    switch( $type ){                case     strtolower("Sender's Name") :           

Staff
8,050 Points
2014-05-27 8:36 am
Looking over your code, it looks like you have things correctly defined, but it is possible that the password you have entered within your love code on the server is incorrect. Try first logging into Webmail with the email address and password that you have defined within your code. If it fails to log in, I recommend resetting your password if you are unsure of it.
n/a Points
2014-05-31 11:36 am

Hi JeffMa. How r u?

which password PHPFMG_SMTP_PASSWORD or PHPFMG_SMTP_PLAIN_PASSWORD.

Staff
9,962 Points
2014-05-31 3:40 pm
Hello Abdur, hope you're doing well this weekend.

It looks like you'd want to edit the PHPFMG_SMTP_PASSWORD variable with the correct email account password. Also you might want to double-check that you're using the correct mail host. You mentioned in your Outlook settings you're using smtp.maahireen.com but in the code you've posted you're using PHPFMG_SMTP_HOST' , 'mail.maahireen.com.

Hope that helps. Please let us know if you had any further questions at all.

- Jacob
n/a Points
2014-05-31 5:05 pm

I have checked and made changes to following entries

PHPFMG_SMTP_HOST' to smtp.maahireen.com

PHPFMG_SMTP_PASSWORD was correct but i am not revealing it here due to security concern. Please donot mind. But i can give you if you give me your personal email id.

Though php mailer is sending data to my server but it is not sending email. Why Jacob?

 

 

Staff
9,962 Points
2014-05-31 5:58 pm
Hello again Abdur,

What do you mean by your script is sending data to your server, but not sending the email? Have you checked at all in your server's mail logs to see if it's the mail server itself preventing your message to go through?

Unfortunately providing us with your email password will not help, because if we can get it to work on our server it would just mean that there is a server configuration difference on your current server that is not allowing the message to deliver.

Please note that this guide covers using phpMailer, and not PHP Form Mail Maker, they are completely different things. You might want to try following along in this guide and try using phpMailer on your current host and see if you're still having any issues.

- Jacob
n/a Points
2014-06-01 3:20 am

In server the data is deposited & an error message showing that it cannot send email because it cannot connect to smtp host.

In the video above it shows to download php mailer in the server. I have not installed it. I think that is why it is not working. Isn't it?

Staff
8,050 Points
2014-06-02 7:56 am
Depending on your server configuration, you may need to set the host to 'localhost' if you are sending mail from the same server that your mail is located one. phpMailer and FormMail are 2 completely different things. It looks like you are using FormMail and not PHPMailer in which the steps in this article will be completely different.
n/a Points
2014-06-03 12:58 am

Yes the email is coming to email address in the webmail of maahireen.com/webmail but not in webmail.maahireen.com. Little confused. Ok.

Please tell what is the name of the file for the script. I copied this script from this page above.

<?php// $email and $message are the data that is being// posted to this page from our html contact form$email = $_REQUEST['email'] ;$message = $_REQUEST['message'] ;// When we unzipped PHPMailer, it unzipped to// public_html/PHPMailer_5.2.0require("lib/PHPMailer/PHPMailerAutoload.php");$mail = new PHPMailer();// set mailer to use SMTP$mail->IsSMTP();// As this email.php script lives on the same server as our email server// we are setting the HOST to localhost$mail->Host = "localhost";  // specify main and backup server$mail->SMTPAuth = true;     // turn on SMTP authentication// When sending email using PHPMailer, you need to send from a valid email address// In this case, we setup a test email account with the following credentials:// email: send_from_PHPMailer@bradm.inmotiontesting.com// pass: password$mail->Username = "send_from_PHPMailer@bradm.inmotiontesting.com";  // SMTP username$mail->Password = "password"; // SMTP password// $email is the user's email address the specified// on our contact us page. We set this variable at// the top of this page with:// $email = $_REQUEST['email'] ;$mail->From = $email;// below we want to set the email address we will be sending our email to.$mail->AddAddress("bradm@inmotiontesting.com", "Brad Markle");// set word wrap to 50 characters$mail->WordWrap = 50;// set email format to HTML$mail->IsHTML(true);$mail->Subject = "You have received feedback from your website!";// $message is the user's message they typed in// on our contact us page. We set this variable at// the top of this page with:// $message = $_REQUEST['message'] ;$mail->Body    = $message;$mail->AltBody = $message;if(!$mail->Send()){   echo "Message could not be sent. <p>";   echo "Mailer Error: " . $mail->ErrorInfo;   exit;}echo "Message has been sent";?>

Staff
8,050 Points
2014-06-03 7:39 am
In this example outlined in the article, your would name the file email.php. Be sure to also customize this script based on your email account and password.
n/a Points
2014-06-04 10:19 am

ok it is email.php

I am receiving email but the form data submitted i am not getting.

How i can get?

Staff
8,050 Points
2014-06-04 10:25 am
Unfortunately, your question is unclear. Could you clarify?
n/a Points
2014-06-06 12:39 pm

Sorry!

Actually i mean to say that

$mail = new PHPMailer();$mail->IsSMTP();                                      // set mailer to use SMTP$mail->Host = "localhost";  // specify main and backup server$mail->SMTPAuth = true;     // turn on SMTP authentication$mail->Username = "email1@maahireen.com";  // SMTP username$mail->Password = "password"; // SMTP password$mail->From = "email1@maahireen.com";$mail->FromName = "PhpMailer";$mail->AddAddress("email2@maahireen.com");                  // name is optional

If i fills the form fields i.e. Email & Message & click submit button. The message comes the "Message has been sent".

then the data of filled form will come to my email account name email2@maahireen.com. I am getting the email but not the filled form data. How it will come? Below is the image.

 

 

Staff
8,253 Points
2014-06-06 1:03 pm
Hello Abdur,

The SMTP settings you provided look accurate, and you can confirm that the email is being delivered successfully.

This would lead me to believe that it is caused by an issue with the actual form setup. Can you provide a link to the form, so we can test it out and troubleshoot further.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-06-06 2:19 pm

the php file name is test1.php

email address are:

user1@example.com

user2@example.com

 

yes the email is coming but form data is not submitted or showing.

Please see it.

Staff
9,962 Points
2014-06-06 6:19 pm
Hello again Abdur,

We took a look at your email form, but unfortunately because it's not hosted on our servers we were unable to view the PHP script itself to see what's going on.

Again this guide that you're commenting on is for phpMailer, and we don't have direct experience with PHP Form Mail Maker which it seems like you're using.

I would as a test have your emailtestform.html page set the form action to test2.php. Then in the test2.php script use this code:

<?php

$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

echo 'Email: ' . $email . '<br>';
echo 'Message: ' . $message;

?>


Do you see the info you typed into the form display on the page? If not it would seem your server could be having issues with the PHP $_REQUEST global variable. You might want to try using $_POST instead and seeing if that allows the info to be passed:

<?php

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

echo 'Email: ' . $email . '<br>';
echo 'Message: ' . $message;

?>


If that isn't working either, you might want to contact your web host and ask them why form data sent in a POST to a PHP script isn't displaying.

- Jacob
n/a Points
2014-06-09 5:23 am

Where the form submit data will be saved? In the server or it will come in email as attachment.

Staff
8,253 Points
2014-06-09 12:12 pm
Hello Abdur,

Thank you for your comment. When a user submits a form, it will be sent in the body of the email.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-06-09 10:22 pm

When I try submittting my form I keep getting the error: 

Message could not be sent.Mailer Error: Message body empty

Below is both the html for the form and the php I am using. I have class.phpmailer.php, class.smtp, and phpmailerautoload.php uploaded to my server. 

<?php
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$message = $_POST['message'] ;

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();  
$mail->Mailer = "smtp";                                   
$mail->Host = 'smtp.gmail.com';  
$mail->Port = 465;
$mail->SMTPAuth = true;                           
$mail->Username = 'xxx@gmail.com';     
$mail->Password = 'xxx';                          
$mail->SMTPSecure = 'ssl';                            
$mail->addAddress('xxx@gmail.com', 'First Last');
$mail->From = $email;
$mail->FromName = $name;

$mail->isHTML(true);  
$mail->Subject = 'Contact from website';
$mail->body= $message ;
$mail->WordWrap = 50;                               
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}<form method="post" action="email.php" ENCTYPE="multipart/form-data" accept-charset='UTF-8'>
<input type="text" class="textbox" placeholder="Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<input type="text" class="textbox" placeholder="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">
<textarea name="Message:" placeholder="Message" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = ' Message';}"></textarea>
<div class="span4">
<a href="#"><i><input type="submit" value="SUMBIT"></i></a>
</div>			
Staff
8,050 Points
2014-06-10 8:14 am
It looks like the error may be in this line:

;<textarea name="Message:" placeholder="Message" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = ' Message';}"></textarea>


I see that you have a space before the single quote and Message. That space appears to be what is causing the issue.
n/a Points
2014-06-11 2:30 pm

Thanks Jeff, that doesn't seen to be the problem though. I changed it but am still getting the same error message. Anything else that might be causing this?

Staff
9,962 Points
2014-06-11 2:48 pm
Hello Liz,

Based off the error message that you're receiving:

Message could not be sent.Mailer Error: Message body empty

It sounds like the body of your email is not being properly set. I believe this is coming from an empty variable that you've declared towards the top of the script:

$message = $_POST['message'] ;

Notice how this is saying $_POST['message'], that means it is trying to grab the form name of message from a POST attempt.

If you look towards the bottom of your script you have this line:

<textarea name="Message:"

This value would only show up if you were looking for $_POST['Message'] ; in your script with a capital M.

I would think the same applies to your $name and $email variables defined at the top of your script.

Please let us know if fixing the case sensitivity of your variable names allows the form to collect all the required info to send a message.

- Jacob
n/a Points
2014-06-11 3:52 pm

Thanks Jacob, but I fixed the case sensitivity and it's still giving me the same error.

Staff
9,962 Points
2014-06-11 4:35 pm
Hello again Liz,

Well it seems the problem definitely relates to your message body being blank. My next guess would be that you have:

$mail->body= $message ;

Instead of:

$mail->Body= $message ;

You might also want to do a test and see if you can directly manipulate this value and have it send mail:

$mail->Body= "Test message" ;

To test if things are making it from your HTML form to the PHP script for processing, you might want to add this at the top of your script:

echo '<pre>';
print_r($_POST);
echo '</pre>';


Then see if it's actually echoing out the values you typed into the form.

- Jacob
n/a Points
2014-06-10 3:41 pm

http://maahireen.com/phpmailertest/emailtestform.html

It ask to enter email & message.

I entered email as abc@cde.com

And message as 123456 abcdefg

And i click on submit

Another page loads called http://maahireen.com/phpmailertest/test1.php which shows

Email: abc@cde.comMessage: 123456 abcdefg Message has been sent

I opened my webmail email email2@maahireen.com

the password is password

it shows

 

[ Previous | Next ]      [ Delete & Previous | Delete & Next ]      [ Message List ]
     |     As Attachment   |    Bypass Trash Move To:        INBOX   Drafts   Sent   Trash        
  Subject: Here is the subject From: "PhpMailer" <email1@maahireen.com> Date: Tue, June 10, 2014 7:31 pm To: email2@maahireen.com Priority: Normal Options: View Full Header  |  Print  |  Download this as a file  |  View as HTML  
This is the body in plain text for non-HTML mail
clients

 
Attachments untitled-[2].html text/html 0 KiB   Download  |  View  
     |     As Attachment   |    Bypass Trash Move To:        INBOX   Drafts   Sent   Trash        
[ Previous | Next ]      [ Delete & Previous | Delete & Next ]      [ Message List ]
When i click on untitled-[2].html attachment it showsThis is the body in plain text for non-HTML mail
clientsWhere is my form data saved. i donot get it.will i send the script of html & php?
Staff
15,973 Points
2014-06-10 5:55 pm
Hello Abdur Rahmaan,

Thanks for the question. PhpMail creates forms that allows for an interface that allows people to fill in a form and email the results to you. This means that the form data is saved IN the email that sent after the form is submitted.

I hope that helps to explain it! Please let us know if you have any further questions.

Regards,
Arnel C.
n/a Points
2014-06-15 5:12 am

Hi Arnel,

Ok you write the form data is saved with IN the email. But why i am not getting any message or attachment of the filled form submitted.

Otherwise i donot know how to retrive data from the email or server.

I want to know How to get the data submitted?

Please explain.

 

Please reply.

Staff
16,694 Points
2014-06-15 8:12 am
Hello Shaikh,

Any fields filled out in the form should appear in the email. Are you not getting any emails at all or are you not getting the data entered in the form in the email? The data is not kept anywhere on the server so it will be impossible to collect it from there.

Kindest Regards,
Scott M
n/a Points
2014-06-17 1:14 am

Yes i am getting email. But not getting the data fields. What to do?

Staff
8,253 Points
2014-06-17 10:36 am
Hello Abdur,

At this point, it seems like the form is just not setup/coded correctly. We are happy to help, but it is somewhat difficult to troubleshoot since you are not hosted on our servers, and we do not have access to the files, or server logs.

Did you try what Jacob last suggested above?

Have you tried following the method on the top of this page? This method definitely works. There are also other options for sending an email from your website.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-06-18 6:43 am

Hi I used the same code as given above, but I am getting below error

Message could not be sent. <p>Mailer Error: SMTP connect() failed.

could you please let me to resolve the issue

Staff
8,050 Points
2014-06-18 8:25 am
If you copied the code without making any changes to it, it will fail as it defines sample data. Be sure to follow each instruction within the article carefully as even a small deviation from the instructions can cause the code to fail.
n/a Points
2014-06-21 10:56 am

I am using the following code :

File name: custom_functions.php

<?phpfunction smtpmailer($to, $from, $from_name, $subject, $body) {     global $error;    $mail = new PHPMailer();  // create a new object    $mail->IsSMTP(); // enable SMTP    $mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only    $mail->SMTPAuth = true;  // authentication enabled    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail    $mail->Host = 'localhost';    $mail->Port = 587;     $mail->Username = 'username@gmail.com';      $mail->Password = 'password';               $mail->SetFrom($from, $from_name);    $mail->Subject = $subject;    $mail->Body = $body;    $mail->AddAddress($to);    if(!$mail->Send()) {        $error = 'Mail error: '.$mail->ErrorInfo;         return false;    } else {        $error = 'Message sent!';        return true;    }?>

 

Filename:casedata.php

<?php

include('includes/PHPMailer/class.phpmailer.php');include('includes/custom_functions.php');$to="anu_man07@rediff.com";$from="anuragswinger@gmail.com";$from_name="Anurag";$subject="Test email subject";$body="Hello All this is my test email";smtpmailer($to,$from,$from_name,$subject,$body);

?>

Basically I am redirecting the page after submission to casedata.php.

I get this error: Mail error: SMTP connect() failed.

Staff
16,694 Points
2014-06-23 6:57 am
Hello Anurag,

Be sure you are using the correct ports. 587 is not the correct one to use with TLS or SSL as it is reserved for the non-secure. Even then 25 is also an option. If you want to use SSL or TLS, try port 465.

Kindest Regards,
Scott M
n/a Points
2014-06-21 11:04 am

i get the error:

SMTP ERROR: Failed to connect to server: Connection refused (111) SMTP connect() failed. message could not be sent.

mailer error:SMTP connect() failed.

am using godaddy as my host

Staff
16,694 Points
2014-06-23 6:59 am
Hello Martin,

As I cannot see your settings, I am unable to say for certain. However, the most common thing we see is a port mismatch. If you are sending via TLS/SSL you will want to use port 465, otherwise try ports 25 or 587.

Kindest Regards,
Scott M
n/a Points
2014-06-22 8:14 am

Hi, I am using Joomla 3.3.1. The inbuilt Joomla phpmailer is not working ...can I use your PHPMailer instead? How this be configured to send authentication mails to registering users?

Thank you

Tarun

 

 

Staff
16,694 Points
2014-06-23 12:25 pm
Hello Tarun,

You may want to try this configuration for your default Joomla 3.3.1 mailer as it should work without issue.

Kindest Regards,
Scott M
n/a Points
2014-06-23 4:39 pm

Thank you Scott

I read your link and replied in details. Acctually nothing is working for us

Regards

Tarun.

n/a Points
2014-06-24 7:53 am

From address is showing what I used for STMP authentication, not the one which I used in $mail->From. Where to include from address?

Staff
8,050 Points
2014-06-24 8:42 am
Defining an email address for $mail->From will determine what the recipient sees as the sender. If this is not working, could you provide us with your code from the script?
n/a Points
2014-06-24 9:10 am

Actually am trying to send verification mail to my subscribers.

$email = 'username@mail.com';//to address mail

                        $message = 'some html message here';

                        require_once (Yii::app()->basePath.'/models/PHPMailer.php');

                        $mail   = new PHPMailer; // call the class 

                        $mail->IsSMTP();

                        require_once (Yii::app()->basePath.'/config/SMTPconfig.php'); // include the class file name

                        $mail->From = "faizal.subair@website-name.com";

//From address mail

                        $mail->FromName = "Cannymart";

                        $mail->WordWrap = 50;

                        $mail->IsHTML(true);

                        $mail->Subject = "Cannymart Verification Mail"; // mail subject

                        $mail->AddAddress($email, $name); // to address - receiver mail and name

                        $mail->Body    = $message;

                        $mail->AltBody = $message;

$mail->Send()

//SMTPconfig.php

<?php

$mail->Host = "smtp.gmail.com";  // specify main and backup server

$mail->SMTPAuth = true;     // turn on SMTP authentication

$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail

$mail->Port = 465; // or 587

$mail->Username = "authentication@mail.com";  // SMTP username

$mail->Password = "*****";

?>

Am using different mail for authentication.

While receiving mail, it shows authentication mail as From address.

Am i clear?

Staff
8,050 Points
2014-06-24 9:13 am
Your settings are correct, but my best guess is that Gmail is changing the From address to prevent individuals from spoofing email accounts.
n/a Points
2014-06-24 9:57 am

I'm so green at this!Please pardon my ignorance, but where does the Final Configuration of the PHP Mailer Code actually belong? Back in contact_us.html of public_html.? Also, my public_html. houses contact.html but there is no contact_us.html... Is that going to be a problem? Should I just rename my contact.html as contact_us.html for redirection purposes? 

Staff
8,050 Points
2014-06-24 10:22 am
The form within the first code block on this article will be on the page that your contact form resides. As for the additional code that controls the mail being sent, this can go into a file named email.php within your public_html directory.
n/a Points
2014-06-24 11:00 am

Okay, so there is not already an email.php in my public_html. directory, so I will create a new .php (email.php) and paste the Final Configuration of the PHP Mailer Code there?

Staff
15,973 Points
2014-06-24 1:38 pm
Hello Wm III,

Yes, as per the tutorial above, the contents of the PHPmailer need to be at the root of your website, in this case public_html. The root directory is also called the document root folder for your website. Use the link for more details on its location.

I hope that helps to explain the issue. Let us know if you have any further questions or comments.

Regards,
Arnel C.
n/a Points
2014-06-28 3:40 pm

Hello again guys,

Thanks for your helpful answers.

I am out of work for 40 days.

I hope i will return to our very important discussion.

Till then good bye.

Take care.

n/a Points
2014-07-09 6:35 am

<?php

 

// $email and $message are the data that is being

// posted to this page from our html contact form

$email = $_REQUEST['email'] ;

$message = $_REQUEST['message'] ;

 

// When we unzipped PHPMailer, it unzipped to

// public_html/PHPMailer_5.2.0

require("C:\wamp\www\design\mail\PHPMailer_5.2.0/class.phpmailer.php");

 

$mail = new PHPMailer();

 

// set mailer to use SMTP

$mail->IsSMTP();

 

// As this email.php script lives on the same server as our email server

// we are setting the HOST to localhost

$mail->Host = "localhost";  // specify main and backup server

 

$mail->SMTPAuth = true; 

$mail->SMTPSecure = "tls";

 

$mail->Host       = "antara029.gmail.com"; 

 

$mail->Port       = 587; 

 

    // turn on SMTP authentication

 

// When sending email using PHPMailer, you need to send from a valid email address

// In this case, we setup a test email account with the following credentials:

// email: send_from_PHPMailer@bradm.inmotiontesting.com

// pass: password

$mail->Username = "antara029@gmail.com";  // SMTP username

$mail->Password = "password"; // SMTP password

 

// $email is the user's email address the specified

// on our contact us page. We set this variable at

// the top of this page with:

// $email = $_REQUEST['email'] ;

$mail->From = $email;

 

// below we want to set the email address we will be sending our email to.

$mail->AddAddress("antara029@yahoo.com", "Brad Markle");

 

// set word wrap to 50 characters

$mail->WordWrap = 50;

// set email format to HTML

$mail->IsHTML(true);

 

$mail->Subject = "You have received feedback from your website!";

 

// $message is the user's message they typed in

// on our contact us page. We set this variable at

// the top of this page with:

// $message = $_REQUEST['message'] ;

$mail->Body    = $message;

$mail->AltBody = $message;

 

if(!$mail->Send())

{

   echo "Message could not be sent. <p>";

   echo "Mailer Error: " . $mail->ErrorInfo;

   exit;

}

 

echo "Message has been sent";

?>

 

 

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

 

 

this error shows.please help

Staff
16,694 Points
2014-07-09 7:42 am
Hello Antara,

The issue is with your secure setting and port. The 587 port does not work with the TLS setting. You will want to use the secure port of 465 when using tls or ssl.

Kindest Regards,
Scott M
n/a Points
2014-07-09 11:52 am

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

I change port to 465 but error is shown.....what will i do now...plz help

Staff
8,050 Points
2014-07-09 1:21 pm
It appears that you may be using an incorrect host setting within your script. I recommend reviewing the correct SMTP settings. I believe Gmail typically uses smtp.gmail.com as their host.
n/a Points
2014-07-15 10:26 pm

Hello, 

I've only just started on php and forms so thanks to your very clear tutorial everything is working great.

However I am trying to implement breaks <br> in the textarea everytime the user hits enter instead of having the text emailed in a plain straight line. This is rather difficult especially when users are listing items.

In the tutorial, it stated that the AltBody is the line that determines if the entered text is styled with or without html. Does that apply to line breaks?

I also saw the $mail-IsHTML (true); I went out on a limb and changed that to false which didn't really do much but I already had a feeling that wouldn't have fixed anything.

So I've looked around and found alternatives but they all use something I'm quite unfamiliar with; 

- strings

- function nl2br()

- $message = str_replace("\r\n", "<br>", $message);

Their whole structure seems different using $post instead of $mail so I'm not too sure what to do here.

I'd rather add more to what I have than redo everything with new code since I'm quite comfortable and familiar with what you guys have brought to the table. 

Thank you in advance.

 

Kind Regards,

Daniel

Staff
8,050 Points
2014-07-16 9:14 am
The code example of:

$message = str_replace("\r\n", "<br>", $message);


would work well within the code because it will automatically insert a line break for a new line. This line can be inserted right before this line:

$mail-<Body = $message;

n/a Points
2014-07-21 6:11 am

Parse error: syntax error, unexpected '<' in C:\wamp\www\send\cont.php on line

 

----------------------------------------------

 

<?php $name = $_POST['name'] ; $email = $_POST['email'] ; $message = $_POST['message'] ; require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); $mail->Mailer = "smtp"; $mail->Host = 'smtp.gmail.com'; $mail->Port = 465; $mail->SMTPAuth = true; $mail->Username = 'smtgl2701@gmail.com'; $mail->Password = 'password'; $mail->SMTPSecure = 'ssl'; $mail->addAddress('smtgl2701@gmail.com', 'Sumit Kumar'); $mail->From = $email; $mail->FromName = $name; $mail->isHTML(true); $mail->Subject = 'Contact from website'; $mail->body= $message ; $mail->WordWrap = 50; error_reporting(E_ALL); ini_set('display_errors', 1); if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } <form method="post" action="email.php" ENCTYPE="multipart/form-data" accept-charset='UTF-8'> <input type="text" class="textbox" placeholder="Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}"> <input type="text" class="textbox" placeholder="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}"> <textarea name="Message:" placeholder="Message" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = ' Message';}"></textarea> <div class="span4"> <a href="#"><i><input type="submit" value="SUMBIT"></i></a> ?>

 

Staff
16,694 Points
2014-07-21 3:03 pm
Hello Sumit,

It appears you have the php form code inside the php. You will want to have the ?> (php close tag) before the form and not after it.

Kindest Regards,
Scott M
n/a Points
2014-07-21 8:05 am
include an example which makes the concept clear to understand.
Staff
16,694 Points
2014-07-21 3:05 pm
Hello Rakhesh,

We are happy to make the process more clear. What particular area did you have issues with?

Kindest Regards,
Scott M
n/a Points
2014-08-15 4:46 am

Hello. When i unzipp the php mail that i download through ur link i cant find the "lib/PHPMailer/PHPMailerAutoload.php" i hope you can help me with this. thanks a lot

Staff
16,694 Points
2014-08-15 10:03 am
Hello Ronilo,

It does seem there is an inconsistency with the second piece of code and the zip file. We will review the article to make any changes needed to bring it up to date. I was able to test the first piece of code, but the second does not as it cannot find the file you mentioned.

Kindest Regards,
Scott M
n/a Points
2014-08-15 8:29 pm

 

Hello everyone. i have the same problem as the previous commenter.

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

i have already tried it in my own domain and in the localhost. the result is still the same. 

when trying my own domain i set this

$mail->SMTPSecure = "tls";

$mail->Host       = "smtp.1and1.com"; 

$mail->Port       = 587; 

still not working

i hope u can help me with this. thanks a lot

 

this is my code

<?php

require("class.phpmailer.php");

 

$mail = new PHPMailer();

 

$mail->IsSMTP(); // set mailer to use SMTP

$mail->Host       = "localhost"; 

$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = "sender@rofelynyap.com"; // SMTP username

$mail->Password = "password"; // SMTP password

 

$mail->From = "sender@rofelynyap.com";

$mail->FromName = "Mailer";

 

$mail->AddAddress("reciever@rofelynyap.com"); // name is optional

 

 

$mail->WordWrap = 50; // set word wrap to 50 characters

 

$mail->IsHTML(true); // set email format to HTML

 

$mail->Subject = "Here is the subject";

$mail->Body = "This is the HTML message body <b>in bold!</b>";

$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

 

if(!$mail->Send())

{

echo "Message could not be sent. <p>";

echo "Mailer Error: " . $mail->ErrorInfo;

exit;

}

 

echo "Message has been sent";

?>

 

Staff
15,973 Points
2014-08-15 8:46 pm
Hello Ronilo,

Sorry for the problem. The error indicates a problem with SMTP. If you're not using the SMTP settings for then you should make sure to use the correct settings. As email servers are getting stricter with sending messages, you may need to use specific SMTP settings. The settings you have shown above indicate that you're not using InMotion as the host. However, as I have indicated above, the error message indicates a sending error because it could not connect to the server. Double-check your settings (or change them to use the proper SMTP settings) and then it should work properly.

Regards,
Arnel C.
n/a Points
2014-08-15 9:50 pm

Hello Again

" If you're not using the SMTP settings for then you should make sure to use the correct settings. "

how can i use the correct setting? im still confuse sorry.

 

Staff
8,253 Points
2014-08-18 10:31 am
Hello Ronillo,

Thank you for contacting us again. Arnel is recommending that you check your SMTP settings, since your error indicates an issue there.

You can view all your email settings (including SMTP) in cPanel or Webmail at any time.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-08-18 11:05 am

It works now just fine, Thanks a lot

n/a Points
2014-08-19 4:16 am

Hello can you help me to how to send my HTML Coding in my message veriable 

Staff
16,694 Points
2014-08-19 8:06 am
Hello Navneet,

This article in particular only sends text emails. Your idea is a great one for a future article. Until we have time to fully create and test the code for an article, however, we can only do some quick research for you. We found a forum post online that covers this specific request. I hope that helps!

Kindest Regards,
Scott M
n/a Points
2014-08-19 9:33 am

Hey I get an error....

 

SMTP() : not connect.. i use "localhost" as server...

 

 

MY motive is send a welcome mail to user when they signup on my website page.

Please help me . And if you can provide well documented code then paste here .

Staff
16,694 Points
2014-08-19 9:50 am
Hello Amit,

That error means that the settings you have for your SMTP are not working. You will need to check them to ensure they are all correct. Remember that other than the common port settings, the rest are relative to you (host, username, password), so it is not feasible for us to give you the exact settings publicly.

Kindest Regards,
Scott M

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

92 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!