PHPMailer is a highly popular, actively developed email-sending library for PHP hosting. And it’s open source.
Below, we’ll give you a quick and easy example of a working script you can use in your local development environment or live on your InMotion Hosting server.
For more information about PHPMailer, or to contribute, check out the PHPMailer GitHub page. Looking for a top-notch PHP web host? You’ve come to the right place.
Install the PHPMailer Dependencies
You may be excited to get this code into your app, but first you need to make sure you’ve installed the necessary code library.
For this example, we’re going to be installing PHPMailer with Composer, since that is the preferred method for a great many PHP developers.
composer require phpmailer/phpmailer
That’s it! If you don’t have one already, composer will create your “vendor” directory and populate your autoload file.
Add The Code to Your App
Now is the fun part. But before running this code, make sure to change some of the example text we used below with your own information.
Sample | Replace with |
---|---|
[email protected] | Your sender email address |
mail.example.com | Your SMTP server name |
‘password’ | The sender email password |
[email protected] | The recipient email address |
Name of sender | Desired sender name |
Name of recipient | Desired recipient name |
Once you have switched out the example text, make sure to select the right development mode. This code can be used on your local server or a live production environment.
- For local development
- keep the
$developmentMode
variable set totrue
- For live server
- change the
$developmentMode
variable tofalse
We’re ready to begin.
<?php require "vendor/autoload.php"; $robo = '[email protected]'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $developmentMode = true; $mailer = new PHPMailer($developmentMode); try { $mailer->SMTPDebug = 2; $mailer->isSMTP(); if ($developmentMode) { $mailer->SMTPOptions = [ 'ssl'=> [ 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ] ]; } $mailer->Host = 'mail.example.com'; $mailer->SMTPAuth = true; $mailer->Username = '[email protected]'; $mailer->Password = 'password'; $mailer->SMTPSecure = 'tls'; $mailer->Port = 587; $mailer->setFrom('[email protected]', 'Name of sender'); $mailer->addAddress('[email protected]', 'Name of recipient'); $mailer->isHTML(true); $mailer->Subject = 'PHPMailer Test'; $mailer->Body = 'This is a <b>SAMPLE<b> email sent through <b>PHPMailer<b>'; $mailer->send(); $mailer->ClearAllRecipients(); echo "MAIL HAS BEEN SENT SUCCESSFULLY"; } catch (Exception $e) { echo "EMAIL SENDING FAILED. INFO: " . $mailer->ErrorInfo; } ?>
Source: MyPHPnotes
A note about the ?>
tag
In PHP, the ?>
tag at the end of a file is optional and can be omitted. The ?>
tag denotes the end of the PHP code block and signifies that the parser should switch back to HTML mode. Including the ?>
tag is necessary only when there is additional non-PHP code or HTML following the PHP block.
Here are a few scenarios to help you understand when to include or exclude the ?>
tag:
Pure PHP code
If your file contains only PHP code and does not include any HTML or non-PHP code after the closing tag, it is recommended to exclude the ?>
tag. Omitting it helps to avoid any accidental whitespace or line breaks after the closing tag, which could unintentionally be sent to the browser.
<?php // PHP code here // No closing tag needed
Mix of PHP and HTML code
When your file contains both PHP and HTML code, it is generally best to exclude the ?>
tag at the end of the PHP sections. This prevents any accidental output of whitespace or line breaks to the browser.
<?php // PHP code here ?> <html> <!-- HTML code here --> </html> <?php // More PHP code here
PHP code followed by non-PHP code
If your PHP code is followed by non-PHP code, such as JavaScript or plain text, you should include the ?>
tag after the PHP code block and before the non-PHP code.
<?php // PHP code here ?> <script> // JavaScript code here </script> <?php // More PHP code here
Remember, the inclusion or exclusion of the ?>
tag is a matter of preference and coding style. However, it is important to maintain consistency throughout your codebase to ensure readability and minimize any potential issues.
Well done! You’ve completed this tutorial. Now, if you have filled in all the correct data, you should be able to run this script in your browser and send mail to the recipient.
hello I am getting issues this
mail send … ERROR!Array ( [type] => 2 [message] => file_get_contents(): Filename cannot be empty [file] => /home/servicen/public_html/mailer.php [line] => 21 )
with in this code anyone help me ?
<?php
$filenameee = $_FILES['file']['name'];
$fileName = $_FILES['file']['tmp_name'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$usermessage = $_POST['message'];
$message ="Name = ". $name . "\r\n Email = " . $email . "\r\n Phone = " . $phone . "\r\n Message =" . $usermessage;
$subject ="My email subject";
$fromname ="My Website Name";
$fromemail = '[email protected]'; //if u dont have an email create one on your cpanel
$mailto = '[email protected]'; //the email which u want to recv this email
$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers = "From: ".$fromname." " . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $message . $eol;
// attachment
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "mail send ... OK"; // do what you want after sending the email
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}
Hello Lukas – The code you’re using is not the PHPmail code that we have provided in the article. As a rule, we do not normally debug code. I would recommend that you go to the GIT page for PHPMail and then post your question to the community there. If you’re using older code, or if someone there recognizes it, then they may be able to help you get on track. You can also try going through the error message, you should see why the file name is seen as “empty”.
TLDR:
The example script is off just a little:
You must set:
$mailer->SMTPSecure = 'ssl';
Other hints
Testing email host config with thunderbird
———-
I learned a whole bunch configuring PHPMailer for my new site.
Here’s what worked for me:
Installing phpmailer:
Sign into your Cpanel, and go to Terminal, it’s in ‘Advance’ way at the bottom.
This will plop you into a command line at your root level directory.
Type or paste the command:
‘composer require phpmailer/phpmailer’
Hit return.
At first you will see nothing.
Give it a minute, literally,
and you should see the script start spitting back to the terminal as it installs phpMailer.
When the process is finished, it should have created two new folders: ‘vendor’ and ‘.composer’
The phpMailer code actually resides in:
vendor/phpmailer/phpmailer
Find your outgoing SMTP email server info at:
CPanel’s Email Accounts Section
Click on ‘Connected Devices’ for the email user you want to send as.
I created a special user:
[email protected]
password: yourPassword
Test the settings from you found in Cpanel by setting up a mail client to connect and send outgoing mail.
I used Thunderbird, which can automatically configure the connection just from ‘secure265.inmotionhosting.com’.
Once this works, edit those settings directly into test email php script provided at the top of this article.
Call it something like mailTest.php
One important difference from the example:
$mailer->SMTPSecure = 'ssl';
The script should look something like this:
SMTPDebug = 3;
$mailer->isSMTP();
if ($developmentMode) {
$mailer->SMTPOptions = [
'ssl'=> [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
];
}
$mailer->Host = 'secure265.inmotionhosting.com';
$mailer->SMTPAuth = true;
$mailer->Username = '[email protected]';
$mailer->Password = 'thePassword';
$mailer->SMTPSecure = 'ssl';
$mailer->Port = 465;
$mailer->setFrom('[email protected]', 'Your Company Contact Form');
$mailer->addAddress('[email protected]', 'First Last');
$mailer->isHTML(true);
$mailer->Subject = 'PHPMailer Test';
$mailer->Body = 'This is a SAMPLE email sent through PHPMailer DevMode TRUE';
$mailer->send();
$mailer->ClearAllRecipients();
echo "MAIL HAS BEEN SENT SUCCESSFULLY";
} catch (Exception $e) {
echo "EMAIL SENDING FAILED. INFO: " . $mailer->ErrorInfo;
}
?>
That lines at the top:
‘require “vendor/autoload.php”;’
indicates where the script is going to look for the phpMailer source.
You must upload the script to your root directory, the same location as the newly created ‘vendor’ folder.
Upload using the CPanel File Manager, or an FTP client such as Fetch or Filezilla.
Once the file is uploaded, go back to the console.
Make sure you are in the root directory and can find the file:
ls -l mailTest.php
Check the syntax of the file by running:
php -l mailTest.php
which should return: ‘No syntax errors detected in mailTester.php’
Finally, you are ready to test the script by running:
php mailTest.php
Since
$mailer->SMTPDebug = 3;
You should get many lines of output, hopefully with some indication that you have successfully connected to the mail server,
and that the message was sent.
I first started testing with the general inmotion hosting outgoing email server:
$mailer->Host = 'secure265.inmotionhosting.com';
$mailer->SMTPOptions = [
'ssl'=> [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
];
Once I had my domain setup with an automatic Cpanel SSL certificate, I was able to change this to:
$mailer->Host = 'mail.mydomain.com';
with no SMTPOptions
Once the basic test script was working, I integrated to the settings into my final phpMailer script:
isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'mail.mydomain.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'ThePassword';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'My Company Contact Form');
$mail->addAddress('[email protected]');
$mail->addAddress('[email protected]');
$mail->addAddress('[email protected]');
$mail->Subject = 'Company Contact Form Activity';
$mail->Body = $incomingFormData;
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "MessageSent";
}
}
?>
This is invoked from my contactForm.php script, which resides in public_html, and references the phpMailer script, one level up (‘../sendEmail.php’) in the root directory. In general the best security practice is to keep mailing script a level above public_html to minimize any chance of it being inadvertently served to the outside.
It is possible to install PHPMailer on shared servers?
If so, I am not clear how to do so.
I do not see it listed in apps that can be installed via Softaculous in cPanel.
I want to use PHPMailer security features when sending email via HTML Forms from static HTML webpages.
If it is not currently possible currently,
1) what would you recommend in its place, and
2) is this something that would be considered in the future?
Hello sherylhohman,
Yes, you can install PHPMailer on Shared Hosting accounts. However, it is not available to install via Softaculous and must be installed via Composer.
Hi,
I am facing on different issue. I am not geting FromName in mail. I have set the from address and name in method setFrom(‘[email protected]’, ‘Chandan singh’) and i got the mail but not showing the name ‘Chandan singh’ . it is showing ‘support’ in name.
PHP Version : 7.0.32
OS : ubuntu0.16.04.1
X-Mailer: PHPMailer 6.0.5
But when i run same code on local machine on. then getting mail and showing FromName ‘Chandan singh’ in my mail. My Machine configration
Php Version : 7.1.20
OS : ubuntu14.04.1
X-Mailer: PHPMailer 6.0.5
I am not able to findout root cause of it.
Kindly Help Me…
I regret that the above snippets are not working for you. However, this code is available on an “as is” basis. We’re not able to provide individual developer support. I suggest checking PHP-related forums or using something like Xdebug in your PHP development environment.
Hey,,
tell me, if i put my SMPT server credentials like host,password , etc. is it secure?
how?
If you use the recommended secure settings for SMTP connections, then the data will be transferred using encryption, which is secure. I hope this helps!
How can i add email list in phpmailer script?
That topic is not covered in this guide but I did find some information via online search on how to use phpmailer to send to lists.
Thank you,
John-Paul
It would be an added great help to show how you would handle, say validation on the html form email field. How to use the validation email error to stop the PHPmailer code from executing.
There is validation in the PHP code itself, but this is an older article offered as is. We are planning do updated PHP content in the near future that will reflect current standards and practices. Thanks for your feedback!
Hallo everyone! Does it exist any way to encrypt the $mail->Username and the $mail->Password? Is it safe to have it in plain text?
Thanks!
It is safe as long as you have PHP installed on you server and no one else has access to the files that you do not want to have access to that password. You can encrypt the password however you would have to have the means to decrypt it in those files aswell so anyone who would have access to it when it was encrypted would see that also and just decrypt it.
I’m receiving an email when I hit “Submit” so that’s good but the email is blank and the redirect to the thank-you.php page is not working.
If the message is blank then that means your message variable is most likely not getting passed to the PHP script, I would ensure that you have the the correct variable in your form for the message field. If you are trying to redirect after the form i would recommend using JavaScript to submit the form and redirect the user.
We have been hosting our website and email with one company, one account. What we did is that we have moved website hosting to a different hosting company and we have left the email service with the previous host.
This means we are hosting our website at Company ABC and we are hosting our email at Company XYZ. It works fine, the problem is we now want to use PHPMailer where we have hosted the website.The challenge is we are getting a “Could Not Authenticate” error.
We have been using PHPMailer for the past 3 years and we have never struggled. Can you help?
I recommend checking your SMTP settings for accuracy. Also, ensure your “Email Routing” is set to “Remote Mail Exchanger”.
Thank you,
John-Paul
Thank you for a very detailed video but I wanted to ask is there not a way to just create a page to which the sender can input their own email address instead of having to set one up? It would be nice to be able to have a small script that will give all fields blank & required to be filled out by the sender.
Thank you again for a great video!
You can do this by creating an HTML form and sending the variables to PHP via POST or GET, you can find documentation on how to do that here.
You will need to ensure the domain you are sending emails from has an SPF record that allows the email to be sent from the server/IP that your script is using. You will also need to ensure the emails your script is sending comply with googles guidelines as well.
Everything working fine. But the email went to my Gmail spam folder.
Any solution to get this right ?
How can I get emails send to Inbox instead of spam folder.
Thanks
Don’t host with GoDaddy. They have a bad reputation for blocking ports like 25 or even 587.
Hi
I got this problem with the code
Error HTTP 500
Hello.
What code are you using?
Where in your site are you adding this code?
What are the steps to replicate what you are doing when you receive this error message?
Unfortunately, without more details I can not advise why you are receiving a 500 error. You may find more help using our guide on 500 Internal Server Error.
I have a one error
Could not execute: /var/qmail/bin/sendmail/
What is my problem? Help me please
Typically an error like that indicates that the script was unable to access the file it needs (indicated by the file contained in the error message). I would recommend checking the permissions and ownership to ensure the script is allowed to use that file for whatever reason it needs to.
this i got when i upload the script.
Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone ‘UTC’ for now, but please set date.timezone to select your timezone. in /home/rayhi2gb/public_html/phpmailertest/PHPMailer_5.2.0/class.phpmailer.php on line 2078Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone ‘UTC’ for now, but please set date.timezone to select your timezone. in /home/rayhi2gb/public_html/phpmailertest/PHPMailer_5.2.0/class.phpmailer.php on line 2082SMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
You may be best advised to check your PHP version and upgrade to the latest version if you are not there already.
Can’t get my code to work.. i removed the email addresses, any advice? i tested on my computer and works, but once upload on inmotion, nothing happens.
<
?phpdate_default_timezone_set("America/Santiago");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/PHPMailer/phpMailer/src/Exception.php';
require 'vendor/PHPMailer/phpMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/phpMailer/src/SMTP.php';
$mail = new PHPMailer;
$error = false;
$firstName = isset( $_POST['firstName'] ) ? filter_var($_POST['firstName'], FILTER_SANITIZE_STRING) : "";
$lastName = isset( $_POST['lastName'] ) ? filter_var($_POST['lastName'], FILTER_SANITIZE_STRING) : "";
$emailAddress = isset( $_POST['emailAddress'] ) ? filter_var($_POST['emailAddress'], FILTER_SANITIZE_EMAIL) : "";
$phoneNumber = isset( $_POST['phoneNumber'] ) ? filter_var($_POST['phoneNumber'], FILTER_SANITIZE_NUMBER_INT) : "";
$radio_destination = isset($_POST['radio_destination']) ? $_POST['radio_destination'] : "";
$desired_destination = isset( $_POST['destination'] ) ? filter_var($_POST['destination'], FILTER_SANITIZE_STRING) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
$luxury = isset($_POST['luxury']) ? $_POST['luxury'] : "no, gracias";
if($firstName != ""){ $firstName = trim($firstName);
if ($firstName == "" OR !preg_match("/^[\p{L}'][ \p{L}'-]*[\p{L}]$/u",$firstName) OR strlen($firstName) <
2){
$error = true;
}
}else { $error = true;
}
if($lastName != ""){
$lastName = trim($lastName);
if ($lastName == "" OR !preg_match("/^[\p{L}'][ \p{L}'-]*[\p{L}]$/u",$lastName) OR strlen($lastName) <
2){
$error = true;
}
}else { $error = true;
}
if($emailAddress != ""){
emailAddress = filter_var($emailAddress, FILTER_VALIDATE_EMAIL);
if($emailAddress == ""){
$error = true;
}
}else { $error = true;
}
if($message != ""){ $msg_length = preg_match_all('/[^ ]/', $message);
if ($message !== "" &
&
$msg_length <
20){$error = true;
}
}else {$message = "x";
}
$body = '<
html>
<
body style="margin:0!important;
padding:20px!important;
font-family: Calibri, Verdana, Arial, sans-serif;
>
<
table border="0" cellpadding="0" cellspacing="0" width="100%" style="display:block;
font-size: 15px;
line-height: 1.4;
margin:0 auto;
">
<
tr>
<
td>
<
h2 style="display:block;
font-weight: normal;
font-size: 25px;
color: #ff8b0f;
margin-bottom:.625em;
">
' . htmlentities('Informació
n de contacto') . '<
/h2>
<
/td>
<
/tr>
<
tr>
<
td>
<
strong>
Nombre: <
/strong>
'. htmlentities($firstName) . ' ' . htmlentities($lastName) . '<
/td>
<
/tr>
<
br>
<
tr>
<
td>
<
strong>
' . htmlentities('Direcció
n de e-mail: ') . '<
/strong>
' . strip_tags($emailAddress) . '<
/td>
<
/tr>
<
br>
<
tr>
<
td>
<
strong>
' . htmlentities('Nú
mero de telé
fono: ') . '<
/strong>
' . htmlentities($phoneNumber) . '<
/td>
<
/tr>
<
br>
<
tr>
<
td>
<
h2 style="display:block;
font-weight:normal;
font-size: 25px;
color: #ff8b0f;
margin-top:2em;
margin-bottom:.625em">
' . htmlentities('Informació
n del Viaje') . '<
/h2>
<
/td>
<
/tr>
<
tr>
<
td>
<
strong>
' . htmlentities('¿
Nos puedes decir dó
nde quieres viajar?') . '<
/strong>
<
br/>
<
/td>
<
/tr>
<
tr>
<
td>
' . htmlentities($radio_destination) . ' ' . htmlentities($desired_destination) . '<
/td>
<
/tr>
<
br>
<
br>
<
tr>
<
td>
<
strong>
' . htmlentities('¿
Tienes una pregunta o comentario?') . '<
/strong>
<
br/>
<
/td>
<
/tr>
<
tr>
<
td>
' . htmlentities($message) . '<
/td>
<
/tr>
<
br>
<
br>
<
tr>
<
td>
<
strong>
' . htmlentities('¿
Deseas un viaje lujoso?') . '<
/strong>
<
br/>
<
/td>
<
/tr>
<
tr>
<
td>
' . htmlentities($luxury) . '<
/td>
<
/tr>
<
/table>
<
/body>
<
/html>
';
try {
//Server settings
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'secure156.inmotionhosting.com';
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'password';
$mail->SMTPSecure = 'ssl';
//Recipients
$mail->setFrom('[email protected]', 'name');
$mail->addAddress('[email protected]');
//, 'Bá
rbara Thayer');
// Add a recipient
$mail->addReplyTo('[email protected]', 'Info');
//Content
$mail->isHTML(true);
// Set email format to HTML
$mail->Subject = 'Tienes un nuevo mensaje del sitio web';
$mail->Body = $body;
//$mail->AltBody = ;
if(isset($_POST['urlFool']) &
&
$_POST['urlFool'] == '' &
&
$error != true){
$mail->
send();
}} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}?>
As long as you have the correct server references and correct credentials then, it should work. It is possible that server security is blocking is blocking the script from working. Check out this article to see if disabling mod security rules helps with getting your code working. We normally do not provide coding support as it is beyond the scope of technical support.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
I need some help here.
I am geting the following error message:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
I recommend checking your file paths for typos or misspellings. Also, review the files to ensure they are in the correct location.
Thank you,
John-Paul
Could you clarify what you mean by public_html?
Sure! public_html is meant to reference the home directory for the domain/website you are uploading the file to. For a primary domain in cPanel, the home directory would default to public_html. I hope this helps!
Is it normal for the server to take over 21 seconds to reply? It only took 2 seconds to send the message to the server.
<[email protected]>2017-09-14 22:15:14 CLIENT -> SERVER: --b1_e31b5e88936f8a2cc74050d43cc7f91d--
2017-09-14 22:15:14 CLIENT -> SERVER:
2017-09-14 22:15:14 CLIENT -> SERVER: .
2017-09-14 22:15:35 SERVER -> CLIENT: 250 OK id=1dscPj-000gRL-8s
2017-09-14 22:15:35 CLIENT -> SERVER: QUIT
Hello!
It’s possible that due to the load on the server the email is delayed a bit, rather than immediately being processed. The server should be delegating resources accordingly. Also, depending on the configuration of your server’s Exim mail service, there may be a queue or filters that could cause a few seconds delay in handling emails. With the details you have provided in your comment, there is not much anyone can assess. Are you experiencing persistent email delays? Are there any delays that are longer than a minute? Is this temporarily or intermittently occurring?
In my experience, I would say that anything less than 30 seconds would be normal/acceptable. However, it shouldn’t persistently take that long, in which case you would want to begin looking into optimizing your Exim configuration and also diagnose the resource usage during the times you are experiencing extreme delays. I hope this helps!
Sincerely,
Carlos E
i tried everything..but it is not working
Are you getting any specific error message. Have you troubleshooted specific php errors?
hi.i tried to send mail using php mailer.but its showing an error
Message could not be sent.
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
<?php
require ‘PHPMailerAutoload.php’;
require ‘class.phpmailer.php’;
$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 = “mail@gmailcom”; // SMTP username
$mail->Password = “password”; // SMTP password
//$mail->SMTPAuth = true;
$mail->SMTPSecure = “tls”;
$mail->Host = “smtp.gmail.com”;
$mail->Port = 587;
$mail->From = “[email protected]”;
$mail->FromName = “name”;
//$mail->AddAddress(“[email protected]”, “Josh Adams”);
$mail->AddAddress(“[email protected]”); // name is optional
//$mail->AddReplyTo(“[email protected]”, “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”;
?>
Check your email username and password.
Hi,
I have made a contact page and for email I have added contactmailer.php. But whenever I click on submit it usually takes me to domain.com/contactmailer.php.
Along with this, I am not receiving any emails.
can you please help me with this.
thanks in advance.
Karan, when you click on submit, your form will execute whatever code is in your “action” script. If your page is redirecting in a way you don’t want, you will need to modify the code for your action script.
I am facing the problem of applying PHP mailer on my website which is currently live.I use katyaweb.com for my website hosting. I have configured and tested PHP mailer on my local machine which runs WAMP. It works pretty well on my localhost, The message can be sent successfully and the receiver receives the message as well.
But when I am applying it on my website ‘projectmedussa.com’, it gives a big error.I don’t know why? I would be very grateful if anyone could help me out.
*** Code removed by moderator ***
You will want to contact your hosting support to ask about the error message from their server. They will have a better understanding of what causing it.
I have solved my problem and please update your this tutorial for new version because in new version some steps are changing.
Anyway thanks for your help. It is really helpful to me
I got error like this while i executing my sample code.
Fatal error: Class ‘smtp’ not found in /home/smtesting/public_html/MailSender/PHPMailer-master/class.phpmailer.php on line 1466
Great video, worked wonderfully. Thank you!
Hi,
My phpMailer is working (as in sending the email text) from localhost but not attaching the image I am sending with it. I’ve tried:
$mail->addAttachment($_SERVER[‘DOCUMENT_ROOT’] . ‘/Test01/photos/’ . $myBNimg . ‘.png’);
and
$mail->addAttachment(‘https://localhost/Test01/photos/’ . $myBNimg, ‘.png’);
The image is saved in this folder before the email process starts. So what am I doing wrong?
Is the php throwing any sort of error message? What is the entire message?
It shows this below error.
Fatal error: Class ‘PHPMailer’ not found in /HOME/mail_sms.php on line 12
It sounds like you dont have all the files needed. Check to make sure you have all the correct files in the right place.
It works but, there is a red question mark appears instead of a google profile photo.
Hello Pajpaj,
As per the responses above, please check the name format and SMTP settings. If these settings are okay, you may need to speak with the Google development team for further assistance.
If you have any further questions, please let us know.
Kindest regards,
Arnel C.
When I try to send emails using SMTP I get “SMTP error”
This is my code:
require("/home/userna05/public_html/shoestring/PHPMailer_5.2.0/class.phpmailer.php");
$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 = "[email protected]"; // SMTP username
$mail->Password = "xxxxxxxxxxxx"; // SMTP password
$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);
$mail->From = "[email protected]";
$mail->FromName = "From Name";
$mail->Subject = $headline;
$Message = substr($story,0,40).'...';
// prepare email body text
$mail->Body = "";
$mail->Body = "Dear Member,"."".$Message.""."For more information, click here: https://shoestring-sailing.com/shoestring/news.php".""."Regards,".""."[email protected]";
mysql_select_db($dbase, $con);
$result = mysql_query("SELECT FirstName, Email FROM members WHERE mailme = 'p' ORDER BY FirstName");
while ($row = mysql_fetch_array($result))
{
$mail->AddAddress($row['Email']);
}
if(!$mail->Send()) // If I comment out this section I don't get the error
{
echo "Message could not be sent. ";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
Check your SMTP password and username by logging into Webmail.
What is the full “SMTP error” you are seeing?
Thank you,
John-Paul
Hi John-Paul, I have just logged in to webmail as you suggested using the same details as are in my php script. The error was just SMTP Error: nothing else. Sometimes it worked, other times it didn’t. The last time it worked, (last night) it took 7 minutes to send 50 emails during which time the page was unresponsive.
Pat, did you mean that you’re not able to login to webmail at all, or just that you’re not able to send? If you are able to login and are trying to send, which address are you trying to send to, and are you receiving any bounce back messages?
Yes I can log into webmail using the same credentials as I have used in my PHP script. The errors I am getting are “Enter message with “.” on a line by itself” (There is no line in the email that contains just a period). I also get ERROR DATA not accepted from server.
The message about entering a “.” on a line by itself is so that the mail processor knows when you are done with your message. This is akin to a closing tag in HMTL, and the mail processor will need it to know when you are done with your email body.
i install opencart Fatal error: Class ‘mysqli’ not found in /home/fazemedi/public_html/system/database/mysqli.php on line 6
Typically, the “Could not authenticate” error indicates an incorrect username, or password. I recommend checking them for accuracy/misspellings.
Thank you,
John-Paul
You will need to check your server and see if mysqli is installed.
Hi,
Will it possible to work if I change contact_us.html to contactus.php also xampp localhost? and I’m confuse of whether if I’m using xampp localhost with phpmailer, do I need to change the smtp_host:mail.example.com to smtp.live.com, if I’m using that and it won’t affect the sending of email?. Lastly, I also won’t need to change any setting from the php.ini file even though I’m using hotmail host?
SMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
Already like that and did not work on me.
As long as you are using correct SMTP settings for Google your emails should send successfully. I recommend double checking them for accuracy.
If your problems persist, I recommend reviewing your transmission logs for Google.
Thank you,
John-Paul
hi, i am using zoho account. my password contain special characters.it not acept in SMTP. . pls help. if i change the password . it works fine
Some users have had success making sure the username is written like this: $mail->Username, with the U capitalized, and the other letters all lowercase.
You will want to make sure to avoid using special characters that are reserved by PHP, such as dollar signs, question marks, greater than / less than symbols.
How to make my messages authenticated ?A red question mark appears next to the email address everytime I use both phpMailer and mail.google.com to send emails in my domain’s emails account.
Hi,
i got error message “No inputfile Specified”
please help
Hello Indrakumar,
Sorry for the problem with the inputfile. Are you using the code provided above? If you’re using different code from what is specified, then you will need to consult with a developer/programmer to determine why it’s causing the error. Editing 3rd party code is beyond the scope of our support.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
I was getting an error while sending a mail with any URL in mail body. the error was – Mailer Error: SMTP Error: Data not accepted
After that I resolved this issue with deleting $mail->IsSMTP(); code from my mail configuration.
But I hoped it was an important part in PHPmailer. Is this give any problem future?
Since that would most likely cause it to use the generic php mail function (instead of authenticating with SMTP), recipents may have issues identifying if it is a valid sender. The results will differ based on the recipients server’s rules.
Thank you,
John-Paul
Thank you very much:) You saved me.
it worked totally well. i appreciate. my Host was LOCALHOST and the rest of my webmail credentials
I got this error:
2016-10-21 12:02:57 SERVER -> CLIENT: 535 Incorrect authentication data
2016-10-21 12:02:57 SMTP ERROR: Password command failed: 535 Incorrect authentication data
2016-10-21 12:02:57 SMTP Error: Could not authenticate.
Moshin, this error indicates that you need to check your authentication information, and possibly reset your password or check your username/login name.
First I tried with my domain email ie [email protected] then tried with my gmail. In all occasions when I fill the when I click submit it returns “Message has been sent” but when I check my inbox there is no email.
I used the testemail.php in phpmailer test folder and it delivers successfully.
I’d suggest looking at the email logs on the server to see if its actually generating the email. Whats your domain? If you’re a customer of InMotion we may be able to look into it futher for you.
Hi sir. Sorry for disturbing again. I pasted my code below. Does it has any error in my SMTP setting setup? Since I can send the mail successfully from the localhost XAMPP or WAMP, but I failed to do so when I put the file in my server hosting domain public_html folder. Does I lack something.
Thank you for your reply, Sir.
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = “localhost”;
$mail->SMTPAuth = true;
$mail->SMTPSecure = “ssl”;
$mail->Host = “smtp.gmail.com”;
$mail->Port = 465;
$mail->Username = “[email protected]”;
$mail->Password = “********”;
Hi Sir. I still face the same problem. I can send the email to my hotmail account successfully vis XAMPP or WAMP in localhost, however when I posted the php and html file in my server hosting domain, I failed to send the email to my hotmail account. The SMTP setting of my file is smtp.gmail.com, ssl and port 465. And my hosted domain is www.foodizzy.com.
Thanks for your reply. Thank you
what is
SMTP username and
SMTP password.
Actually i do not want to use gmail id here. I want to send mail from my domain mail that is like [email protected]
when i send email by using gmail id here then it works well, but when i use [email protected] then it doesn’t work. So where will be problem ?
Your SMTP username would be your full email address, such as “[email protected]”. The SMTP password is the password for the email address.
You can view your email settings including SMTP username/password in cPanel at any time.
Thank you,
John-Paul
Check your email settings to confirm they are accurate.
If you are sending from a xampp/wamp server, ensure you have setup your mail services correctly. Also your mail logs may provide more detailed clues into what is happening.
Thank you,
John-Paul
Hi Sir, the mail is successful sent in localhost via XAMPP or WAMP but can’t sent through the online host server. I try many times, but the resullt still. Does it caused other issues, Sir?
Thanks for your reply.
Hi guys, the form works fine, returns “Message has been sent” but there’s nothing in my inbox, please advise
Hello Elvis,
Sorry for the problem with the message. In order to investigate this problem, we would need more information concerning the email address, any error messages, account information and steps to duplicate the issue. If you want the issue handled privately, please contact our live technical support team via email/chat/phone/skype.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
Hi Sir. Thank for your nice tutorial and the tutorial is awesome. I am facing the problem when I trying to send the mail.
The error is
Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase ‘Connection Timeout’.
I advise double-checking your SMTP settings. Adjusting the timeout time would not affect the outcome if the settings are incorrect. Make sure that you update the code samples with information relevant to your server configuration.
Website is having simple feedback form and I am expecting any visitor (unknown) can send the feedback and that feedback content will go to my site contact email id.
My query was, in above scenario, can I incorporate this “phpMailer” code ?
Yes, you can use the phpmailer for your contact form as you described.
Hello,this code run properly but i want this code for my website where 1 admin that is me recieve all mails from diffrent users where users does’t enter their password.
how can i solve this problem?please help
I’m not sure I understand what you are trying to do. Can you explain it with more details so we can assist you further?
I have a simple form in my website, asking any visitor to send feedback with email id (unknown email). Can I use php mailer to get that feedback info in my site’s email id ?
PHP mailer is the code that emails the form. I’m not sure what you mean by email ID. Can you elaborate more so I can see if it will work for your needs?
I have try but there have error
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
how I can fix that?
That is a connection error. It means that one or more of the settings are incorrect. You will need to check those.
The post was helpful, it worked perfectly.
Thanks
i have an error on mail function,here by mention the error details
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.[]
please give the solution sir/madom
Please doublecheck your SMTP settings in your code to ensure they are correct.
HI,
i face this, can check for me what wrong.
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(“/PHPMailer_5.2.0/class.phpmailer.php”);
$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 = “[email protected]”; // SMTP username
$mail->Password = “%123tcs”; // SMTP password
$mail->From = “[email protected]”;
$mail->FromName = “TCS”;
$mail->AddAddress(“[email protected]”); // 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”;
?>
Hi,
I am getting this message “Message has been sent” !
But when i check my inbox I cannot see any mail in it
Please help me out with this , or guide me where would I have gone worng
Thank you
Verify that your SMTP name and address are valid, and without misspellings. You can test your credentials by logging into Webmail.
Thank you,
John-Paul
I recommend reviewing your mail logs for additional errors, or record of your transmissions.
Thank you,
John-Paul
In an Mailer Inbox Sender please what or which email do we have to put in {Your Email} please answer needed as soon as possible .
You should enter your valid email address in this field. Typically, this would be the email you are using for sending via SMTP.
Thank you,
John-Paul
I believe I have everything setup like (or almost like) I am supposed to but receiving an authentication error.
SMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
I have tried two different hosts and have verified the accounts have SMTP access. I would appreciate it if someone can peek at the email.php to verify I am not missing somthing.
<?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”);
require(“PHPMailer_5.2.0/class.phpmailer.php”);
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// TCS Modified
// If this email.php script lives on the same server as our email server
// then set the HOST to localhost.
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = “tls”; // sets the prefix to the server
$mail->Host = “smtp-mail.outlook.com”; // specify main and backup server
$mail->Port = 587; // set the SMTP port for the server
// TCS Modified
// 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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “xxxxxxxx”; // SMTP password
// $email is the user’s email address specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST[’email’] ;
$mail->From = $email;
// TCS Modified
// below we want to set the email address we will be sending our email to.
$mail->AddAddress(“[email protected]”, “TWC Website”);
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
// TCS Modified
$mail->Subject = “Question from the 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”;
?>
Thank You!
Hello TCS Greg,
Sorry for the problem with getting your email to properly use SMTP. When I’m looking at your code, it is difficult to tell where a comment begins and ends. For future reference, if you could please format the code for a line by line display in these posts, it would help us immensely. SMTP Authentication issues have to do with the user OR the SMTP authentication settings. Otherwise, it would be a different error. I tried to find an example of it in a third party forum, and this post displays one solution. Note the specific formatting used in the solution.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
🙁 Hello
SMTP Error: Could not connect to SMTP host.
https://xefordbinhduong.net/smtp/sample.php
<?php
include (“class.smtp.php”);
include (“class.phpmailer.php”);
$mail = new PHPMailer();
$mail->setMail(‘smtp’); // smtp | mail (ham mail trong PHP), default: mail
$mail->Host = “smtpout.secureserver.net”; //
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = ‘ssl’; // ssl hoac tls, neu su dung tls thi $mail->Port la: 587
$mail->Username = “[email protected]”; // tai khoan dang nhap de gui email
$mail->Password = “pass”; // mat khau gui email
$mail->From = “[email protected]”; // email se duoc thay the email trong smtp
$mail->AddReplyTo(“[email protected]”); // email cho phep nguoi dung reply lai
$mail->FromName = “iTNET”; // ho ten nguoi gui email
$mail->WordWrap = 50;
$mail->IsHTML(‘text/html’); //text/html | text/plain, default:text/html
$mail->AltBody = “Send from iTNET class_smtp_mail”; //Text Body
$mail->Body = “Noi dung can gui”; //HTML Body
$mail->Subject = “Tieu de email”;
$mail->AddAddress(“[email protected]”); // email nguoi nhan
$mail->Send();
$mail->ClearAddresses();
?>
Hello Mr. Van,
Sorry for the problem with connecting to your outbound server (SMTP). It’s difficult to tell where your comments end and begin. If I start each comment and create a line break using the “//”, then your code looks wrong. Make sure that you’re using the correct code (as demonstrated above) and then place the proper SMTP connection information. If you think it’s correct and you want us to review it, then please re-add the code to your reply, but make sure you add it line by line so that we can review it or at least know where the linebreaks are locted.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
Really a nice script for mail
Thanks guys
I’m confused. I’m trying to send an email from within php on a development machine using xampp. I have installed the hmailserver. When using phpmailer, do I need to use a local email server? Could someone explain the concept behind using phpmailer and how it cohabits with other software? Thanks.
It is possible that your testing environment does not have the necessary email services available. Using PHP to send mail can be a preferred method for those comfortable with PHP. However, other SMTP email services achieve the same effect.
You are the best BRAD!!
Thanks!
Hello,
I am using the phpmailer script and it is working.
I recevieve the mail send from my website.
But,…
after sending an email with the form on my site you go to …./sendmail.php and you will see only a blank page with only ‘Message has been sent’ on it.
Is it possible to change anything in the script so I stay on the same page and open the ‘Message has been sent’ in a div or so?
if(!$mail->send()) {
echo ‘Message could not be sent.’;
echo ‘Mailer Error: ‘ . $mail->ErrorInfo;
} else {
echo ‘Message has been sent’;
Hello Rutger,
You can change the form to post to itself instead of the /sendmail.php and just put the sendmail.php code into the same file as your form. I also found a StackOverflow thread that did almost the same thing.
Best Regards,
TJ Edens
Thanks for your reply TJ Edens.
Hope that I am able to do this, we will see…
To be honest, I don’t understand how they fixed this….
Hi,
I am have downloaded PHPMailer_5.2.0.zip & PHPMailerAutoload zip file (do I need to change any of the file content in these files?) Then i have created email.php as follow. I am getting error. what is wrong?
SMTP Error: Could not connect to SMTP host. Message could not be sent.Mailer Error: SMTP Error: Could not connect to SMTP host.
Hello Josephine,
I removed the code portion for security reasons since it had account names and passwords. Don’t worry, I removed it before making it public.
The error message says it could not connect to the SMTP server. This means you need to check the server name, username, and password in the SMTP settings to ensure they are correct.
Other than the settings and the specific email addresses you want to send to or from, you should not have to change any other code in the files.
Kindest Regards,
Scott M
please help asap, when i press the button, the php file shows up as plain text
Hello Hani,
Do you have the tags
hi guys, im stuck in this, what is wrong with the code? i am getting the error (
The mydomain.com page isn’t working
mydomain.com is currently unable to handle this request.
500).
*mydomain.com is just an alias,
public_html/PHPMailer_5.2.0
public_html/lib
public_html/mail.php
(mail.php)
<?php
$to= “[email protected]”;
$message = “Test”;
require(“lib/PHPMailer/PHPMailerAutoload.php”);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = “mydomain.com,mydomain.com”;
$mail->SMTPAuth = true;
$mail->Username = “[email protected]”;
$mail->Password = mypassword;
$mail->From = “[email protected]”;
$mail->AddAddress($to);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$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”;
?>
Please,give replay as soon as possible. Thank you in advance. 🙂
Hello Geo,
Thank you for contacting us. We are happy to help, but this will require additional testing. Can you provide a link to the form?
Thank you,
John-Paul
I have this error
Warning: stream_socket_enable_crypto(): Peer certificate CN=`*.inmotionhosting.com’ did not match expected CN=`localhost’ in
I solve using ecbiz196.inmotionhosting.com
in order to work with smtp.gmail.com, in the acount you use the login info, must activate “gmail less secure apps” .
Hi sir,
I have an web site.In that i have a page contact form.I am a begginer in php.But i want that page as to work.If someone as write the feedback in that page that message has to deliver to my gmail account.
1.What changes i as to write in this code??
2.Is there any settings that as to change in cpanel??
3.Is there any settings that as to change in gmail??
Please,give replay as soon as possible.I tried the mail function also but the mail is not send.plzzzzzzzzzzzzzzzzzzzzzzzzzzz
Hello Raghavendra,
Using the code above in this article you should be able to send emails to your Gmail account without changing any settings on either Gmail or cPanel.
Best Regards,
TJ Edens
I have the following changes made and i am using yahoomail to send email. when i run email.php file in browser if does not display anything . blank page is displayed but other html/php pages are working correctly. what else should i do?
$mail->Host = “localhost”; // specify main and backup server
$mail->SMTPAuth = true;
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password
$mail->SMTPSecure = “tls”;
$mail->Port = 587;
$mail->AddAddress(“[email protected]”, “Brad Markle”);
I advise checking the mail logs to see where the transmission is getting stuck. That will help get you more information. If you’re on a shared hosting plan, you can contact our Live Support to check the logs with you. Also, you can try changing the settings around, using different ports, for example.
Hi,
Tried to use the code above. Can’t seem to make it work. I’m on my dev machine, so I’m pointing the Host to your smtp server. Got the error “SMTP connect() failed”. The credentials are correct, the fact that I used it to login to webmail. Here’s part of my slightly modified code
Hello jb,
Thank you for contacting us. I recommend reviewing the mail logs for additional clues or record of the transmission.
Thank you,
John-Paul
Hi,
When I send message from html form I am being redirected to blank email.php with no messages and my email is not sent (received). I did everything as described in tutorial. Need assistance. My email.php>
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$name = $_POST[‘name’] ;
$email = $_POST[’email’] ;
$phone = $_POST[‘phone’] ;
$message = $_POST[‘message’] ;
// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require(“PHPMailer_5.2.0/class.PHPMailer.php”);
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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // 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(“[email protected]”, “Igor Mihailovi?”);
// set word wrap to 50 characters
$mail->WordWrap = 150;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = “Imate poruku sa Vaše web stranice!”;
// $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”;
?>
Hello Igor,
I just copied the code to a random server and it worked just fine as described. Did you make sure to do the previous steps as well as you don’t need to just copy the code.
Best Regards,
TJ Edens
I have purchased domain and hosting from godaddy and purchased business emails from google. I can send emails from localhost by using credentials of google mail id but when I put such code in godadaddy cpanel, It is not working ? What is the issue or causes for this problem ? I have used PHPMailer to send the mails.
My code is as follows :
Gotcha… well thank you for the assistance thus far, I will review that article! Cheers
Thanks for that idea… can you look at this and tell me an example of bringing the data into the sent message? I have tried many different ways most result in a syntax error or just blanks. The code I have pasted into the BODY section is just as it was in the old html email template, but now using phpmailer it doesnt work. This is the end of my script as is it now (just the last portion of the whole script)…
$mail->IsHTML(true);
$mail->Subject = ‘Here is the subject’;
$mail->Body = ‘
<h2><b>$first_name</b><b> $last_name, $license_type</b></h2>
<p><h3>Email confirmation sent to:</h3> $email</p>’;
$mail->AltBody = ”;
if(!$mail->Send()) {
echo ‘Message could not be sent.’;
echo ‘Mailer Error: ‘ . $mail->ErrorInfo;
exit;
}
echo ”;
?>
Hello KawaiiGuyy,
Thanks for the question about adding data into your email through the email script. We do not provide programming support as it’s beyond the scope of our support. However we do try to point you in the direction of a possible solution. You may want to check out this article where they are adding data from Google forms. It may provide insight on how you can do this for your emails.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
This was such a help… Does anyone know how to display the form data entered in the confirmation message??? I used to do this in an old form with $fieldname1 in the html but this does not work if I add html in the body of the confirmation message.
Hello KawaiiGuyy,
You can just echo the variables in your confirmation area.
Best Regards,
TJ Edens
How to set SMTP setting correctly if there is an error exist?
Hello Wani,
Can you please elaborate on what your question is? Are you getting an error when sending via SMTP?
Best Regards,
TJ Edens
helo sir,
i had the same problem …
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
how to define the HOST name as smtp.gmail.com
Hello Padhu,
If you’re going to be using the Gmail server as your outgoing mail server, then you would need to provide the correct settings. If you use our email server, then you can obtain the email settings and set it to use an email account and SMTP.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
Hello, I am an aspiring programmer, and I have been more of a front-end developer. So I am now getting my feet wet on the back-end.
Currently I’m engaged in a website, and everything seems to work well except for the form. The data does not seem to be sent since it does not get displayed at the designated email.
The validations are passed well, and the redirection to the (thanks.html) message is successfully processed.
Please point me into the right direction. Below is a sample of the php script used. (Please note that the site is on an online server for testing.)
<?php
/* Set e-mail recipient */
$myemail = “[email protected]”;
/* Check all form inputs using check_input function */
$name = check_input($_POST[‘name’], “Enter your name”);
$subject = check_input($_POST[‘subject’], “Enter a subject”);
$email = check_input($_POST[’email’]);
$message = check_input($_POST[‘message’], “Write your message”);
/* If e-mail is not valid show error message */
if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”, $email))
{
show_error(“E-mail address not valid”);
}
/* Let’s prepare the message for the e-mail */
$message = “
Name: $name
E-mail: $email
Subject: $subject
Message:
$message
“;
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header(‘Location: thanks.html’);
exit();
/* Functions we used */
function check_input($data, $problem=”)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Hello Kingsley,
Unfortunately we are not able to set up a test environment to troubleshoot code. You will want to input some code to test the query, variables, error codes, etc to locate the issue.
Kindest Regards,
Scott M
Hello,
I am having problem in sending mail. Below error is showing
Message could not be sent.
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
And my code 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(“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 = “smtp.gmail.com”; // 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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “xxxxxxxxxxxxx”; // 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(“[email protected]”, “Suraj”);
// 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”;
?>
Unfortunately we are not able to test and troubleshoot code. Do be sure, however, that your SMTP settings are set correctly.
Kindest Regards,
Scott M
SMTP ERROR: Failed to connect to server: Connection refused (111)
when i tried this script with host as smtp.gmail.com i am getting this error. please help. i’ve already tried the above solutions but nothing helped
I was sent to this page by the helpdesk as an example of how to use PHPMailer to rate limit email blasts. Yet, there is no information here. It’s very irritating to see that. More information needs to be included so we have a tutorial on how to do it.
Especially since I was told that the systems engineers are expecting us to be using it. Guess what…they shouldn’t since they don’t actually teach how to rate limit here.
Hello Corey,
I’m not sure why they would send you to this specific article. For features such as rate limiting you will want to use software such as phpList or even services such as MailChimp.
Kindest Regards,
Scott M
Hello Akshay,
You will need to ensure your SMTP settings are correct.
Kindest Regards,
Scott M
Sir below is my php code and while running this code … this error is coming
Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Please help me
<?php
require ‘PHPMailer/PHPMailerAutoload.php’;
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ‘localhost’; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ‘[email protected]’; // SMTP username
$mail->Password = ‘@smart_noReply1’; // SMTP password
$mail->SMTPSecure = ‘tls’; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom(‘[email protected]’, ‘smartraysolutions’);
$mail->addAddress(‘[email protected]’, ‘Joe User’); // Add a recipient
//$mail->addAddress(‘[email protected]’); // Name is optional
$mail->addReplyTo(‘[email protected]’, ‘Information’);
$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.’;
echo ‘Mailer Error: ‘ . $mail->ErrorInfo;
} else {
echo ‘Message has been sent’;
}
?>
Hi Guyz,
I am using localhost and I have this code running in my file.
<?php
/*$from_name = $_REQUEST[‘name’];
$from = $_REQUEST[’email’] ;
$body = $_REQUEST[‘message’] ;*/
require(“PHPMailer/PHPMailerAutoload.php”);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPSecure = “tls”;
$mail->Port = 465;
$mail->Host = “smtp.gmail.com”; // specify main and backup server
$mail->Mailer = “smtp”;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “rushi123”; // SMTP password
$mail->From = “[email protected]”;
$mail->AddAddress(“[email protected]”, “Rushikesh Oza”);
//$mail->IsHTML(true);
$mail->Subject = “You have received feedback from your website!”;
$mail->Body = “This is testing Email…”;
//$mail->AltBody = $body;
if(!$mail->Send())
{
echo “Message could not be sent. <p>”;
echo “Mailer Error: ” . $mail->ErrorInfo;
exit;
}
else
{
echo “Message has been sent”;
}
?>
But when I run this page at that time this page is continous loading and suddenly it gets stopped and shows nothing. There is a blank page and when I refresh this page at that time this happens again and again. Please help me as soon as possible.
Hello Rushikesh,
Thank you for contacting us. Since a blank page often indicates a suppressed error, I recommend. This may provide specific errors or clues into what is happening.
Also, check your mail logs for any errors or record of your connection. If you are not seeing anything there, it is failing before hitting the server.
Thank you,
John-Paul
Now I’m seeing the same errors echoed again even after turning off error display in PHP.ini.
Here’s what’s displayed, and this display hangs if an e-mail address is not entered in submit. If an e-mail address is submitted (it’s valid, its mine) this same display will appear momentarily before the “thank-you page” redirect:
Warning: trim() expects parameter 1 to be string, array given in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 272
Deprecated: Function eregi_replace() is deprecated in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 367
Deprecated: Function eregi_replace() is deprecated in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 411
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined offset: 1 in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1648
Notice: Undefined index: replyEmailOnFail in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1137
Notice: Undefined variable: missing_field_redirect in /home/faster12/public_html/city-space.biz/asheville/order/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php on line 1162
Hello Cynthia,
Have you ensured that your php.ini file is set to be recursive?
Kindest Regards,
Scott M
Hello,
I followed everything shown in the linked page.
Turning off the ‘display errors’ did eliminate all but one warning at the top of the window. It still displays the window for an instant, showing one error at the top, before going to the ‘thank-you’ page. Any ideas?
Thank-you in advance.
Hello Cynthia,
Thank you for contacting us. What is the exact error you are seeing?
Thank you,
John-Paul
Hello Cynthia,
Thank you for contacting us. We have a guide on How to create a custom PHP contact form with validation, that may help you get started.
Unfortunately, we do not have any guides on creating a form that allows image uploads.
Thank you,
John-Paul
I’m sorry… let me check the link you provided first.
Please can you show me where? I have poured through it…
I asked earlier about assistance with PHPmailer-FE…
I need to be more specific on my problem with PHPMailer-FE by WorxWare. Apparently the effort moved to SourceForge, now on GitHub. Their effort in PHPMailer-FE is hugely different from WorxWare’s. Very little documentation.
I went with PHPMailer-FE becuse it has a form already. Now I think I should abandon it. According to Support Chat here, it looks like error reporting may be reported to another server as errors where not seen in logs at InMotion.
That said, can you suggest an easy to integrate multipart form with an upload field that I can use with PHPMailer on my plain HTML/CSS/Javascript (shared SSL site – it’s not a CMS site.)? I use PayPal for payment processing… The form I need allows uploading images to be sent to my e-mail.
Or, is there software in C-Panel that I can use together with my plain website for the purpose?
Hello,
I am using PHPMailer to send mails. Mails are sent successfully. But the from address which I specify is not shown in recieved mail.
I am using
$mail->Host = ‘smtp.gmail.com’; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = ‘[email protected]’; // SMTP username
$mail->Password = ‘password’; // SMTP password
Can anybody tell me why my from address is not set?
Hello Sid,
Thank you for contacting us. We do not cover this in any of our guide, but I found a possible solution through online search. On that forum, they discuss possible options, but it will require further testing/troubleshooting.
Thank you,
John-Paul
Hello Cynthia,
Thank you for contacting us. As a test, I recommend turning “display errors” off. This should cause it to suppress the errors, instead of displaying them on the page.
Thank you,
John-Paul
Can the Community Support Staff help me with PHPMailer-FE ?
The Form-2-Mail works nicely. The problem I have is that it publicly displays errors in the browser for a moment before successful send. Or, if a required field isn’t entered in the form (on my webpage) then the whole list of notices and warnings is displayed and it just stays in that browser window. It works wonderfully well, if it didn’t display this information for the public to see. Can you help me turn displayed content off?
Hello guys, sorry that I bothered you, thank’s a lot for your very fast answer. After a long evening I have found the solution, it’s working now. Problem was on providers side and sometimes its better to read the documentation very carefully.
Best regards
Jens
Hello tried your nice script, but alsways getting following mistake: Fatal error: Class ‘SMTP’ not found in C:\xampp\htdocs\stoneglass-test\PHPMailer\class.phpmailer.php on line 1302
May be you can help me with this, thank you JeSto
Hello Jens,
Are you only using the code we provided? Can you provide what code is on line 1302 of that file? Do you have sendmail installed on the server?
Best Regards,
TJ Edens
Hello,
I was wondering, since the script includes both the email username and password, how can I “hide” it or make it safe when it is on my hosting server?
Tanks.
Nicolas.
Hello Nicolas,
A php script can only be seen if you are logged onto the server.
Kindest Regards,
Scott M
Can I send mail from local machine by configuring the smtp from [email protected] mail id ?
I don’t want to use gmail account to send mail. I want to send mail from my domain mail id from local machine.
Please suggest the process for this.
Thanks & Regards
Jagadish
Hello Jagadish,
If you follow the tutorial above, the email that is sent through PHPmailer sends the email through the server assigned to your account. The SMTP settings above uses an existing email account (from your cPanel settings) for authentication . I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
hai.. is it possible for me to send email from localhost ? i tried but never received the email.. it says successful though
Hello Fahmy,
If you look through the code in the tutorial above, it uses “localhost”. If you’re using the code above, you should be able use that setting when using the PHPmailer to send mail.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
I am sending 50 to 70 emails each day. However, there are two intreresting facts:
However, I will give it a try and let you know.
Also, the only error I get is Mailer Error: SMTP connect() failed.
It is echoed from the line echo “Mailer Error: ” . $mail->ErrorInfo;
I don’t know where to find more information about the error. I am using LinuxMint as my OS, so if you have any suggestions I would welcome it.
I am using this script (with a few cuts, because I didn’t just copy pasted it) to send several emails. The script is wraped up as a function with recepients, subjects and body as parameters, because I have a list to who the email must go. The issue is this. Sometimes (for no apparent reason) the emails stop at some point of the list and for the rest of them I get Mailer Error: SMTP connect() failed. Before this point the emails are resent, after this point no emails are sent (I dont get a delivery status = fail which I would get if for example I would get if the addresses were incorrect). This happens only once in a while and the point to which has happened varies.
The code hasn’t been changed in quite a while, so I don’t think it is a bug. The data used are correct (if not it wouldn’t send any emails at all, but it only fails arbitrarily). I thought it might be an internet connection issue, but my internet is pretty good.
Hello Cora,
How many emails are you trying to send at each time? Have you noticed any mail log errors? If you are sending large list of emails I would suggest sectioning them up some to see if it relieves the issue.
Best Regards,
TJ Edens
The mailer is working correctly but i have recieve the mail in spam folder. Can u please tell me what is the problem in this…
Hello Rahul,
Sorry that you’re having problems with your email being labeled spam. We do not have enough information concerning the email in order to determine the issue. It may be content related. Check out stop emails being labeled spam. Please provide more information on the content of the email in order for us to look at the issue further.
Regards,
Arnel C.
I’m sorted thanks
<?php
//.:/usr/lib/php:/usr/local/lib/php/
require(“public_html/PHPMailer_5.2.0/class.phpmailer.php);
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = ‘lnxwebs31.cpt.wa.co.za’; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = ‘[email protected]’; // SMTP username
$mail->Password = ‘password’; // SMTP password
$mail->Port = 465;
$email = $_REQUEST[“email”];
$name = $_REQUEST[“name”];
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress(“[email protected]”, “Email Admin”);
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$message = $_REQUEST[“message”];
$mail->Subject = “Feedback from the website contact form”;
$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”;
?>
I keep getting a blank page and an error in the error_log
Goodday, please i dont know if you can help me with a script that can help me send out bulk mails..and please tell me how to power it (SMTP).
i need it. thank u
Hello Elena,
For bulk mails you will want to check out applications such as phpList, which can be installed via the Softaculous tool within the cPanel. You also may want to check out services such as MailChimp which can be very helpful in preserving server resources.
Kindest Regards,
Scott M
how to add multiple recepiant at a time
Hello german,
Thank you for contacting us. We do not have a guide for this, but I found a possible solution via online search. This will require some coding/development knowledge.
Thank you,
John-Paul
I’m not an expert so I would like to ask a (maybe) stupid question:
with phpmailer we need to use a valid email address with valid credentials…
If we put these info into the code, aren’t they a little bit easy to find?
is this safe to use?
Thank you.
Hello Alex,
The email address and credentials are within the PHP code. PHP code is not viewable within the browser, only the HTML output.
Kindest Regards,
Scott M
Scott,
I am having the html page what you above said (contact_us.html) and email.php what you above said (code under the heading “Add the PHPMailer code to your side”). Both are working if no changes. When my situation, i want to add email template (which is received in email not run in web browser) from email.php using $Body = file_get_contents(‘contents.php’); Thru contents.php, i want to pass and print the variable $message as email template. Got my point? Give me a solution.
Thanks
Karthik N
Hello Karthik,
Sorry to hear that the solutions prevented above are not sufficient. Providing a custom coded solution is unfortunately beyond our scope of support. If you require such a solution we suggest finding a developer/programmer to help create your solution.
Apologies again that we can’t provide a direct solution. If you have any further questions or comments, please let us know.
Regards,
Arnel C.
Hi Brad,
Thanks for the guidelines. But in my situation, I want to pass the $message variable to my custom mail template which is called thru
$Body = file_get_contents(‘contents.php’);
In my contents. php file, I want to achive like the below,
<table>
<tr>
<td><?php echo $message ?>
</td>
</tr>
</table>
How can i achieve that… Any Idea would be appreciated
Hello Karthik,
As long as you have the $message variable populated properly echoing it out should not be a problem. I am not understanding where you are having an issue, so please let us know so we can be of better assistance.
Kindest Regards,
Scott M
Hello Chuks,
Thank you for contacting us. If it is not that many people, you can simply include them in the cc field, which will copy them on the email.
You can also use a mailing list program such as PHPList, or a mailing service like MailChimp.
Thank you,
JohnPaul
Hi,
I have a contact page on my website which is working perfectly fine without any error messages. But I just want one thing to add in code that is whenever any one send my a message/eamil from contact form all there details name,email , telephone also gets into my email.
I am pasting the code for both html as well as php over here….
Please hel me out with this…
Thanks
Hello Karan,
Unfortunately we had to remove your code as we cannot have that much space taken up by code. We are not able to provide custom coded solutions, so you will want to look out for a freelancer or developer who can add that functionality to your site for you.
Kindest Regards,
Scott M
Good day, I am desperately in need of a php mailer because i need to send a mass mail at the office but it is so difficult for me to understand the steps, I would love you to assist me, i really need your help.
I just wanna use this oppotunity to thank Brad for this tutorial and to the staffs in the support line, thank you all.
Yes, its possible. I found a fix. Thank you for the response.
Hello;
Is there a way to attach php code, into email.php script, that check to see if the form submitted data like username & email exist in the database?
Thanks.
Hello Tony,
Thank you for your question. Yes, this is definitely possible, but you will have to custom code a solution for this.
I recommend our class on Using PHP to create dynamic pages, it includes tutorials on using PHP to connect to and retrieve data from MySQL.
Thank you,
John-Paul
hello, I wanna ask something.
i using phpmailer to sending an email in my application. when I try in my localhost, my email can send corectly. but when I move the folder in local server, the email sending but nothing in inbox. What should I do?
Hello Meili,
Have you tried to echo $result? This would display all of the email information to make sure everything is in place. Also have you checked the spam folder on the recipients end?
Best Regards,
TJ Edens
thanx for the code
all these is working but i am recieving in spam folder please help me….
Hello rahul,
Thank you for contacting us. On line 12 of your “C:\wamp\www\mymail\email.php” file, have you verified that the “PHPMailer” is specified correctly?
Thank you,
John-Paul
Hello Pankaj,
Thank you for contacting us. You can Whitelist the email address in spam assassin.
If it is being flagged as spam in your client (such as Outlook, Thunderbird, etc.), you will have to check your spam/blacklist settings there.
Thank you,
John-Paul
Sir, when i m running this code it giving a fatal error like that– “Fatal error: Class ‘PHPMailer’ not found in C:\wamp\www\mymail\email.php on line 12″
i am in need of using this site please
Hello Edward,
Thank you for contacting us today. We are happy to help, but I am not sure what you are asking. Please provide more information on what you are trying to accomplish.
Thank you,
John-Paul
Hello Nguyen,
Have you tried ports 25 and 587 as well?
Kindest Regards,
Scott M
hi all,
i config mail as below:
$mail = new PHPMailer();
$mail->IsSMTP(); // SMTP
$mail->Host = ‘smtp.gmail.com’;
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true;
$mail->SMTPSecure = ‘ssl’;
$mail->Port = 465;
$mail->Username = sfConfig::get(‘app_smtp_username’); // SMTP account username
$mail->Password = sfConfig::get(‘app_smtp_password’); // SMTP account password
$body = ‘<p>’.’Check send mail:’.'</p>’;
$body .= ‘<p><a href=”‘.$link.'”>Link test</a></p>’;
$mail->SetFrom($mail->Username);
$mail->AddAddress($sendto, $sendto);
$mail->Subject = ‘Check send mail’;
$mail->CharSet = “utf-8”;
$mail->ContentType = ‘text/html’;
$mail->Body = $body;
$mail->IsHTML(true);
if(!$mail->Send()){
echo “Mailer Error: ” . $mail->ErrorInfo;
exit;
}else{
echo “Message has been sent”;
}
but when i try send email test e have an error:
SMTP -> ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution (0)
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.
pls, give me some solution!
thank,
Fatal error: Class ‘PHPMailer’ not found in C:\xampp\htdocs\public_html\email.php on line 27
Hello Karan,
The SMTP settings should be the same. We would need to see them to check them out, however. What port have you specified?
Kindest Regards,
Scott M
Have you required the file that contains the PHPMailer class? It should be in “class.PHPMailer.php”
Hello,
Thank you so much for your help.
The exact error message which I am getting is :
“{“status”:”error”,”messages”:[{“message”:”Sorry your mail was not sent – please try again later
SMTP connect() failed.<\/small>”,”field”:”submitButton”}]} “
I have configured the same mail in macmail & it is working perfectly fine.
I am able to send & receive emails.
It would be a great help if you making it work.
Thanks & Regards
Karan Dhawan
Yes. I tried 587 instead of 25 but it is still not working. I have also tried 465 but make no difference.
I will be highly obliged if you get it going.
Hello Karan,
Thank you for contacting us. We are happy to help you troubleshoot further, but will need some additional information.
Other than “smtp connect() failed” are you getting any additional errors messages?
Have you reviewed the Mail logs for additional error messages or information?
Have you tested the email settings in another setup, such as in Outlook, or MacMail. This will determine if the settings are functional or not.
Thank you,
John-Paul
hi,
Mail sent succesfully but did not receive the mail
could u please help me out
Thanks
Hello nandan,
Thank you for contacting us. I recommend checking your spam box/filter settings to ensure they did not catch or delete the incoming email.
Next, I would check the mail logs for any transmissions/errors. If you are on a shared server, Live Support can help you with this.
Thank you,
John-Paul
Thanks alot………………………………… <3
Got me working… Excellently Explained…
Have you tried using port 587 instead of 25 for your SMTP port?
I am also getting the same error, that is, smtp connect() failed
check coding several times also put the two smtp’s but still not getting the issues.
Please help me.
<?php
$email = $_REQUEST[’email’] ;
$message = $_REQUEST[‘message’] ;
require(“vendor/phpmailer/phpmailer/PHPMailerAutoload.php”);
$mail = new PHPMailer();
// Setting up PHPMailer
$mail->IsSMTP(); // Set mailer to use SMTP
// Visit https://phpmailer.worxware.com/index.php?pg=tip_srvrs for more info on server settings
// For GMail => smtp.gmail.com
// Hotmail => smtp.live.com
// Yahoo => smtp.mail.yahoo.com
// Lycos => smtp.mail.lycos.com
// AOL => smtp.aol.com
$mail->Host = “[email protected];rely-hosting.secureserver.net”; // Specify main and backup server
$mail->SMTPAuth = “false”;
// Enable SMTP authentication
//This is the email that you need to set so PHPMailer will send the email from
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “Passc0de”; // SMTP password
$mail->SMTPSecure = “false”;
//$mail->Port = “25”; // TCP port to connect to
// Add the address to send the mail to
$mail->AddAddress(“[email protected]”);
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
// add your company name here
$company_name = ‘Adroit Technologys’;
// choose which fields you would like to be validated separated by |
// options required – check input has content valid_email – check for valid email
$field_rules = array(
‘name’ => ‘required’,
’email’ => ‘required|valid_email’,
‘message’ => ‘required’
);
// change your error messages here
$error_messages = array(
‘required’ => ‘This field is required’,
‘valid_email’ => ‘Please enter a valid email address’
);
// select where each inputs error messages will be shown
$error_placements = array(
‘name’ => ‘top’,
’email’ => ‘top’,
‘subject’ => ‘right’,
‘message’ => ‘right’,
‘submitButton’ => ‘right’
);
// success message
$success_message = new stdClass();
$success_message->message = ‘Thanks! your message has been sent’;
$success_message->field = ‘submitButton’;
// mail failure message
$mail_error_message = new stdClass();
$mail_error_message->message = ‘Sorry your mail was not sent – please try again later’;
$mail_error_message->field = ‘submitButton’;
// DONT EDIT BELOW THIS LINE UNLESS YOU KNOW YOUR STUFF!
$fields = $_POST;
$returnVal = new stdClass();
$returnVal->status = ‘error’;
$returnVal->messages = array();
if (!empty($fields)) {
//Validate each of the fields
foreach ($field_rules as $field => $rules) {
$rules = explode(‘|’, $rules);
foreach ($rules as $rule) {
$result = null;
if (isset($fields[$field])) {
if (!empty($rule)) {
$result = $rule($fields[$field]);
}
if ($result === false) {
$error = new stdClass();
$error->field = $field;
$error->message = $error_messages[$rule];
$error->placement = $error_placements[$field];
$returnVal->messages[] = $error;
// break from the rule loop so we only get 1 error at a time
break;
}
} else {
$returnVal->messages[] = $field . ‘ ‘ . $error_messages[‘required’];
}
}
}
if (empty($returnVal->messages)) { // Enable encryption, ‘ssl’ also accepted
$email = stripslashes(safe($fields[’email’]));
$body = stripslashes(safe($fields[‘message’]));
// The sender of the form/mail
$mail->From = $email;
$mail->FromName = stripslashes(safe($fields[‘name’]));
$mail->Subject = ‘[‘ . $company_name . ‘]’;
$content = $email . ” sent you a message from your contact form:<br><br>”;
$content .= “——-<br>” . $body . “<br><br><br><br>Email: ” . $email;
$mail->Body = $content;
if(@$mail->Send()) {
$returnVal->messages[] = $success_message;
$returnVal->status = ‘ok’;
} else {
$mail_error_message->message .= ‘<br> <small>’ . $mail->ErrorInfo . ‘</small>’;
$returnVal->messages[] = $mail_error_message;
}
}
echo json_encode($returnVal);
}
function required($str, $val = false)
{
if (!is_array($str)) {
$str = trim($str);
return ($str == ”) ? false : true;
} else {
return !empty($str);
}
}
function valid_email($str)
{
return (!preg_match(“/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD”, $str)) ? false : true;
}
function safe($name)
{
return(str_ireplace(array(“\r”, “\n”, ‘%0a’, ‘%0d’, ‘Content-Type:’, ‘bcc:’,’to:’,’cc:’), ”, $name));
}
Hi again Scott M,
thanks again for your quick responce, I figured out what was going on. When downloading the files for phpmailer off of Github, I rightclicked the individual files I knew I needed (autoloader, class.smtp etc) and I must have accidentally missed the link and downloaded the html instead. So when I reinstalled everything, I downloaded the zip and replaced the other files. No wonder it showed me the github phpmailer repository instead of actually working… I feel like such an idiot for wasting your time, so please accept my appologies. Now everything is working perfectly!
Best regards, Lodott.
I’ve been playing with the phpmailer for a bit now. Two things I had to change for it to work for me:
require $_SERVER[‘DOCUMENT_ROOT’]. “/PHPMailer/PHPMailerAutoload.php”;
and add
$mail->IsHTML(true);
after the $mail-> Body line in order for the email to display html correctly instead of the code.
Hi Scott M and thanks for your swift reply.
Of course, I understand. Seems like noone else is having this problem, so I’m definitely doing something wrong. I’ll let you know when I find the fix for this, for future reference!
Best,
Lodott
Hello lodott,
If you can test on a hosting account that would be a better indicator. One, it would be on the machine it would be using when live, and two we may be able to assist further as we could look at code, logs, etc. So if you are a customer and wish to try it that way, we are here for you.
Kindest Regards,
Scott M
Hi guys, great project.
I’m having a small problem setting this up. I tried running it from localhost, but when I submit through the post-button, it takes me to the Phpmailerautoload.php file. It doens’t send the mail, nor delivers any errors. Just shows me the nice phpmailerautoload.php site. Any idea why? Thanks for your time.
<?php
error_reporting(E_ALL | E_STRICT); ini_set(“display_errors”, 1);
// $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(“libs/phpmailer/PHPMailerAutoload.php”);
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
$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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “mypassword”; // SMTP password
$mail->SMTPSecure = “ssl”;
$mail->Host = “smtp.gmail.com”;
$mail->Port = 465;
// $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(“[email protected]”, “My mail”);
// 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”;
?>
Hello lodott,
Although we would love to assist, unfortunately we are not able to test anything on a local system. It should work the same as it does on the hosting servers, however.
Kindest Regards,
Scott M
HI
I have tried the code no error is displayed and it alerts saying mail is sent sucessfully but im not getting the mail
what should be the HOST
$mail->Host = “mail.domain.com”;
or
$mail->Host = “smtp.domain.com”;
Hello shaista,
Thank you for the information. According to your error the data is not being accepted, because the email addresses don’t match.
For example:
Your FROM address (shai***[email protected]) must match your authenticated email user (info@pa****.com)
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
Hello Rakesh,
Thank you for contacting us. You must replace the HOST with your valid email settings for it to send. This will differ based on your setup.
Thank you,
John-Paul
Hello Mr. Scott,
Thank you very much for the information. I first configure the php.ini and sendmail.ini I spent more time but it was unsucssessfull.
Also How to check the CC in localhost with php.ini
thank you
Hello Saboor,
You would need to look into the logs of your mail service to see if the emails are being sent out properly. Unfortunately we are not able to troubleshoot specifics of a local setup. If it was on our servers we would be able to assist by checking the logs here.
Kindest Regards,
Scott M
I set up the PHPMailer in my website, it is working perfectly if I set two different emails like gmail (in TO) and one from my server (in From). But if I set both my server emails in TO and FROM, I am not recieving the email. I have the SMTP config like below:
$mail->IsSMTP();
$mail->Host = ‘smtp.myserver.org’;
$mail->Mailer = “smtp”;
$mail->SMTPAuth = true;
$mail->Username = ‘[email protected]’;
$mail->Password = ‘Password’;
$mail->setFrom([email protected], ‘1st Person);
$mail->addReplyTo(‘[email protected]’, ‘2nd Person);
$mail->addAddress(‘[email protected]’, ‘Me’);
$mail->addCC(‘[email protected]’, ‘3rd Person’);
I just recieve the email in “[email protected]” but i am not recieving the emails in [email protected], [email protected].
Thank you very much
Hello Saboor,
Have you set the php.ini to display all errors? I assume this may not display any, but it is a good test. From there, you may want to have Live Support check the email logs to see if those other emails are actually being sent.
Kindest Regards,
Scott M
please tell the mistake just a simple form data to be mailed..not sent message is displayed
<?php
session_start();
include(“conn.php”);
if(isset($_POST[‘submit’]))
{
$name=$_POST[‘name’];
$email=$_POST[‘id’];
$num=$_POST[‘num’];
$msg=$name.$email.$num;
$to=”[email protected]”;
$from=”[email protected]”;
$sub=”hi”;
$t=mail($to,$sub,$msg,$from);
if($t)
echo “msg sent success”;
else
echo “not sent”;
}
?>
<html>
<body>
<form method=”post” action=”f.php”>
<table>
<tr>
<td>
Name:</td><td><input type=”text” name=”name” placeholder=”enter
your name”></input></td></tr>
<tr><td>
Email:</td><td><input type=”email” name=”id” placeholder=”enetr
email”/></td></tr>
<tr><td>
number:</td><td><input type=”text” name=”num”/></td></tr>
<tr><td>submit</td><td><input type=”submit” name=”submit”
value=”reg”/></td></tr></table></form>
</body>
</html>
Hello Tripti,
You will need to follow standard coding troubleshooting to check for error messages in the php. You will want to set up for error reporting, but also look for programmatical errors such as testing the variables that are to be sent to see if they are being populated properly.
Kindest Regards,
Scott M
i want user just type his name , email and message and when he click on the send button this mail directly in my mail box how this i do??
Jaya,
Since the error message you’re seeing says, “Warning: stream_socket_enable_crypto() [streams.crypto]: this stream does not support SSL/crypto in C:\wamp\www\mail1\PHPMailer_5.2.0\class.smtp.php on line 200″… it means that you need to TURN OFF that option in your code. It is turned on by the line that says: $mail->SMTPSecure = “tls”;
Try changing that to “none” or remove it. That line is not in our documentation above, so you may need to refer to the documentation from where you got that code. I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
Hello Navpreet,
This is a form, so by its nature it already works that way. You provide fields for your user to enter the information, when they hit enter, the form is emailed to you.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
this works really fine!
but i really need help right now, since iam novice/noob in php and need to get this working
i’m using unity3d to make a simple app, the app will able users to send screenshot via email, now i already tried this php plugin, and already connect and take string from my app into the php page, and it works excellent, but now i need to included the screenshow as an attachment, i really confuse since as far as i understand, the “add as attachment” that phpmailer include is targeting a spesific directory, which is not an option since the image will be in the client phone/comp
anyone can help me with this please? 🙁
thank you in advance
Hello Liquid_Metal,
Thanks for the question about phpMailer. Basically, the “add as attachment” option is based on where the phpmailer is running from. We can’t really make it work with mobile devices (as we did not develop it). If you’re trying to include screenshots, it would first have to be uploaded to the server before it could be added as an attachment. I hope this helps to explain the issue.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
If i send email to other email-ID it display in spam…
any solution for that?
Thanks.
Hello Mahesh,
If you are sending mail to “other email-ID” there should be other factors that may be leading to it being classified as spam. Unless the email ID itself is a keywork that is triggering a filter, the email-ID should not be causing the email to be filtered as spam. Review our tutorial on stopping emails being labeled as spam.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
Great article. I implemented it on my website and it works great.
I only wonder if it is possible to show the message “Message has been sent” (and the error messages) on the same webpage (my contact form) and not on a separate empty page.
Hello Gert,
It is possible, however it would require recoding of the php files involved.
Kindest Regards,
Scott M
Hello All,
Now I am getting this error. please help me I am bore now this hit n try 🙁
Message could not be sent.
Mailer Error: SMTP Error: Data not accepted.
SMTP server error: Your FROM address ( [email protected] , Root User <[email protected]>550 ) must match your authenticated email user ( [email protected] ).
Actually I am buildng a contact us form and fields are name, email address and comment. but my form is successfully post and say thank you but I don’t get any email on my domain email adddress.
Hello Jesus,
Thank you for your question. The ‘Mailbox name’ is the sending name, for example ‘John Doe’.
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
Hello shaista,
Thank you for your question. You may have to check your spam box, to ensure a filter/rule is not catching the emails.
Next, you may have to review your server’s mail logs for errors, or record of the transmission. If you are hosted with us, Live Support can help you with this.
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
Dear Scott,
All files are at exact location. I googled the problem and found that there can be version compaitibility issue. can you please porvide me PHPMailerAutoload.php file used as I downloaded PHPMailer from your site and PHPMailerAutoload.php from google. Please help.
Phanks
Hello Shaista,
You can find PHPMAILERAUTOLOAD.PHP here: [URL Removed. No Longer Available]. If you have any further questions or comments, please let us know.
Regards,
Arnel C.
Hi Scott,
Thanks for your quick response. Scott I got these Errors.
[01-Mar-2015 01:06:33 Asia/Karachi] PHP Warning: require(/public_html/PHPMailer/lib/PHPMailer/PHPMailerAutoload.php):
failed to open stream: No such file or directory in
/home2/pakwes/public_html/email.php on line 10
[01-Mar-2015 01:06:33 Asia/Karachi] PHP Fatal error:
require(): Failed opening required ‘/public_html/PHPMailer/lib/PHPMailer/PHPMailerAutoload.php’
Hello Shaista,
Those are errors stating that it cannnot find the files at the specified path. You will need to make sure you have the PHPMailerAutolad.php file in the ‘/public_html/PHPMailer/lib/PHPMailer’ directory.
Kindest Regards,
Scott M
$mail->SetFrom(‘[email protected]’, ‘Mailbox name’);
In ‘Mailbox name’ what I have to write ? because I have the same problem, I can receive mails but in blank.
Hello Shaista,
Have you enabled error reporting within your php.ini to display any php errors on the screen?
Kindest Regards,
Scott M
HI,
I have done like you guys mentioned in the post. I have uploaded PHPMailerAutoload.php in PHPMailer/lib/PHPMaier folder also I have created the contact_us.html file and email.php file. but no joy. please help. here is my email.php file. when i submit it show blank page.
<?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(“/public_html/PHPMailer/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 = “mail.pakwes.com”; // 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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “pasword”; // 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(“[email protected]”);
// 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”;
?>
Hello Sir,
Thank you for the video tutorial i was able to setup phpmailer as you did in the video but still when i goto the test1.php i uploaded to the subdomain i create to my website where i also uploaded the file i downloaded from code.google.com before i extracted it, this is the message i get back is ( Message could not be sent.Mailer Error: The following From address failed: [email protected] : Called Mail() without being connected )
This is my test1.php file path (/home/smartshop/public_html/Testphpmailer/phpmailertesting/test1.php)
And This is my class.phpmailer.php file path (/home/smartshop/public_html/Testphpmailer/phpmailertesting/PHPMailer_5.2.4/class.phpmailer.php) but it does not send the email, Please sir, I would like to know if i made any mistake and how can i correct it ?
Thanks in Advance.
Hello Rhonda,
Without seeing the code it is difficult to say, but many times it is a proper port issue. Never use 25 for unsecure. Use 587 for unsecure or TLS and use 465 for SSL. Ensure those are correct and give it another try.
Kindest Regards,
Scott M
Good day to you,
I got the mailer working relatively easy (we just need to read :))
One problem, the mail received indicates that the sender is ROOT USER and not the email entered in the html form.
Did I miss something?
Otherwise, excellent!
rgs
Zack
Hello Zack,
You should be able to add another parameter to the code such as:
Give that a try and see if that helps.
Kindest Regards,
Scott M
Hello everyonr
My error is: Invalid address: Message could not be sent.
Mailer Error: Message body empty
this is my code :
IsSMTP();
$mail->Host = “smtp.gmail.com”;
$mail->SMTPSecure = “ssl”;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = 465;
$mail->Username = “my [email protected]”; // SMTP username
$mail->Password = “xxxxxxxxx”; // SMTP password
$mail->From = $email;
$mail->AddAddress(“my [email protected]”, ” First name Second Name”);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = “PHP Proba”;
$mail->AddAddress($email, $name ); // to address – receiver mail and nam
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
echo “Message could not be sent.
“;
echo “Mailer Error: ” . $mail->ErrorInfo;
exit;
}
echo “Message has been sent”;
?>
i echo the password and checked my password its correctly but still getting same i used the both ssl with 465 and tls 587 ..but showing same error
require_once(“class.phpmailer.php”);
$mail = new PHPMailer();
$mail->SMTPDebug = 1;
$mail->IsSMTP();
$mail->Host= “smtp.gmail.com”;
$mail->SMTPAuth = true;
$mail->SMTPSecure = “ssl”;
$mail->Port= 465;
$mail->Username = “[email protected]”;
$mail->Password = “password”;
echo $sp;
$mail->From = “[email protected]”;
$mail->FromName = “From Name”;
$mail->AddAddress(“[email protected]”);
$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”;
?>
Hello Jhon,
I have tested our code with both my personal server and gmail. It works without issue on my personal server, but I also get the same issue when attempting to connect to the gmail server. This leads me to assume that the code itself is not incorrect, but there is something else that needs to be done to get it connected to gmail. We do not have that answer currently, as it will take more testing.
Kindest Regards,
Scott M
hi scott
i cahnged the tsl with port 587 but after that itz showing another error like
SMTP -> ERROR: Password not accepted from server: 534-5.7.14 Please log in via your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 18sm2602461wjr.46 – gsmtp
SMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
Hello Jhon,
That error is a bit more clear. It seems that the SMTP server is not happy with the password that it is being provided. You will want to check that specific password by logging into the account directly. Also, you may want to echo out the password in the code to display exactly what it is sending to the SMTP server.
Kindest Regards,
Scott M
OK thanks.I’ll try.
Hello John,
The error message you get may be due to using the 465 port with TLS. You will want to use port 587 for TLS. 465 is reserved for SSL.
Kindest Regards,
Scott M
hy everyone i was getting first smtp error
i maked some changes in my code like
THIS IS MY CODE
<?php
require_once(“class.phpmailer.php”);
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host= “smtp.gmail.com”;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = “tls”;
$mail->Port= 465;
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password
$mail->From = “[email protected]”;
$mail->FromName = “shahrukh”;
$mail->AddAddress(“[email protected]”); // 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”;
?>
now i am geetting the error
Language string failed to load: tls Message could not be sent.
Mailer Error: Language string failed to load: tls
I’ve checked the entire code.password and emailid are correct …Still it’s showing the same error.
Jhilmil,
Sorry for the continued problems with the PHP mailer issue. Please review this support article from Google. If your code is correct, and the error message you’re getting is can not connect to the SMTP server, then you will need to work with Google to see why it is that you cannot connect with their SMTP server. It’s possible that a port is being blocked, or may be there is another factor, but we cannot troubleshoot the connection to Google’s SMTP server as we have no control over it. Try testing your outgoing settings in an email client like Thunderbird/Outlook. If they work there, then they should work in the code. If they’re working in the email client and not in the code, then there may be something small that you’re missing in the code.
Kindest regards,
Arnel C.
What is pear mail package? what is
Mail.php
?? where do I get this file from?Jhilmil,
It did appear that you corrected the Class ‘PHPMailer’ not found error in your later post. The main issue in your code is that you’re not authenticating correctly. I merely gave the link to show you how others are connecting to the mail server. The PEAR module is not required. FYI – you can download PEAR packages through the cPanel. The code provided in this article works, but again it works when you have the correct connection and authentication criteria.
If you have any further questions or comments, please let us know.
Regards,
Arnel C.
I have got following error while trying t send Email
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
My email.php code is :
<?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”);
require(“PHPMailer_5.2.0/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
// specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = “ssl”;
$mail->Host = “smtp.gmail.com”;
$mail->Port = 465;
// 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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // 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(“[email protected]”, “My Site”);
// 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”;
?>
What should I do??? Please Help
Hello Ayush,
It appears that your code is not authenticating with the outgoing (SMTP) server. Check out this post concerning the issue. Basically, you need to have the correct port and legitimate email address that can send from gmail in order for it to work.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
Hello Jhilmil,
Sorry for the problem that you’re seeing. Generally, when you see that error, you need to include the phpmailer class in your code. Here’s an example from one of the common support forums: phpmailer not working. It does appear per your following post that you have already resolved this issue.
I hope this helps to answer your question, please let us know if you require any further assistance.
Regards,
Arnel C.
Hello Jhimil,
It appears that your code is not authenticating with the outgoing (SMTP) server. Check out this post concerning the issue. Basically, you need to have the correct port and legitimate email address that can send from gmail in order for it to work.
Let us know if you have any further questions or comments.
Regards,
Arnel C.
I have got this error…What can I do?
Fatal error: Class ‘PHPMailer’ not found
<?php
$email = $_REQUEST[’email’] ;
$message = $_REQUEST[‘message’] ;
require(“PHPMailer/class.phpmailer.php”);
require(“PHPMailer/class.smtp.php”);
require(“PHPMailer/PHPMailerAutoload.php”);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = “localhost”; // specify main and backup server
$mail->Port = 200;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “xxxxx”; // SMTP password
$mail->From = $email;
$mail->AddAddress(“[email protected]”);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$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”;
?>
on clicking the submit button showing blank page and mail is also not being sent
hello , arn , i have multiple input in my form , but only 1 input was delivered to the email , do you know how to fix this? i have tried to _Request all the input and send them to the body , but still only 1 input was delivered , please help me , thank you.
Hello Hasif,
It may be helpful if you could provide a code snippet. It is very difficult to troubleshoot without seeing what you are working with.
Kindest Regards,
Scott M
im new to programming , i actually dont understand , is the code actually need to put on the same file or into a new file? how many file required to make it work? thanks.
Hello Hasif,
Thanks for the question. If you have a SINGLE form, then the code would go on the page that has your form code. If you have multiple forms that require mailing, then you may need to put it on multiple pages. I hope this helps to answer your question.
Kindest regards,
Arnel C.
i want to ask, ive success for making password recovery send to mail.
Send to Gmail , is working fine
but send to Yahoo Mail.. why only 2 lines ..
heres my code
for Gmail send like this
but in Ymail send like this
Hello novanakal,
I took a quick look at the code and there is nothing that separates behavior for gmail vs yahoo mail. If you can confirm that the $message is the same regardless of which email you have it sent to, then the issue likely lies in how the message is parsed and displayed on the Yahoo server. You may want to take a close look at the $message and see if there is anything there that could cause the ymail server to stop after the first two lines.
Kindest Regards,
Scott M
Hi,
PHP mailer code was working fine. suddenly from last friday mailed got sending failed and error message was coudnot authenticate. check the same code using gmail email and code statred work. but when i use cpanel email it does’t work. after trying with the code realise that it’s working after commenting ” $mail->IsSMTP(); “. any solution for this and why this happned?
Thank you
Hello Chaturika,
Sorry you’re having problems with your email code. Unfortunately, we can’t see your code to see what’s happening. Can you provide us any bounceback emails, a URL, email address or account user where the problem is occurring so that we can investigate it further? If SMTP is enabled, then your SMTP settings must be valid in order for the email to arrive properly.
If you continue to have problems, please provide the information that we have requested in order for us to troubleshoot the issue in more depth.
Kindest regards,
Arnel C.
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = ‘tls’;
$mail->Mailer = “smtp”; // sets the prefix to the servier
$mail->Host = “smtp.gmail.com”; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = “*******edited by customer community”; // GMAIL username
$mail->Password = “*******edited by customer community”; // GMAIL password
$mail->From = “[email protected]”;
$mail->FromName = “sunil”;
$mail->Subject = “test mail”;
$mail->AddReplyTo(“[email protected]”, “No Reply”);
$mail->AltBody = “To view the message, please use an HTML compatible email viewer!”; // optional, comment out and test
$mail->WordWrap = 50; // set word wrap
$mail->MsgHTML($body);
$to = “[email protected]”;
$mail->addAttachment($path);
$mail->AddAddress($to, $to);
$mail->IsHTML(true); // send as HTML
if (!$mail->Send()) {
echo “Mailer Error: ” . $mail->ErrorInfo;
} else {
}
this is my code…to send mail..
and i m getting this error..
Mailer Error: SMTP Error: Could not connect to SMTP host.
what should i do?.plz..help..if possible.
Hello,
This type of error could mean that the credentials are incorrect. Be sure you can connect to the server with your username and password. You can also test all the settings by attaching via an email client such as Thunderbird.
Kindest Regards,
Scott M
Hello Nikhil,
I did some research on the error you provided and I found an interesting Stack Overflow thread helping someone else with the same error. It looks as if though you may need to upgrade your version of PHP.
Kindest Regards,
TJ Edens
hi thanks for addressing my concern
This is the full code, which works perfectly locally, but often when you get on the server bluehost and try resetting your password sent me this message “ERROR 31/10/2014 14:03:47 SMTP: Failed to connect to server : Connection timed out (110) SMTP connect () failed “.
locally so I drive with xampp
code:
<?php session_start();
require (‘../../../lib/phpmailer/class.phpmailer.php’);
include_once ‘../../../core.php’;
include_once Config::$home_bin.Config::$ds.’db’.Config::$ds.’active_table.php’;
$user=atable::Make(‘usuario’);
if($user->load(“nombre_usuario='{$_POST[’email_usuario’]}'”))
{
$user->codigo_res= rand(0,999999999);
$user->update();
$persona=atable::Make(‘persona’);
$persona->load(“id_persona=$user->id_persona”);
$mail = new PHPMailer(); // defaults to using php “mail()”
//defino el cuerpo del mensaje en una variable $body
// se crea el contenido del mensaje
$mail->IsSMTP();
//permite modo debug para ver mensajes de las cosas que van ocurriendo
$mail->SMTPDebug = 2;
//Debo de hacer autenticación SMTP
$mail->SMTPAuth = true;
$mail->SMTPSecure = “tls”;
//indico el servidor de Gmail para SMTP
$mail->Host = “smtp.office365.com”;
//indico el puerto que usa Gmail
$mail->Port = 587;
//indico un usuario / clave de un usuario de gmail
$mail->Username = “[email protected]”;
$mail->Password = “pass”;
$body=’
<h2>Proceso de Restauración de Contraseña </h2>
<p>Mensaje generado automaticamente </p>’;
$body.=”Para restaurar tu contraseña es debes hacer click en el siguiente Link o cipiarlo y pegarlo en tu navegador\r\n”;
$body.=”https://[email protected]/restaurar_password/index.php?codigo_res=$user->codigo_res&usuario=’$user->nombre_usuario'”;
//$body = file_get_contents(‘contenido.html’);
$mail->SetFrom(“[email protected]”, “S”);
//defino la dirección de email de “reply”, a la que responder los mensajes
//Obs: es bueno dejar la misma dirección que el From, para no caer en spam
$mail->AddReplyTo(“[email protected]”,”S”);
//Defino la dirección de correo a la que se envía el mensaje
$address = $persona->email;
//la añado a la clase, indicando el nombre de la persona destinatario
$mail->AddAddress($address, $persona->nombre_completo);
//Añado un asunto al mensaje
$mail->Subject = “Solicitud de Cambio de Contraseña en el Sistema”;
//Puedo definir un cuerpo alternativo del mensaje, que contenga solo texto
//$mail>AltBody = “Cuerpo alternativo del mensaje”;
//inserto el texto del mensaje en formato HTML
$mail->MsgHTML($body);
//asigno un archivo adjunto al mensaje
//$mail>AddAttachment(“ruta/archivo_adjunto.gif”);
//envío el mensaje, comprobando si se envió correctamente
if(!$mail->Send()) {
echo “Error al enviar el mensaje: ” . $mail>ErrorInfo;
}
else {
echo ‘<script>alert(“Revisa tu bandeja de correo, se te ha enviado un link con los pasos a seguir”); document.location=(“../../../”);</script>’;
}
}
else
{
echo ‘<script>alert(“usuario no existe”); document.location=(“../../../”);</script>’;
}
?>
Hello Duvan,
Thank you for contacting us today. I compared your settings to Office365’s guide and they look correct.
You also tested on your local server and it is working there.
At this point, I recommend reviewing your server for issues, or blocked ports (if you are hosted with us, Live Support can help you with this).
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
Hi I have a problem sending my emails me this message appears 30.10.2014 22:44:50 SMTP ERROR: Failed to connect to server: Connection timed out (110) SMTP connect () failed. the strange thing is that when working locally it works fine but when I upload it to the server that sends me blue host SMTP error
Hello Duvan,
Thank you for your question. We’re happy to help, but will need more information to troubleshoot it.
What is the full SMTP error you are getting, and what are the settings you are using? (please blank out any passwords, etc.)
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
I have created the form and these are my php script
but I keep on getting these
SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.
What went wrong?
$message = $_REQUEST[‘message’] ;
require(“class.phpmailer.php”);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = “localhost”; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = “tls/ssl”;
$mail->Host = “smtp.gmail.com”;
$mail->Port = 587;
$mail->Username = “[email protected]”; // SMTP username
$mail->Password = “mypassword”; // SMTP password
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress(“[email protected]”, “Shahirah Rashid”);
// 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”;
Hello Natalie,
Thank you for your question. Since your error seems to be related to the host (Error: Could not connect to SMTP host), I checked the $mail->Host setting in your script.
Then, I noticed there are 2 settings entered:
$mail->Host = “localhost”; // specify main and backup server
&
$mail->Host = “smtp.gmail.com”;
You will have to choose one or the other. If you are using gmail as a mail server, see Jacob’s gmail settings posted above.
If the server your website is hosted on is handling the email, it will be localhost.
If you have any further questions, feel free to post them below.
Thank you,
John-Paul
How can we get SMTP username and password for our email,would you give an idea please?
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
Can you recommend me any way or clues of doing it?
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
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?
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
Something like this?
//echo ‘Message has been sent’;
header(“Location: success.html”);exit;
It doesnt seem to work though..
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
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 !
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.
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?
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.
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
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
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
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” “https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”https://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) [email protected] |
| : Marcus Bointon (coolbru) [email protected] |
| : Jim Jagielski (jimjag) [email protected] |
| 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) |
| https://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 https://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 ‘[email protected]’
* @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 ‘[email protected]’
* @var string
*/
public $DKIM_domain = ”;
/**
* Used with DKIM DNS Resource Record
* optional, in format of email address ‘[email protected]’
* @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 https://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.’ (https://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] . ‘”‘);
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.
can some on help me with the mailer html form that will work with the php mailer?
Hello,
We are happy to try and answer any specific questions you may have. What are you having trouble with?
Kindest Regards,
Scott M
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
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?
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 [email protected] 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.
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.
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.
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
Does not tell how to use it in our website. It Just about making a new file.
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 [email protected] 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
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
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
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 [email protected]
I have several webpage for example 1.html, 2.html, 3.html with respective external email such as [email protected], [email protected], [email protected] 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
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=1
if(i==1){continue label3;
}
</script>
label1:
This is now html.
label2:
document.write(“This is middle”);
</script>
label3:
document.write(“This is javascript”);
</script>
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
It helped me a lot 🙂
Well written and detailed instructions. Awesome!
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
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
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??
As long as the server is running PHP, everything should work as expected.
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
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.
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.
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
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 .
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
Nice. Worked well.
Hello can you help me to how to send my HTML Coding in my message veriable
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
It works now just fine, Thanks a lot
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.
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
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 = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password
$mail->From = “[email protected]”;
$mail->FromName = “Mailer”;
$mail->AddAddress(“[email protected]”); // 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”;
?>
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.
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
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
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 = ‘[email protected]’; $mail->Password = ‘password’; $mail->SMTPSecure = ‘ssl’; $mail->addAddress(‘[email protected]’, ‘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> ?>
include an example which makes the concept clear to understand.
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
Hello Rakhesh,
We are happy to make the process more clear. What particular area did you have issues with?
Kindest Regards,
Scott M
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
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;
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
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.
<?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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // 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(“[email protected]”, “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
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
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.
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?
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.
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.
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?
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.
Actually am trying to send verification mail to my subscribers.
$email = ‘[email protected]’;//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 = “[email protected]”;
//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 = “[email protected]”; // SMTP username
$mail->Password = “*****”;
?>
Am using different mail for authentication.
While receiving mail, it shows authentication mail as From address.
Am i clear?
Your settings are correct, but my best guess is that Gmail is changing the From address to prevent individuals from spoofing email accounts.
From address is showing what I used for STMP authentication, not the one which I used in $mail->From. Where to include from address?
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?
Thank you Scott
I read your link and replied in details. Acctually nothing is working for us
Regards
Tarun.
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
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
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
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
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
I am using the following code :
File name: custom_functions.php
<?php
function 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 = ‘[email protected]’;
$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=”[email protected]”;
$from=”[email protected]”;
$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.
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
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.
Yes i am getting email. But not getting the data fields. What to do?
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
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.
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
Thanks Jacob, but I fixed the case sensitivity and it’s still giving me the same error.
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:
Then see if it’s actually echoing out the values you typed into the form.
– Jacob
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?
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
It ask to enter email & message.
I entered email as [email protected]
And message as 123456 abcdefg
And i click on submit
Another page loads called m/phpmailertest/test1.php which shows
Email: [email protected]
Message: 123456 abcdefg Message has been sent
I opened my webmail email [email protected]
it shows: “This is the body in plain text for non-HTML mail clients”
When i click on untitled-[2].html attachment it shows
This is the body in plain text for non-HTML mail clients
Where is my form data saved. i do not get it.
will i send the script of html & php?
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.
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.
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.
Where the form submit data will be saved? In the server or it will come in email as attachment.
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
the php file name is test1.php
email address are:
[email protected]
[email protected]
yes the email is coming but form data is not submitted or showing.
Please see it.
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:
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:
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
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 = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password
$mail->From = “[email protected]”;
$mail->FromName = “PhpMailer”;
$mail->AddAddress(“[email protected]”); // 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 [email protected]. I am getting the email but not the filled form data. How it will come? Below is the image.
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
ok it is email.php
I am receiving email but the form data submitted i am not getting.
How i can get?
Unfortunately, your question is unclear. Could you clarify?
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.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: [email protected]
// pass: password
$mail->Username = “[email protected]”; // 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(“[email protected]”, “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”;
?>
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.
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?
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.
I have checked and made changes to following entries
PHPFMG_SMTP_HOST'
tosmtp.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?
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
Hi JeffMa. How r u?
which password PHPFMG_SMTP_PASSWORD or PHPFMG_SMTP_PLAIN_PASSWORD.
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 usingsmtp.maahireen.com
but in the code you’ve posted you’re usingPHPFMG_SMTP_HOST' , 'mail.maahireen.com
.Hope that helps. Please let us know if you had any further questions at all.
– Jacob
I use filezilla to upload files into my server with encryption as Require FTP over TLS
I have a email address called [email protected]
Alhamdulillah in Microsoft Office Outlook 2007 i use to send & receive emails perfectly with the setup given below for [email protected]:
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 https://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 [email protected] & 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 : https://phpfmg.sourceforge.net
# —————————————————————————–
define( ‘PAYPAL_ID’ , ” ); // Put donation ID here to disable the bottom backlink
define( ‘PHPFMG_TO’ , ‘[email protected]’ );
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 file
define( ‘PHPFMG_EMAILS_LOGFILE’ , PHPFMG_ROOT_DIR . ‘/email-traffics-log.php’ ); // log email traffics to this file
if( !defined(‘PHPFMG_ADMIN_URL’) ) define( ‘PHPFMG_ADMIN_URL’ , ‘admin.php’ ); // might be defined already by wordpress form loader plugin
define( ‘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 Kilobytes
define( ‘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 email
define( ‘PHPFMG_RETURN_ENABLE’ , ‘Y’ ); // ‘Y’ to enable auto-response email, use ” or ‘N’ to turn off
define( ‘PHPFMG_YOUR_NAME’ , ” ); // name of auto-response mail address
define( ‘PHPFMG_RETURN_EMAIL’ , “” );
define( ‘PHPFMG_RETURN_SUBJECT’ , “” ); // auto-response mail subject
define( ‘PHPFMG_RETURN_NO_ATTACHMENT’ , ” ); // Y – No attachements will be included for auto-response email
define( ‘PHPFMG_CHARSET’ , ‘UTF-8’ );
define( ‘PHPFMG_MAIL_TYPE’ , ‘text’ ); // send mail in html format or plain text.
define( ‘PHPFMG_ACTION’ , ‘mailandfile’ ); // delivery method
define( ‘PHPFMG_TEXT_ALIGN’ , ‘top’ ); // field label text alignment: top, right, left
define( ‘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 options
define( ‘PHPFMG_USE_SMTP’ , ‘Y’ ); // Y – enable
define( ‘PHPFMG_SMTP_HOST’ , ‘mail.maahireen.com’ );
define( ‘PHPFMG_SMTP_USER’ , ‘[email protected]’ );
define( ‘PHPFMG_SMTP_PASSWORD’ , ‘changed password’ );
define( ‘PHPFMG_SMTP_PLAIN_PASSWORD’ , ” ); // use this to overwrite above password
define( ‘PHPFMG_SMTP_PORT’ , ’25’ ); // default 25, use 465 for gmail
define( ‘PHPFMG_SMTP_SECURE’ , ” );
define( ‘PHPFMG_SMTP_DEBUG_LEVEL’ , ” ); // empty or 0 – trun off debug
if( !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 code
define( ‘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” ] . “ </td> <td valign=top style='{$style};’>” . nl2br($value) . “ </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 online
function phpfmg_admin_url(){
$http_host = “https://{$_SERVER[‘HTTP_HOST’]}”;
switch( true ){
case (0 === strpos(PHPFMG_ADMIN_URL, ‘https://’ )) :
$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=’https://www.formmail-maker.com’>formmail-maker.com</a> which is not allowed.
Please read the <a href=’https://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 injecting
function 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”) :
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.
excuse me, but i asked Jacob? and i know i should add some lines on the html and php. thats weird
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.
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!!
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.
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>
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
How to get SMTP username and password?Do we have to purchase it?
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
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
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 = “[email protected]”;
$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 = “[email protected]”; // 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?
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
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:
Please let us know if you’re still having issues connecting.
– Jacob
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 = “[email protected]”; // 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”;
?>
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 = "[email protected]"; // 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
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 = “[email protected]”; // SMTP username
$mail->Password = “password”; // SMTP password
$mail->From = “[email protected]”;
$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.
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
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.
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 itself
CLIENT -> SMTP: Date: Wed, 19 Mar 2014 08:31:14 -0400
CLIENT -> SMTP: Return-Path:
CLIENT -> SMTP: To: [email protected]
CLIENT -> SMTP: From: Log Power
CLIENT -> SMTP: Reply-To: [email protected]
CLIENT -> SMTP: Subject: PHPMailer test e-mail
CLIENT -> SMTP: Message-ID: <[email protected]>
CLIENT -> SMTP: X-Priority: 3
CLIENT -> SMTP: X-Mailer: PHPMailer 5.2.5 (https://github.com/Synchro/PHPMailer/)
CLIENT -> SMTP: X-Mailer: Drupal
CLIENT -> SMTP: MIME-Version: 1.0
CLIENT -> SMTP: Content-Transfer-Encoding: 8Bit
CLIENT -> SMTP: Content-Type: text/plain; format=flowed; delsp=yes; charset=UTF-8
CLIENT -> 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:
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?
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??
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.