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!

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
9,193 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
9,193 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,968 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
9,684 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,968 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
19,592 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
9,684 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,968 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
9,193 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
17,357 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
9,193 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,968 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,968 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
9,193 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
9,193 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
9,193 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
9,684 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,968 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
9,684 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
9,193 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,968 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,968 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
17,357 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
19,592 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
9,684 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
9,193 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
19,592 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
19,592 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
19,592 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
9,193 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
9,193 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
9,193 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
17,357 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
19,592 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
9,193 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
9,193 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
19,592 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
19,592 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
19,592 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
17,357 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
9,684 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
19,592 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
19,592 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
n/a Points
2014-08-21 3:30 am
Nice. Worked well.
n/a Points
2014-08-28 5:10 am

helo everyone,

actually am developing a website in which i need to send email to the respective students, am using xampp server as local host and designing my website.

i had made changes in my mail sending option as you said above, but sttill its showing the same error

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

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

am using my gmail id and password to check wheather emails are sent or not.

could you plase help me.

Staff
19,592 Points
2014-08-28 10:21 am
Hello Kedarnath,

You will need to check your SMTP settings to ensure they are set correctly. (host, username, password,port settings)

Kindest Regards,
Scott M
n/a Points
2014-08-28 10:36 am

Hey Scott,

Now my new error message is that

Error: not authenticated

Problem with authentication

I had given my email id and password correctly

Even then am getting the same error

Staff
9,193 Points
2014-08-28 10:48 am
Be sure to check over your SMTP settings. To double-check your username and password, attempt to log into Webmail using that email/password combination. Be sure that you are entering your full email address as the username.

It is possible that the host that you have set could be incorrect as well. Double-check this too.
n/a Points
2014-08-28 11:02 am

Hey, 

Just help me that if i put this entire code in a red hat server which our college people are using, will that work?? Any changes i need to do for that system again??

Staff
9,193 Points
2014-08-28 11:23 am
As long as the server is running PHP, everything should work as expected.
n/a Points
2014-08-30 6:42 am

Hi frndz i am using win 8.1 create the mail form send the its geting msg could not sent ,,what is the problem i canot solve t pls help me i am using win 8.1 64 bit

Staff
19,592 Points
2014-09-02 11:30 am
Hello Hari,

Your operating system should not have an effect on the sending. Even if you are working on a local maching, you are likely using a WAMP setup, which means the php is running off of the Apache setup for your computer. What is the exact error message you are receiving? Also, are you using a WAMP setup? Or are you connecting to the hosting server?

Kindest Regards,
Scott M
n/a Points
2014-09-04 6:37 am

Write a program in javascript which check condition that if i=1 then it continue to a label otherwise continue to the bottom of the program. Can u find out the error in the program below:

<script type="text/javascript">var i=1if(i==1){continue label3;}</script>label1:This is now html.label2:document.write("This is middle");</script>label3:document.write("This is javascript");</script>

Staff
19,592 Points
2014-09-04 8:46 am
Hello Abdur,

This is not the appropriate article for your question. If you have a question you will need to ask it from here. That way, if we are unable to answer perhaps another one of our community members may.

Kindest Regards,
Scott M
n/a Points
2014-09-05 2:15 pm
It helped me a lot :)
n/a Points
2014-09-09 7:15 pm
Well written and detailed instructions. Awesome!
n/a Points
2014-09-20 2:07 pm

I have several webpage linked with a common internal email address to send form data to respective external email. A common internal email is used to send contact us form to respective external email. I want a script for a common contact us form without making severals contact us form. A common contact us form will get a variable email adress passed form the webpage. User will use to fill the a common contact us form & submit it. The submitted form should go to respective external emails using a common internal email.

Suppose i have a common internal email called commonemail@abc.com

I have several webpage for example 1.html, 2.html, 3.html with respective external email such as abc@gmail.com, def@gmail.com, ghi@email.com to send form data. For that we have to make several contact us form. But i want a single contact us form such as contactus.php with a varaible email address passed from any webpage.

What script i will add in the webpage & what script i will add on contactus.php

Staff
19,592 Points
2014-09-22 7:34 am
Hello Shaikh,

I am not able to give specific code for that that as I would need to create a test environment and test to ensure it worked properly. That is a bit beyond what we do here in the Support Center. Check into passing an email address to the contact form from the different pages your visitor. If they came in directly, there will not be an address passed so have a default one in place for those. I hope this helps you design the form the way you need it.

Kindest Regards,
Scott M
n/a Points
2014-09-22 2:40 am

Hi,

I have downloaded phpmailer and  kept in htdocs of xampp server.I'm using xampp and have created contact form webpage.But not yet hosted the website.I have used the same code given here.I have used port=80.username=me@example.com as given in php.ini and blank password.Im gettin 'ehlo command failed'  error.Sending mail to my gmail id.Dont know where I went wrong.

Actually I dont know where to get username and password.

Please help me.

Thanks

Staff
19,592 Points
2014-09-22 7:36 am
Hello kgh,

SMTP settings will not use port 80. They typically use 25 or 587 for standard email. Give that a try.

Kindest Regards,
Scott M
n/a Points
2014-09-22 8:44 am

