PHP Mailer [escapeshellcmd() has been disabled for security reasons] - php

First of all, hi and thanks for your time, yesterday I have installed PHP Mailer 6.0.5, by running composer locally then I uploaded the vendor folder that it generated on my server, but when I try to run phpmailer it say: escapeshellcmd() has been disabled for security reasons , here is my code:
require '/.../.../public_html/vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->addAddress($_POST['Email']);
$mail->setFrom('.......');
$mail->Subject=".....";
$mail->Body=".....";
if ($mail->send()) {
.....
}
How can I solve this error, could it depend on my installation?

source https://github.com/PHPMailer/PHPMailer/issues/966
use:
$mail->isSMTP();
that way PHPMailer will send via SMTP to localhost, which does not involve calling escapeshellcmd.

Related

Could not instantiate mail function: A PHPMailer Error

I'm trying to create a contact form. And I searched all over the internet how to send email, and they always say that it is better to use PHPMailer than mail() function.
The contact form consists of: Name, Email, Comments, and a Send Button.
I just followed this tutorial: https://alexwebdevelop.com/phpmailer-tutorial/ but it's not working as I always got the error called: 'Could not instantiate mail function.' when I already installed the Composer.
Proof that I've already installed the composer:
Composer installed with autoload.php
Here's my code inside the php tags:
use PHPMailer\PHPMailer\PHPMailer;
require 'C:\xampp\composer\vendor\autoload.php';
if(isset($_POST['send'])) {
$em = $_POST['email'];
$nm = $_POST['name'];
$msg = $_POST['comments'];
$mail = new PHPMailer();
$mail->setFrom($em, $nm);
$mail->addAddress('mygmail#gmail.com', 'Admin');
$mail->Subject = 'Concern';
$mail->isHTML(TRUE);
$mail->Body = '$em';
if(!$mail->send()) {
echo $mail->ErrorInfo;
}
}
Thank you for answering this question! It'll be a big help!
UPDATE:
Content/File of the composer.json:
{
"require": {
"phpmailer/phpmailer": "^6.0"
}
}
If you read the PHPMailer troubleshooting guide linked from nearly everywhere (including in your error message), you'll find it contains a detailed explanation for this error and how to solve it. Copying from there:
This means that your PHP installation is not configured to call the mail() function correctly (e.g. sendmail_path is not set correctly in your php.ini), or you have no local mail server installed and configured. To fix this you need to do one or more of these things:
Install a local mail server (e.g. postfix).
Ensure that your sendmail_path points at the sendmail binary (usually /usr/sbin/sendmail) in your php.ini. Note that on Ubuntu/Debian you may have multiple .ini files in /etc/php5/mods-available and possibly other locations.
Use isSendmail() and set the path to the sendmail binary in PHPMailer ($mail->Sendmail = '/usr/sbin/sendmail';).
Use isSMTP() and send directly using SMTP.
This is nothing to do with how you load composer's autoloader.
Some hosting services return this error when the email is considered a spam. Try using an email address with the same domain as your website.
Instead of: require 'C:\xampp\composer\vendor\autoload.php';
Try: require __DIR__ . '/vendor/autoload.php';
This is assuming that /vendor is a sub directory of your document root.

PHPMailer install without Composer