If I use that (port=587 or 25) I'm getting this error:

2014-09-22 12:30:21 SMTP ERROR: Failed to connect to server: No connection could be made because the target machine actively refused it. (10061) 2014-09-22 12:30:21 SMTP connect() failed. Message could not be sent.Mailer Error: SMTP connect() failed.

I'm using tls.

Staff
19,592 Points
2014-09-22 9:01 am
Hello kgh,

Keep in mind that XAMPP configuration may not match our servers. To send with localhost, you will need to use the sendmail package, which should be included in XAMPP. You may need to make other changes to the settings, php.ini and even the sendmail.ini on your local machine. Check out the forum post on this from StackOverflow.

Kindest Regards,
Scott M
n/a Points
2014-09-23 7:55 am
Does not tell how to use it in our website. It Just about making a new file.
n/a Points
2014-09-23 9:07 am

Hi

I found the settings in the link you told.But not getting it.Really i'm confused.

Actually I have php mail() script which I'm trying to send to my gmail Id.That is from localhost(in windows) since I havent yet hosted pages.

I made SMTP=localhost and port=25 send_from=me@example.com which didnt work for me.There is no mail in my inbox.

Some people say in we have to use gmail username password in php.ini.That also I tried.

Isit really possible to send a mail using mail() of php in windows from localhost to gmail id?Bit confused!!

If I host the website should I inform the server people to set the settings in xamp server?Or do they do themselves?(I'm new to php)

Please guide me properly.

Staff
9,193 Points
2014-09-23 10:58 am
XAMPP is quite a bit different than a typical server configuration. It looks like you will have to define several other settings within it to get mail operating properly. After defining these settings, you may also have to restart the XAMPP services. I was able to find some information on your issue within a Stackoverflow question that may help you.
n/a Points
2014-09-25 3:25 am

Hello sir,

 I'm getting message sent but not getting the mail in my inbox or concerned people's inbox.What ma be wrong?Please help me.

kgh

Staff
19,592 Points
2014-09-25 9:05 am
Hello kgh,

If the message says it is being sent, then the send() function has returned a success message. Check your logs to see if it was sent and also the settings for the intended recipient to ensure everything is correct.

Kindest Regards,
Scott M
Staff
9,684 Points
2014-09-25 9:12 am
Hello kgh,

Thank you for your question. I recommend reviewing the Email logs, to see if they are actually being sent.

If you need help reviewing the logs, Live Support can assist you.

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

Thank you,
John-Paul
n/a Points
2014-09-24 6:21 am

Yes sir,I got the settings and  I did.Then I executed my php code using xampp.Then if I check the mail I'm not getting any mail.I'm sending from my gmail id using localhost to another gmailid.This is what they have told right?

Where I went wrong?

Staff
9,684 Points
2014-09-24 12:19 pm
Hello kgh,

Thank you for your question. If you are using gmail, you need to adjust the settings a little bit.

Jacob answered a similar question earlier, here is a link to his suggested gmail settings.

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

Thank you,
John-Paul
n/a Points
2014-09-24 8:07 am

can some on help me with the mailer html form that will work with the php mailer?

Staff
19,592 Points
2014-09-24 11:34 am
Hello,

We are happy to try and answer any specific questions you may have. What are you having trouble with?

Kindest Regards,
Scott M
n/a Points
2014-09-24 12:33 pm

i use phpmailer5.2  but when i send mail it sends whitout the attachment here is my code

<?php    $fromname = addslashes($_POST['fromname']);    $frommail = addslashes($_POST['from']);    $torcpt = addslashes($_POST['rcpt']);    $subject =  addslashes($_POST['subject']);    $replyto =  addslashes($_POST['reply']);    $errors =  addslashes($_POST['errors']);    $cc = addslashes($_POST['cc']);    $bcc = addslashes($_POST['bcc']);    $text = addslashes($_POST['editor1']);    $text =$_POST['attachment'];            $PHPmailer = new PHPMailer(true);    $PHPmailer->AddAddress($torcpt);    $PHPmailer->SetFrom($frommail,$fromname);    $PHPmailer->AddReplyTo($replyto,$fromname);    $PHPmailer->AddBCC($bcc);    $PHPmailer->AddCC($cc);            $PHPmailer->WordWrap = 50;                                 // set word wrap to 50 characters    $PHPmailer->AddAttachment("/var/tmp/file.tar.gz");         // add attachments    $PHPmailer->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name    $PHPmailer->IsHTML(true);      $PHPmailer->Subject = $subject;        $xMailInfo = '        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">        <html xmlns="http://www.w3.org/1999/xhtml">        <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <title>'.$fromname.'</title>        </head>        <body>        '.$text.'        </body>        </html>    ';    $PHPmailer->MsgHTML($xMailInfo);        if($PHPmailer->Send()){        //echo "Sent";        header('location: mailer-zome.php?sent=1');         }else{        //echo "UnSent";        header('location: mailer-zome.php?sent=0');         }    /*~ class.phpmailer.php.---------------------------------------------------------------------------.| Software: PHPMailer - PHP email class || Version: 5.2 || Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ || ------------------------------------------------------------------------- || Admin: Jim Jagielski (project admininistrator) || Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net || : Marcus Bointon (coolbru) coolbru@users.sourceforge.net || : Jim Jagielski (jimjag) jimjag@gmail.com || Founder: Brent R. Matzelle (original founder) || Copyright (c) 2010-2011, Jim Jagielski. All Rights Reserved. || Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. || Copyright (c) 2001-2003, Brent R. Matzelle || ------------------------------------------------------------------------- || License: Distributed under the Lesser General Public License (LGPL) || http://www.gnu.org/copyleft/lesser.html || This program is distributed in the hope that it will be useful - WITHOUT || ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or || FITNESS FOR A PARTICULAR PURPOSE. |'---------------------------------------------------------------------------'*//*** PHPMailer - PHP email transport class* NOTE: Requires PHP version 5 or later* @package PHPMailer* @author Andy Prevost* @author Marcus Bointon* @author Jim Jagielski* @copyright 2010 - 2011 Jim Jagielski* @copyright 2004 - 2009 Andy Prevost* @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License*/if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");class PHPMailer {  /////////////////////////////////////////////////  // PROPERTIES, PUBLIC  /////////////////////////////////////////////////  /*** Email priority (1 = High, 3 = Normal, 5 = low).* @var int*/  public $Priority = 3;  /*** Sets the CharSet of the message.* @var string*/  public $CharSet = 'iso-8859-1';  /*** Sets the Content-type of the message.* @var string*/  public $ContentType = 'text/plain';  /*** Sets the Encoding of the message. Options for this are* "8bit", "7bit", "binary", "base64", and "quoted-printable".* @var string*/  public $Encoding = '8bit';  /*** Holds the most recent mailer error message.* @var string*/  public $ErrorInfo = '';  /*** Sets the From email address for the message.* @var string*/  public $From = 'root@localhost';  /*** Sets the From name of the message.* @var string*/  public $FromName = 'Root User';  /*** Sets the Sender email (Return-Path) of the message. If not empty,* will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.* @var string*/  public $Sender = '';  /*** Sets the Subject of the message.* @var string*/  public $Subject = '';  /*** Sets the Body of the message. This can be either an HTML or text body.* If HTML then run IsHTML(true).* @var string*/  public $Body = '';  /*** Sets the text-only body of the message. This automatically sets the* email to multipart/alternative. This body can be read by mail* clients that do not have HTML email capability such as mutt. Clients* that can read HTML will view the normal Body.* @var string*/  public $AltBody = '';  /*** Stores the complete compiled MIME message body.* @var string* @access protected*/  protected $MIMEBody = '';  /*** Stores the complete compiled MIME message headers.* @var string* @access protected*/  protected $MIMEHeader = '';  /*** Sets word wrapping on the body of the message to a given number of* characters.* @var int*/  public $WordWrap = 0;  /*** Method to send mail: ("mail", "sendmail", or "smtp").* @var string*/  public $Mailer = 'mail';  /*** Sets the path of the sendmail program.* @var string*/  public $Sendmail = '/usr/sbin/sendmail';  /*** Path to PHPMailer plugins. Useful if the SMTP class* is in a different directory than the PHP include path.* @var string*/  public $PluginDir = './library/';  /*** Sets the email address that a reading confirmation will be sent.* @var string*/  public $ConfirmReadingTo = '';  /*** Sets the hostname to use in Message-Id and Received headers* and as default HELO string. If empty, the value returned* by SERVER_NAME is used or 'localhost.localdomain'.* @var string*/  public $Hostname = '';  /*** Sets the message ID to be used in the Message-Id header.* If empty, a unique id will be generated.* @var string*/  public $MessageID = '';  /////////////////////////////////////////////////  // PROPERTIES FOR SMTP  /////////////////////////////////////////////////  /*** Sets the SMTP hosts. All hosts must be separated by a* semicolon. You can also specify a different port* for each host by using this format: [hostname:port]* (e.g. "smtp1.example.com:25;smtp2.example.com").* Hosts will be tried in order.* @var string*/  public $Host = 'localhost';  /*** Sets the default SMTP server port.* @var int*/  public $Port = 25;  /*** Sets the SMTP HELO of the message (Default is $Hostname).* @var string*/  public $Helo = '';  /*** Sets connection prefix.* Options are "", "ssl" or "tls"* @var string*/  public $SMTPSecure = '';  /*** Sets SMTP authentication. Utilizes the Username and Password variables.* @var bool*/  public $SMTPAuth = false;  /*** Sets SMTP username.* @var string*/  public $Username = '';  /*** Sets SMTP password.* @var string*/  public $Password = '';  /*** Sets the SMTP server timeout in seconds.* This function will not work with the win32 version.* @var int*/  public $Timeout = 10;  /*** Sets SMTP class debugging on or off.* @var bool*/  public $SMTPDebug = false;  /*** Prevents the SMTP connection from being closed after each mail* sending. If this is set to true then to close the connection* requires an explicit call to SmtpClose().* @var bool*/  public $SMTPKeepAlive = false;  /*** Provides the ability to have the TO field process individual* emails, instead of sending to entire TO addresses* @var bool*/  public $SingleTo = false;   /*** If SingleTo is true, this provides the array to hold the email addresses* @var bool*/  public $SingleToArray = array(); /*** Provides the ability to change the line ending* @var string*/  public $LE = "\n";  /*** Used with DKIM DNS Resource Record* @var string*/  public $DKIM_selector = 'phpmailer';  /*** Used with DKIM DNS Resource Record* optional, in format of email address 'you@yourdomain.com'* @var string*/  public $DKIM_identity = '';  /*** Used with DKIM DNS Resource Record* @var string*/  public $DKIM_passphrase = '';  /*** Used with DKIM DNS Resource Record* optional, in format of email address 'you@yourdomain.com'* @var string*/  public $DKIM_domain = '';  /*** Used with DKIM DNS Resource Record* optional, in format of email address 'you@yourdomain.com'* @var string*/  public $DKIM_private = '';  /*** Callback Action function name* the function that handles the result of the send email action. Parameters:* bool $result result of the send action* string $to email address of the recipient* string $cc cc email addresses* string $bcc bcc email addresses* string $subject the subject* string $body the email body* @var string*/  public $action_function = ''; //'callbackAction';  /*** Sets the PHPMailer Version number* @var string*/  public $Version = '5.2';  /*** What to use in the X-Mailer header* @var string*/  public $XMailer = '';  /////////////////////////////////////////////////  // PROPERTIES, PRIVATE AND PROTECTED  /////////////////////////////////////////////////  protected $smtp = NULL;  protected $to = array();  protected $cc = array();  protected $bcc = array();  protected $ReplyTo = array();  protected $all_recipients = array();  protected $attachment = array();  protected $CustomHeader = array();  protected $message_type = '';  protected $boundary = array();  protected $language = array();  protected $error_count = 0;  protected $sign_cert_file = '';  protected $sign_key_file = '';  protected $sign_key_pass = '';  protected $exceptions = false;  /////////////////////////////////////////////////  // CONSTANTS  /////////////////////////////////////////////////  const STOP_MESSAGE = 0; // message only, continue processing  const STOP_CONTINUE = 1; // message?, likely ok to continue processing  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached  /////////////////////////////////////////////////  // METHODS, VARIABLES  /////////////////////////////////////////////////  /*** Constructor* @param boolean $exceptions Should we throw external exceptions?*/  public function __construct($exceptions = false) {    $this->exceptions = ($exceptions == true);  }  /*** Sets message type to HTML.* @param bool $ishtml* @return void*/  public function IsHTML($ishtml = true) {    if ($ishtml) {      $this->ContentType = 'text/html';    } else {      $this->ContentType = 'text/plain';    }  }  /*** Sets Mailer to send message using SMTP.* @return void*/  public function IsSMTP() {    $this->Mailer = 'smtp';  }  /*** Sets Mailer to send message using PHP mail() function.* @return void*/  public function IsMail() {    $this->Mailer = 'mail';  }  /*** Sets Mailer to send message using the $Sendmail program.* @return void*/  public function IsSendmail() {    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {      $this->Sendmail = '/var/qmail/bin/sendmail';    }    $this->Mailer = 'sendmail';  }  /*** Sets Mailer to send message using the qmail MTA.* @return void*/  public function IsQmail() {    if (stristr(ini_get('sendmail_path'), 'qmail')) {      $this->Sendmail = '/var/qmail/bin/sendmail';    }    $this->Mailer = 'sendmail';  }  /////////////////////////////////////////////////  // METHODS, RECIPIENTS  /////////////////////////////////////////////////  /*** Adds a "To" address.* @param string $address* @param string $name* @return boolean true on success, false if address already used*/  public function AddAddress($address, $name = '') {    return $this->AddAnAddress('to', $address, $name);  }  /*** Adds a "Cc" address.* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.* @param string $address* @param string $name* @return boolean true on success, false if address already used*/  public function AddCC($address, $name = '') {    return $this->AddAnAddress('cc', $address, $name);  }  /*** Adds a "Bcc" address.* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.* @param string $address* @param string $name* @return boolean true on success, false if address already used*/  public function AddBCC($address, $name = '') {    return $this->AddAnAddress('bcc', $address, $name);  }  /*** Adds a "Reply-to" address.* @param string $address* @param string $name* @return boolean*/  public function AddReplyTo($address, $name = '') {    return $this->AddAnAddress('ReplyTo', $address, $name);  }  /*** Adds an address to one of the recipient arrays* Addresses that have been added already return false, but do not throw exceptions* @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'* @param string $address The email address to send to* @param string $name* @return boolean true on success, false if address already used or invalid in some way* @access protected*/  protected function AddAnAddress($kind, $address, $name = '') {    if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);      if ($this->exceptions) {        throw new phpmailerException('Invalid recipient array: ' . $kind);      }      echo $this->Lang('Invalid recipient array').': '.$kind;      return false;    }    $address = trim($address);    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim    if (!self::ValidateAddress($address)) {      $this->SetError($this->Lang('invalid_address').': '. $address);     /* if ($this->exceptions) {        throw new phpmailerException($this->Lang('invalid_address').': '.$bcc);      }      echo $this->Lang('invalid_address').': '.$address;      return false;*/    }    if ($kind != 'ReplyTo') {      if (!isset($this->all_recipients[strtolower($address)])) {        array_push($this->$kind, array($address, $name));        $this->all_recipients[strtolower($address)] = true;        return true;      }    } else {      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {        $this->ReplyTo[strtolower($address)] = array($address, $name);      return true;    }  }  return false;}/*** Set the From and FromName properties* @param string $address* @param string $name* @return boolean*/  public function SetFrom($address, $name = '', $auto = 1) {    $address = trim($address);    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim    if (!self::ValidateAddress($address)) {      $this->SetError($this->Lang('invalid_address').': '. $address);      if ($this->exceptions) {        throw new phpmailerException($this->Lang('invalid_address').': '.$address);      }      echo $this->Lang('invalid_address').': '.$address;      return false;    }    $this->From = $address;    $this->FromName = $name;    if ($auto) {      if (empty($this->ReplyTo)) {        $this->AddAnAddress('ReplyTo', $address, $name);      }      if (empty($this->Sender)) {        $this->Sender = $address;      }    }    return true;  }  /*** Check that a string looks roughly like an email address should* Static so it can be used without instantiation* Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator* Conforms approximately to RFC2822* @link http://www.hexillion.com/samples/#Regex Original pattern found here* @param string $address The email address to check* @return boolean* @static* @access public*/  public static function ValidateAddress($address) {    if (function_exists('filter_var')) { //Introduced in PHP 5.2      if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {        return false;      } else {        return true;      }    } else {      return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);    }  }  /////////////////////////////////////////////////  // METHODS, MAIL SENDING  /////////////////////////////////////////////////  /*** Creates message and assigns Mailer. If the message is* not sent successfully then it returns false. Use the ErrorInfo* variable to view description of the error.* @return bool*/  public function Send() {    try {      if(!$this->PreSend()) return false;      return $this->PostSend();    } catch (phpmailerException $e) {      $this->SetError($e->getMessage());      if ($this->exceptions) {        throw $e;      }      return false;    }  }  protected function PreSend() {    try {      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);      }      // Set whether the message is multipart/alternative      if(!empty($this->AltBody)) {        $this->ContentType = 'multipart/alternative';      }      $this->error_count = 0; // reset errors      $this->SetMessageType();      //Refuse to send an empty message      if (empty($this->Body)) {        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);      }      $this->MIMEHeader = $this->CreateHeader();      $this->MIMEBody = $this->CreateBody();      // digitally sign with DKIM if enabled      if ($this->DKIM_domain && $this->DKIM_private) {        $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;      }      return true;    } catch (phpmailerException $e) {      $this->SetError($e->getMessage());      if ($this->exceptions) {        throw $e;      }      return false;    }  }  protected function PostSend() {    try {      // Choose the mailer and send through it      switch($this->Mailer) {        case 'sendmail':          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);        case 'smtp':          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);        default:          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);      }    } catch (phpmailerException $e) {      $this->SetError($e->getMessage());      if ($this->exceptions) {        throw $e;      }      echo $e->getMessage()."\n";      return false;    }  }  /*** Sends mail using the $Sendmail program.* @param string $header The message headers* @param string $body The message body* @access protected* @return bool*/  protected function SendmailSend($header, $body) {    if ($this->Sender != '') {      $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));    } else {      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));    }    if ($this->SingleTo === true) {      foreach ($this->SingleToArray as $key => $val) {        if(!@$mail = popen($sendmail, 'w')) {          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);        }        fputs($mail, "To: " . $val . "\n");        fputs($mail, $header);        fputs($mail, $body);        $result = pclose($mail);        // implement call back function if it exists        $isSent = ($result == 0) ? 1 : 0;        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);        if($result != 0) {          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);        }      }    } else {      if(!@$mail = popen($sendmail, 'w')) {        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);      }      fputs($mail, $header);      fputs($mail, $body);      $result = pclose($mail);      // implement call back function if it exists      $isSent = ($result == 0) ? 1 : 0;      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);      if($result != 0) {        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);      }    }    return true;  }  /*** Sends mail using the PHP mail() function.* @param string $header The message headers* @param string $body The message body* @access protected* @return bool*/  protected function MailSend($header, $body) {    $toArr = array();    foreach($this->to as $t) {      $toArr[] = $this->AddrFormat($t);    }    $to = implode(', ', $toArr);    if (empty($this->Sender)) {      $params = "-oi -f %s";    } else {      $params = sprintf("-oi -f %s", $this->Sender);    }    if ($this->Sender != '' and !ini_get('safe_mode')) {      $old_from = ini_get('sendmail_from');      ini_set('sendmail_from', $this->Sender);      if ($this->SingleTo === true && count($toArr) > 1) {        foreach ($toArr as $key => $val) {          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);          // implement call back function if it exists          $isSent = ($rt == 1) ? 1 : 0;          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);        }      } else {        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);        // implement call back function if it exists        $isSent = ($rt == 1) ? 1 : 0;        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);      }    } else {      if ($this->SingleTo === true && count($toArr) > 1) {        foreach ($toArr as $key => $val) {          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);          // implement call back function if it exists          $isSent = ($rt == 1) ? 1 : 0;          $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);        }      } else {        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);        // implement call back function if it exists        $isSent = ($rt == 1) ? 1 : 0;        $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);      }    }    if (isset($old_from)) {      ini_set('sendmail_from', $old_from);    }    if(!$rt) {      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);    }    return true;  }  /*** Sends mail via SMTP using PhpSMTP* Returns false if there is a bad MAIL FROM, RCPT, or DATA input.* @param string $header The message headers* @param string $body The message body* @uses SMTP* @access protected* @return bool*/  protected function SmtpSend($header, $body) {    require_once $this->PluginDir . 'anthill.smtp.php';    //require_once $this->PluginDir . 'class.smtp.php';    $bad_rcpt = array();    if(!$this->SmtpConnect()) {      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);    }    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;    if(!$this->smtp->Mail($smtp_from)) {      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);    }    // Attempt to send attach all recipients    foreach($this->to as $to) {      if (!$this->smtp->Recipient($to[0])) {        $bad_rcpt[] = $to[0];        // implement call back function if it exists        $isSent = 0;        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);      } else {        // implement call back function if it exists        $isSent = 1;        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);      }    }    foreach($this->cc as $cc) {      if (!$this->smtp->Recipient($cc[0])) {        $bad_rcpt[] = $cc[0];        // implement call back function if it exists        $isSent = 0;        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);      } else {        // implement call back function if it exists        $isSent = 1;        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);      }    }    foreach($this->bcc as $bcc) {      if (!$this->smtp->Recipient($bcc[0])) {        $bad_rcpt[] = $bcc[0];        // implement call back function if it exists        $isSent = 0;        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);      } else {        // implement call back function if it exists        $isSent = 1;        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);      }    }    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses      $badaddresses = implode(', ', $bad_rcpt);      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);    }    if(!$this->smtp->Data($header . $body)) {      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);    }    if($this->SMTPKeepAlive == true) {      $this->smtp->Reset();    }    return true;  }  /*** Initiates a connection to an SMTP server.* Returns false if the operation failed.* @uses SMTP* @access public* @return bool*/  public function SmtpConnect() {    if(is_null($this->smtp)) {      $this->smtp = new SMTP();    }    $this->smtp->do_debug = $this->SMTPDebug;    $hosts = explode(';', $this->Host);    $index = 0;    $connection = $this->smtp->Connected();    // Retry while there is no connection    try {      while($index < count($hosts) && !$connection) {        $hostinfo = array();        if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {          $host = $hostinfo[1];          $port = $hostinfo[2];        } else {          $host = $hosts[$index];          $port = $this->Port;        }        $tls = ($this->SMTPSecure == 'tls');        $ssl = ($this->SMTPSecure == 'ssl');        if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {          $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());          $this->smtp->Hello($hello);          if ($tls) {            if (!$this->smtp->StartTLS()) {              throw new phpmailerException($this->Lang('tls'));            }            //We must resend HELO after tls negotiation            $this->smtp->Hello($hello);          }          $connection = true;          if ($this->SMTPAuth) {            if (!$this->smtp->Authenticate($this->Username, $this->Password)) {              throw new phpmailerException($this->Lang('authenticate'));            }          }        }        $index++;        if (!$connection) {          throw new phpmailerException($this->Lang('connect_host'));        }      }    } catch (phpmailerException $e) {      $this->smtp->Reset();      throw $e;    }    return true;  }  /*** Closes the active SMTP session if one exists.* @return void*/  public function SmtpClose() {    if(!is_null($this->smtp)) {      if($this->smtp->Connected()) {        $this->smtp->Quit();        $this->smtp->Close();      }    }  }  /*** Sets the language for all class error messages.* Returns false if it cannot load the language file. The default language is English.* @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")* @param string $lang_path Path to the language file directory* @access public*/  function SetLanguage($langcode = 'en', $lang_path = 'language/') {    //Define full set of translatable strings    $PHPMAILER_LANG = array(      'provide_address' => 'You must provide at least one recipient email address.',      'mailer_not_supported' => ' mailer is not supported.',      'execute' => 'Could not execute: ',      'instantiate' => 'Could not instantiate mail function.',      'authenticate' => 'SMTP Error: Could not authenticate.',      'from_failed' => 'The following From address failed: ',      'recipients_failed' => 'SMTP Error: The following recipients failed: ',      'data_not_accepted' => 'SMTP Error: Data not accepted.',      'connect_host' => 'SMTP Error: Could not connect to SMTP host.',      'file_access' => 'Could not access file: ',      'file_open' => 'File Error: Could not open file: ',      'encoding' => 'Unknown encoding: ',      'signing' => 'Signing Error: ',      'smtp_error' => 'SMTP server error: ',      'empty_message' => 'Message body empty',      'invalid_address' => 'Invalid address',      'variable_set' => 'Cannot set or reset variable: '    );    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!    $l = true;    if ($langcode != 'en') { //There is no English translation file      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';    }    $this->language = $PHPMAILER_LANG;    return ($l == true); //Returns false if language not found  }  /*** Return the current array of language strings* @return array*/  public function GetTranslations() {    return $this->language;  }  /////////////////////////////////////////////////  // METHODS, MESSAGE CREATION  /////////////////////////////////////////////////  /*** Creates recipient headers.* @access public* @return string*/  public function AddrAppend($type, $addr) {    $addr_str = $type . ': ';    $addresses = array();    foreach ($addr as $a) {      $addresses[] = $this->AddrFormat($a);    }    $addr_str .= implode(', ', $addresses);    $addr_str .= $this->LE;    return $addr_str;  }  /*** Formats an address correctly.* @access public* @return string*/  public function AddrFormat($addr) {    if (empty($addr[1])) {      return $this->SecureHeader($addr[0]);    } else {      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";    }  }  /*** Wraps message for use with mailers that do not* automatically perform wrapping and for quoted-printable.* Original written by philippe.* @param string $message The message to wrap* @param integer $length The line length to wrap to* @param boolean $qp_mode Whether to run in Quoted-Printable mode* @access public* @return string*/  public function WrapText($message, $length, $qp_mode = false) {    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;    // If utf-8 encoding is used, we will need to make sure we don't    // split multibyte characters when we wrap    $is_utf8 = (strtolower($this->CharSet) == "utf-8");    $message = $this->FixEOL($message);    if (substr($message, -1) == $this->LE) {      $message = substr($message, 0, -1);    }    $line = explode($this->LE, $message);    $message = '';    for ($i = 0 ;$i < count($line); $i++) {      $line_part = explode(' ', $line[$i]);      $buf = '';      for ($e = 0; $e<count($line_part); $e++) {        $word = $line_part[$e];        if ($qp_mode and (strlen($word) > $length)) {          $space_left = $length - strlen($buf) - 1;          if ($e != 0) {            if ($space_left > 20) {              $len = $space_left;              if ($is_utf8) {                $len = $this->UTF8CharBoundary($word, $len);              } elseif (substr($word, $len - 1, 1) == "=") {                $len--;              } elseif (substr($word, $len - 2, 1) == "=") {                $len -= 2;              }              $part = substr($word, 0, $len);              $word = substr($word, $len);              $buf .= ' ' . $part;              $message .= $buf . sprintf("=%s", $this->LE);            } else {              $message .= $buf . $soft_break;            }            $buf = '';          }          while (strlen($word) > 0) {            $len = $length;            if ($is_utf8) {              $len = $this->UTF8CharBoundary($word, $len);            } elseif (substr($word, $len - 1, 1) == "=") {              $len--;            } elseif (substr($word, $len - 2, 1) == "=") {              $len -= 2;            }            $part = substr($word, 0, $len);            $word = substr($word, $len);            if (strlen($word) > 0) {              $message .= $part . sprintf("=%s", $this->LE);            } else {              $buf = $part;            }          }        } else {          $buf_o = $buf;          $buf .= ($e == 0) ? $word : (' ' . $word);          if (strlen($buf) > $length and $buf_o != '') {            $message .= $buf_o . $soft_break;            $buf = $word;          }        }      }      $message .= $buf . $this->LE;    }    return $message;  }  /*** Finds last character boundary prior to maxLength in a utf-8* quoted (printable) encoded string.* Original written by Colin Brown.* @access public* @param string $encodedText utf-8 QP text* @param int $maxLength find last character boundary prior to this length* @return int*/  public function UTF8CharBoundary($encodedText, $maxLength) {    $foundSplitPos = false;    $lookBack = 3;    while (!$foundSplitPos) {      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);      $encodedCharPos = strpos($lastChunk, "=");      if ($encodedCharPos !== false) {        // Found start of encoded character byte within $lookBack block.        // Check the encoded byte value (the 2 chars after the '=')        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);        $dec = hexdec($hex);        if ($dec < 128) { // Single byte character.          // If the encoded char was found at pos 0, it will fit          // otherwise reduce maxLength to start of the encoded char          $maxLength = ($encodedCharPos == 0) ? $maxLength :          $maxLength - ($lookBack - $encodedCharPos);          $foundSplitPos = true;        } elseif ($dec >= 192) { // First byte of a multi byte character          // Reduce maxLength to split at start of character          $maxLength = $maxLength - ($lookBack - $encodedCharPos);          $foundSplitPos = true;        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back          $lookBack += 3;        }      } else {        // No encoded character found        $foundSplitPos = true;      }    }    return $maxLength;  }  /*** Set the body wrapping.* @access public* @return void*/  public function SetWordWrap() {    if($this->WordWrap < 1) {      return;    }    switch($this->message_type) {      case 'alt':      case 'alt_inline':      case 'alt_attach':      case 'alt_inline_attach':        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);        break;      default:        $this->Body = $this->WrapText($this->Body, $this->WordWrap);        break;    }  }  /*** Assembles message header.* @access public* @return string The assembled header*/  public function CreateHeader() {    $result = '';    // Set the boundaries    $uniq_id = md5(uniqid(time()));    $this->boundary[1] = 'b1_' . $uniq_id;    $this->boundary[2] = 'b2_' . $uniq_id;    $this->boundary[3] = 'b3_' . $uniq_id;    $result .= $this->HeaderLine('Date', self::RFCDate());    if($this->Sender == '') {      $result .= $this->HeaderLine('Return-Path', trim($this->From));    } else {      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));    }    // To be created automatically by mail()    if($this->Mailer != 'mail') {      if ($this->SingleTo === true) {        foreach($this->to as $t) {          $this->SingleToArray[] = $this->AddrFormat($t);        }      } else {        if(count($this->to) > 0) {          $result .= $this->AddrAppend('To', $this->to);        } elseif (count($this->cc) == 0) {          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');        }      }    }    $from = array();    $from[0][0] = trim($this->From);    $from[0][1] = $this->FromName;    $result .= $this->AddrAppend('From', $from);    // sendmail and mail() extract Cc from the header before sending    if(count($this->cc) > 0) {      $result .= $this->AddrAppend('Cc', $this->cc);    }    // sendmail and mail() extract Bcc from the header before sending    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {      $result .= $this->AddrAppend('Bcc', $this->bcc);    }    if(count($this->ReplyTo) > 0) {      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);    }    // mail() sets the subject itself    if($this->Mailer != 'mail') {      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));    }    if($this->MessageID != '') {      $result .= $this->HeaderLine('Message-ID', $this->MessageID);    } else {      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);    }    $result .= $this->HeaderLine('X-Priority', $this->Priority);    if($this->XMailer) {      $result .= $this->HeaderLine('X-Mailer', $this->XMailer);    } else {      $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');    }    if($this->ConfirmReadingTo != '') {      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');    }    // Add custom headers    for($index = 0; $index < count($this->CustomHeader); $index++) {      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));    }    if (!$this->sign_key_file) {      $result .= $this->HeaderLine('MIME-Version', '1.0');      $result .= $this->GetMailMIME();    }    return $result;  }  /*** Returns the message MIME.* @access public* @return string*/  public function GetMailMIME() {    $result = '';    switch($this->message_type) {      case 'plain':        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');        break;      case 'inline':        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');        break;      case 'attach':      case 'inline_attach':      case 'alt_attach':      case 'alt_inline_attach':        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');        break;      case 'alt':      case 'alt_inline':        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');       

Staff
17,357 Points
2014-09-24 1:27 pm
Hello Code_me,

Sorry that your PHPmailer code is giving your problems. These solutions are third party solutions and we do not provide custom coding. However, we do try to point you in the right direction. I did a little searching and StackOverflow advises that you turn on debugging. The post goes on to say that you should check the path assigned in the code to make sure it is correct. Here's the post for your reference. If you want us to continue to help you, it help to know if you have an account with us, or if you can provide us any error messages that you're seeing.

Kindest regards,
Arnel C.
n/a Points
2014-09-26 8:01 am

Hello sir

I'm sending the message form localhost using gmail server to gmail id and some other mail id.I'm not using your server.I am using mail() function of php.When execute thru xampp server,I'm getting message sent.No errors.But if Icheck in gmail account or any other,there r no mails,not even in spam.I did the settings in php.ini ans sendmail.ini as you had guided(xampp settings for gmail server)

What may be the problem?

Staff
17,357 Points
2014-09-26 12:16 pm
Hello Kgh,

Thanks for the question! The problem you're having sounds more like an issue with XAMPP server settings. We do not support it, but you may want to take a look at several people have posted here in response to a similar issue. They provide a solution in regards to settings that you may be missing on XAMPP.

Regards,
Arnel C.
n/a Points
2014-10-06 11:47 am

Everything worked fine thanks! 

Now a question:

When the form is filled and i click send, it redirects me to the php page with the echo text. Is there any way to get back to the previous page?? THanks !

Staff
17,357 Points
2014-10-06 12:50 pm
Hello Jose,

Thanks for the question! You would need to include a link that basically points to the page that originally directed your viewer to the form. You can include the link in the same area as the echoed text.

I hope this helps to answer your question. Please let us know if you require any further assistance.

Regards,
Arnel C.
n/a Points
2014-10-06 12:57 pm

Something like this?

//echo 'Message has been sent';

header("Location: success.html");exit;

It doesnt seem to work though..

Staff
19,592 Points
2014-10-06 1:29 pm
Hello Jose,

header("Location: success.php"); is the correct format and should work, is there an error message that you are getting?

Kindest Regards,
Scott M
n/a Points
2014-10-23 9:07 am

This article is really helpful and it works. But it would really help me if it can generate a scheduled email. Like the email would only be sent at a certain hour and date that I would set earlier. Is there any function for this?

Staff
19,592 Points
2014-10-23 10:17 am
Hello Shasha,

This phpmailer article does not have that functionality built in, so there is not a way to send an email at a specified time. That would require a custom coded solution.

Kindest Regards,
Scott M
n/a Points
2014-10-23 11:25 am

Can you recommend me any way or clues of doing it?

Staff
9,684 Points
2014-10-23 2:24 pm
Hello Shasha,

Thank you for contacting us today. I found a forum post via Google search, where they are suggesting you store it in a database, and set up a cron job.

I hope this helps,
John-Paul
n/a Points
2014-10-25 8:51 am

How can we get SMTP username and password for our email,would you give an idea please?

Staff
9,684 Points
2014-10-27 7:04 am
Hello Suresh,

Thank you for your question. Your SMTP Username will be your email address, and the password will be for that email account.

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

Thank you,
John-Paul

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.

137 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!