Please forgive my ignorance.
I am trying to install PHPMailer 6.0.1 under PHP 5.6 on Linux.
My PHP installation is remote and I manage all my websites’ PHP via FTP (I typically download packages as .zips to Win 10, unpack and then FTP the result to my webspace).
Of the various ways to install PHPMailer, Composer is preferred, but this is where I come unstuck. None of the Composer instructions seems appropriate to this way of working – the installer wants me to the ‘Choose the command line PHP you want to use’, but I don’t have PHP locally ...
Annoyingly, I see PHPMailer’s composer.json file installed waiting to be used.
But no PHPMailerAutoload.php (is this created by Composer?)
So I try to do a manual install of PHPMailer. I download, unzip and FTP upload the resulting directories to my webspace in folder PHPMailer. I then insert the following at the head of my PHP code and outside of any functions:
require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
With the ‘use’ statements I get a syntax error unexpected 'use' (T_USE) …
Without them I get as far as trying to instantiate:
$mail = new PHPMailer;
but this fails with a ‘class 'PHPMailer' not found
What please am I doing wrong and how can I do better?
This isn't specific to PHPMailer - it's what you need to do to use any of the myriad PHP packages that use namespaces. The PHP docs on how to use use are here.
The short version is, you need to put namespace and use directives before any other scripting, so if you simply reverse the order of your commands, it should work:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';
Incidentally, this is the order used in the example in the PHPMailer readme and all the other examples provided with PHPMailer. You may find the upgrade guide useful too.
The PHPMailerAutoload.php file no longer exists - composer's autoloader does a much better job. PHPMailer's own composer.json file is used to resolve dependencies and flag compatibility requirements for your app's own composer file, that is, it's used to tell your project's composer file how to use PHPMailer – but is not your project's composer file itself – every package you load will have its own.
Developing without a local PHP instance is hard work – developing on your live server is, shall we say, "discouraged"! If you can't install PHP directly, run it in a container or VM using Docker, VirtualBox or something like XAMPP that's completely self-contained.
In version 6.02, each of the phpmailer modules contain the namespace PHPMailer\PHPMailer declaration so the following works (no autoloader needed but this routine should be in /src folder):
include($_SERVER['DOCUMENT_ROOT'].'/path_setup.php');
require_once ($_SERVER['DOCUMENT_ROOT'].'/php/PHPMailer/src/PHPMailer.php');
require_once ($_SERVER['DOCUMENT_ROOT'].'/php/PHPMailer/src/SMTP.php');
require_once ($_SERVER['DOCUMENT_ROOT'].'/php/PHPMailer/src/Exception.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
Modify you require, and try set like the wiki of PHPMailer says:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
Link of wiki
Not passable without composer....
Warning: require(src/Exception.php): failed to open stream: No such file or directory in C:\xampp\htdocs\testtest\test.php on line 5
Fatal error: require(): Failed opening required 'src/Exception.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\testtest\test.php on line 5
First create a folder src and create Exception.php,PHPMailer.php,SMTP.php Liber's then we get results
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "smtp.gmail.com"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = 'tls'; // ssl is depracated
$mail->SMTPAuth = true;
$mail->Username = '#gmail.com';
$mail->Password = '';
$mail->setFrom('#gmail.com', '...');
$mail->addReplyTo('#gmail.com', ' Name');
$mail->addAddress('#gmail.com', '...');
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->msgHTML("Hello test SMTP body"); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported';
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file
if(!$mail->send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "Message sent!";
}
?>*strong text*

PHPMailer loads a while, then gives 500 - Internal server error

I am trying to setup a php page to automatically send a verification email. I would like to use the gmail smtp servers, and everywhere I've looked suggests to use PHPMailer. I installed it and used the following example code:
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once ("incl\PHPMailer\PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
$mail->SetFrom('myemail#gmail.com','Me');
$mail->AddAddress("ToAddress#gmail.com");
$mail->Subject = "Verify your email";
$mail->Body = "Thank you for signing up. Please verify your email using the link below:";
$mail->IsHTML (true);
if($mail->Send()){
echo "Success";
}else{
echo "Error";
}
When trying to access the page via Firefox, the page will load for a few minutes, then give this error:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
The server is Windows Server 2008 R2 Standard running IIS 7.5 and PHP Version 5.5.8. I can access all other pages without issues, but trying to call $mail->Send() seems to be timing out or something. I know this because I commented every line and slowly added pieces back in and $mail->Send() is the line that causes the behavior.
My Google abilities are failing me here as I simply cannot figure out how to make this work. Any ideas on what might be wrong?
Update
I opened the server log then tried loading the page again, but no new errors were added to the log. However, I noticed the following errors from today in System32\LogFiles\httperr1.log
2014-10-27 06:29:21 1.161.23.122 3148 212.83.145.123 80 HTTP/1.0 CONNECT mx2.mail2000.com.tw:25 400 - URL -
2014-10-27 10:10:12 95.183.244.244 33553 212.83.145.123 80 HTTP/1.1 GET / 400 - Hostname -
2014-10-27 11:25:25 207.38.185.197 51157 212.83.145.123 80 HTTP/1.1 GET /tmUnblock.cgi 400 - Hostname -
2014-10-27 12:46:21 1.168.221.158 7952 212.83.145.123 80 - - - - - Timer_ConnectionIdle -
UPDATE 2
I am positive that my gmail account details are correct and have tested sending from it using Thunderbird on the server. When trying to sent without secured methods, as suggested in this comment I get this error:
MAIL FROM command failed,550,5.7.3 Requested action aborted; user not authenticated
My PHP Mailer version is 5.2.9 and I've now also tried the following:
Using \\ in file paths instead of \
No change
Including class.phpmailer.php instead of PHPMailerAutoload.php
Fatal error: Class 'SMTP' not found in C:\inetpub\wwwroot\incl\PHPMailer\class.phpmailer.php on line 1195
Using ssl over port 465
SMTP connect() failed
Sending with a hotmail address over port 25 with $mail->SMTPAuth = false;
MAIL FROM command failed,550,5.7.3 Requested action aborted; user not authenticated
Update 3
After reloading the problem page, I checked through the Event Viewer and saw a new entry in Windows Logs -> System:
PHP Error : syntax error, unexpected BOOL_TRUE in C:\PHP\php.ini on line 101
That line is:
php_flag display_errors on
Looks like you're dealing with bunch of issues and here is a checklist: you're having issues with ssl, the actual mail software and credentials. It became an issue of 3 from one main issue and I'm guessing you don't either have your credentials typed in correctly or your open ssl isn't setup and you're also having issues using the mail software.
535 535 5.7.3 Authentication Unsuccessful means auth is unsuccessful, check your credentials username and password.
550 error code, it means that the receiving system could not deliver your email to the user to whom it was addressed because the mailbox is unavailable.
There are plenty of other solutions to resolve your issue. Why don't you try something more simple instead of using the autoload PHPMailerAutoload.php. Create a new file and place the code below, create a message body (test_message.html) and call it from the browser to test gmail smtp with the gmail credentials. This is a snippet from PHPMailer on how to use it with gmail smtp and it shouldn't go wrong if you have everything filled in correctly.
<?php
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('test_message.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "yourusername#gmail.com"; // GMAIL username
$mail->Password = "yourpassword"; // GMAIL password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
If you're getting user auth error, then your credentials aren't typed in
correctly. If that's not the issue, you'll get an ssl error if you're not using the right port.
If there are software issues with include, you should try something better.
I was debating this morning if I should should PHPMailer, ended up using Swiftmailer which worked right after I installed it with PHPComposer.
My Internal mail server is extremely picky and has ton of firewall settings and rules on hardware and software level and I was surprised it didn't give me any problems; the emails were being sent right away without any problems on port 587.
require_once 'vendor/swiftmailer/swiftmailer/lib/swift_required.php';
$transport = Swift_SmtpTransport::newInstance('mail.hellog***.com', 587)
->setUsername('apache#hellog***.com')
->setPassword('apa******')
;
This is what you need for gmail:
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername($this->username)
->setPassword($this->password);
$this->mailer = Swift_Mailer::newInstance($transporter);
If none of what you like, you can try phpgmailer:
https://github.com/GregDracoulis/LectureBank/tree/master/phpgmailer
here is an example on how to use it:
http://www.vulgarisoverip.com/2006/10/13/update-send-email-with-php-and-gmail-hosted-for-your-domain/
this class is dedicated for gmail use.
If all your problems and issues relate to openSSL, you should follow the steps below:
1. Make sure the OpenSSL module DLL file is included in the PHP installation:
C:\user>dir \local\php\ext\php_openssl.dll
Directory of C:\local\php\ext
php_openssl.dll
2. Create the PHP configuration file, \local\php\php.ini, if it does not exist:
C:\user>copy \local\php\php.ini-production \local\php\php.ini
1 file(s) copied.
3. Enable the OpenSSL module by editing the configuration file with a text editor. You need to remove the comment maker (;) on two configuration lines:
...
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"
...
extension=php_openssl.dll
...
That’s it. You should be all set setting up openSSL on your Windows IIS WebServer. Follow these options and steps, it could be your issue.
This problem is slashes ( \ )
Edit
require_once ("incl\\PHPMailer\\PHPMailerAutoload.php");
I have tried with you code, and i have only changed this line :
require_once ("incl\PHPMailer\PHPMailerAutoload.php");
by this one :
require_once ("incl\PHPMailer\class.phpmailer.php");
And it was worked successfully.
Also you should keep attention about your PHPMailer version and your PHP version.
Have you tried to send an email with not secured method ?
Are you sure that your google credentials are valid ?
UPDATED
From the command line of your server, what is the output of this command and how much time that it takes to respond
telnet smtp.gmail.com 587
I wonder if you are running into the same issue that this question ran into. Google actively frowns on people using Gmail as their own personal SMTP server.
http://www.labnol.org/internet/email/gmail-daily-limit-sending-bulk-email/2191/
Google also limits the number of email messages that you can send through your Gmail account in a day. If you exceed the daily quota, Google may temporarily disable your Gmail account without any warnings and you may have to wait for up to 24 hours before you can regain access to your Gmail mailbox.
I could see an error like that potentially producing a 500 error.
From the comments to the question, it seems pretty clear that this issue is OpenSSL related.
You mentioned that you already have extension=php_openssl.dll uncommented, but phpinfo() does show it not beeing loaded.
Some thoughts:
Have you restarted the webserver, after uncommenting the openssl php module in your php.ini?
This is the really obvious one, but still worth mentioning. The php.ini is loaded on start-up, and not doing a service restart is simply a common mistake.
Check the value of Loaded Configuration File in phpinfo()
If this is not the same location than the php.ini which you have edited, it also becomes clear why it has not been loaded. Also following lines from phpinfo() might be worth checking.
Configuration File (php.ini) Path
Loaded Configuration File
Scan this dir for additional .ini files
There are other things too which can be done like uninstalling and reinstalling OpenSSL, but it might be good to check these more obvious things first.
Further thoughts:
Checking the error logs
For php the path can (again) be found in your phpinfo(). Look for the value of error_log and check the latest entries, right after you tried to reload your page.
Also you may wanna check the log files of IIS. If you don't know the path look in the IIS Manager, select the computer on the left pane, and in the middle pane, go under "logging" in the IIS area. Usually these will point to something like C:\inetpub\logs\LogFiles or C:\Windows\System32\LogFiles with a subfolder like W3SVC[x] where [x] is the website ID. (Will be just 1 if you only have one page, otherwise check the top level websites folder in IIS Manager, view the lists of sites in the right hand pane, it's the App ID)
Setting Up and Configuring IIS
Start by going to the ServerManager on you Server. Most often this is the server you’ll be running your php website on. Go to Add features in the Features summary section. Check SMTP Services in the Add Features Wizard and hit install. Now wait for the installation to finish. Open IIS6 (or IIS7) Manager under Administrative Tools -> Internet Information Services 6.0 in the Start Menu, the configuration of SMTP makes use of the management console from IIS6. Under [SMTP Virtual Server], click your right mouse button and select properties from the context menu. Go to the Access Tab and hit the Relay button.Add a new entry to the list by clicking the Add button and enter 127.0.0.1 (or your web server's IP) in the single computer entry field. Hit Ok two times to apply the new settings.
Configuring Php
To make Php send emails you need to make some configurations. Basically there are two options.
In case you’re only going to use the SMTP server in a single project and do not want it to interfere with other projects, you can set the configuration from within your php code by adding the following lines anywhere before sending the email:
ini_set('SMTP','localhost' );
ini_set('sendmail_from', 'administrator#YourWebsite.com');
Another way, to make global use of these settings, add the next lines to your php.ini file.
[mail function]
SMTP = localhost
sendmail_from = me#example.com
Make sure you restart your server after making these changes, to be sure they’re loaded.
This solution is provided here http://geekswithblogs.net/tkokke/archive/2009/05/31/sending-email-from-php-on-windows-using-iis.aspx on how to set up IIS and php and was provided as answer to this question 500 error when trying to use the MAIL function
Try to use SSL encryption with a port 465:
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
Warning: require_once(mailer/PHPMailerAutoload.php): failed to open
stream: No such file or directory in....
This is the way I had my file routed
Before:
require_once "mailer/PHPMailerAutoload.php";
After:
require_once "../mailer/PHPMailerAutoload.php";
...Same process you would normally do to link an img as background using css.

PHP send mail on windows causing it to 'hang' after sending email

we're starting to build a web app. My colleague is developing on linux, and I am running via a WAMP stack running windows xp. We're using Zend.
When we submit a form and send an email using Zend email, the email would send and then I would get a blank screen, wheras on the linux machine the app would continue normally.
So I wrote my own little script, mail.php which uses phpmailer - and the exact same thing happens, the email sends, and then blank screen. So we have:
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
So there is no error reported, the email sends, but "Message has been sent" never prints to the screen (or anything else, normal HTML too).
I am not very technical, so apologies if there are obvious debug steps to take. Is there something peculiar to windows php config that I have missed?
It's an off-site SMTP server with authentication.
Sounds like you are getting an error, but just not seeing it. Make sure you have this somewhere in your code
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
And inspect your apache logs for 500 errors as well.
PHP has it's own error log, when in doubt check there. You should be able to locate it by running
<?php
phpinfo();
?>
It should be located in the PHP Core section - if it's blank, edit your php.ini file and turn log_errors on and specify where you want the file to be.
Errors I couldn't get to display I've found using this.
UPDATE
Did some digging and it seems that Zend_Mail is essentially a wrapper for PHP's mail() function according to the documentation: http://framework.zend.com/manual/en/zend.mail.html
With that in mind there's some information on PHP's mail() function in the PHP manual that you're going to want to look at regarding SendMail http://www.php.net/manual/en/ref.mail.php the first comment on the page (as of this writing) has all the details on configuring your WAMP server to behave like a *nix server - at least as far as mail() operations go ;-)
I use phpmailer with success on a windows box (my dev machine). Can I see the setup code? I do something like the below. One thing is you need to make sure openssl module is installed in php if you are using ssl. Take a look at the below. Make sure your SMTPDebug flag is set to have some output that you can work with.
<?php
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "blah.com";
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "mail.blah.com";
$mail->Port = 465;
$mail->Username = "noreply#blah.com";
$mail->Password = "smtppass";
$mail->SetFrom('noreply#blah.com', 'Blah Name');
$mail->AddReplyTo("noreply#blah.com", "Blah Name");
$mail->Sender = "noreply#blah.com"
?>
apologies for taking so long to answer this. The problem was caused by a firewall in the office blocking outbound SMTP traffic. I am still not sure as to why it returned nothing - but outside of this office when it was tested the php errors for invalid smtp etc. returned fine. Just a case of getting the appropriate ports allowed on the network.
Thanks everyone for their help.

How to send an email using Zend_Mail, sendmail, and localhost?

I'm developing a zend framework application that includes a simple email function. The development version is running on my computer, which is running Ubuntu. The production version is going to run on a production server.
When trying to send a test email to myself, I get an exception with the message: "Unable to send mail". I don't know if this is an environment issue, or a code issue. I'm not using a transport so I think it is defaulting to Zend_Mail_Transport_Sendmail. Here's my code:
public function sendtestAction()
{
$mail = new Zend_Mail();
$mail->setFrom('test#aol.com', 'Test Email');
$mail->addTo('my#email.com', 'My Name');
$mail->setSubject('This is just a test.');
$mail->setBodyText('This is only a test.');
$mail->send();
}
Update: I tried a different approach by setting the SMTP transport to use localhost:
transport = new Zend_Mail_Transport_Smtp('localhost');
Zend_Mail::setDefaultTransport($transport);
I got a different error this time: "Connection refused" Not sure what that means. Maybe I haven't set something up yet?
Update: I guess I didn't have an SMTP server installed/setup. This tutorial made it really easy for me to get an SMTP server up an running. Now both of the code samples above work.
It sounds like you need to configure an MTA, or find one that you can send to. Ubuntu desktop should set one up by default, probably either exim or postfix, but if you haven't configured it, it will unlikely to be running.
You don't want to set the default transport if you wish to use sendmail (it is the default) and SMTP is different.
That it doesn't send the emails suggests that sendmail or the MTA on your server is not installed/not setup correctly.

Categories