I’m using the mail() basic example modified slightly for my user id and I’m getting the error «Mailer Error: Could not instantiate mail function»
if I use the mail function —
mail($to, $subject, $message, $headers);
it works fine, though I’m having trouble sending HTML, which is why I’m trying PHPMailer.
this is the code:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[]",'',$body);
print ($body ); // to verify that I got the html
$mail->AddReplyTo("reply@example.com","my name");
$mail->SetFrom('from@example.com', 'my name');
$address = "to@example.com";
$mail->AddAddress($address, "her name");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$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!";
}
?>
asked Aug 18, 2009 at 23:20
3
Try using SMTP to send email:-
$mail->IsSMTP();
$mail->Host = "smtp.example.com";
// optional
// used only when SMTP requires authentication
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';
answered Aug 22, 2011 at 8:55
Mukesh ChapagainMukesh Chapagain
24.6k15 gold badges116 silver badges119 bronze badges
4
Your code looks good, did you forget to install PostFix on your server?
sudo apt-get install postfix
It worked for me 
Cheers
Andrew
17.8k12 gold badges102 silver badges112 bronze badges
answered Feb 6, 2018 at 13:22
IrwuinIrwuin
4933 silver badges9 bronze badges
2
This worked for me
$mail->SetFrom("from@domain.co","my name", 0); //notice the third parameter
answered Feb 27, 2016 at 20:52
Matías CánepaMatías Cánepa
5,5754 gold badges56 silver badges94 bronze badges
2
$mail->AddAddress($address, "her name");
should be changed to
$mail->AddAddress($address);
This worked for my case..
answered Aug 31, 2011 at 12:09
AvinashAvinash
6,00415 gold badges59 silver badges93 bronze badges
5
You need to make sure that your from address is a valid email account setup on that server.
answered Jun 19, 2010 at 7:31
D.F.D.F.
1851 silver badge6 bronze badges
0
If you are sending file attachments and your code works for small attachments but fails for large attachments:
If you get the error «Could not instantiate mail function» error when you try to send large emails and your PHP error log contains the message «Cannot send message: Too big» then your mail transfer agent (sendmail, postfix, exim, etc) is refusing to deliver these emails.
The solution is to configure the MTA to allow larger attachments. But this is not always possible. The alternate solution is to use SMTP. You will need access to a SMTP server (and login credentials if your SMTP server requires authentication):
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.example.com"; // set the SMTP server
$mail->Port = 26; // set the SMTP port
$mail->Username = "johndoe@example.com"; // SMTP account username
$mail->Password = "********"; // SMTP account password
PHPMailer defaults to using PHP mail() function which uses settings from php.ini which normally defaults to use sendmail (or something similar). In the above example we override the default behavior.
answered Aug 26, 2015 at 21:15
Salman ASalman A
255k81 gold badges426 silver badges515 bronze badges
The PHPMailer help docs on this specific error helped to get me on the right path.
What we found is that php.ini did not have the sendmail_path defined, so I added that with sendmail_path = /usr/sbin/sendmail -t -i;
answered May 4, 2017 at 1:24
Matt PopeMatt Pope
1672 silver badges11 bronze badges
1
In my case, it was the attachment size limit that causes the issue. Check and increase the size limit of mail worked for me.
answered Oct 31, 2018 at 17:59
1
Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.
answered Nov 10, 2016 at 10:32
AlexAlex
1,2571 gold badge15 silver badges12 bronze badges
I had this issue, and after doing some debugging, and searching I realized that the SERVER (Godaddy) can have issues.
I recommend you contact your Web hosting Provider and talk to them about Quota Restrictions on the mail function (They do this to prevent people doing spam bots or mass emailing (spam) ).
They may be able to advise you of their limits, and if you’re exceeding them. You can also possibly upgrade limit by going to private server.
After talking with GoDaddy for 15 minutes the tech support was able to resolve this within 20 minutes.
This helped me out a lot, and I wanted to share it so if someone else comes across this they can try this method if all fails, or before they try anything else.
answered Jan 21, 2017 at 7:47
kraykray
1,4802 gold badges18 silver badges36 bronze badges
An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini
answered Jun 6, 2013 at 0:38
I had this issue as well. My solution was to disable selinux. I tried allowing 2 different http settings in selinux (something like httpd_allow_email and http_can_connect) and that didn’t work, so I just disabled it completely and it started working.
answered Dec 30, 2014 at 19:53
iAndyiAndy
113 bronze badges
I was having this issue while sending files with regional characters in their names like: VęryRęgióńął file - name.pdf.
The solution was to clear filename before attaching it to the email.
answered Aug 20, 2016 at 19:20
jmarcelijmarceli
18.5k6 gold badges67 silver badges66 bronze badges
Check if sendmail is enabled, mostly if your server is provided by another company.
answered Oct 5, 2017 at 13:43
For what it’s worth I had this issue and had to go into cPanel where I saw the error message
«Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find «Registered Mail IDs» plugin in paper_lantern theme.»
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
answered Jun 21, 2018 at 10:19
MomasVIIMomasVII
4,3503 gold badges31 silver badges47 bronze badges
A lot of people often overlook the best/right way to call phpmailer and to put these:
require_once('../class.phpmailer.php');
or, something like this from the composer installation:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require_once "../../vendor/autoload.php";
on TOP of the page before calling or including anything else. That causes the «Could not instantiate mail function»-error by most folks.
Best solution: put all mail handling in a different file to have it as clean as possible. And always use SMTP.
If that is not working, check your DNS if your allowed to send mail.
answered Dec 24, 2021 at 22:20
KJSKJS
1,1561 gold badge12 silver badges28 bronze badges
My config: IIS + php7.4
I had the same issue as @Salman-A, where small attachments were emailed but large were causing the page to error out.
I have increased file and attachments limits in php.ini, but this has made no difference.
Then I found a configuration in IIS(6.0), and increased file limits in there.
Also here is my mail.php:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require '../_PHPMailer-master/src/Exception.php';
require '../_PHPMailer-master/src/PHPMailer.php';
try{
$email = new PHPMailer(true);
$email->SetFrom('internal@example.com', 'optional name');
$email->isHTML(true);
$email->Subject = 'my subject';
$email->Body = $emailContent;
$email->AddAddress( $eml_to );
$email->AddAttachment( $file_to_attach );
$email->Send();
}catch(phpmailerException $e){echo $e->errorMessage();}
future.
answered Sep 8, 2020 at 14:39
michalmichal
3274 silver badges15 bronze badges
We nee to change the values of ‘SMTP’ in php.ini file
php.ini file is located into
EasyPHP-DevServer-14.1VC11binariesphpphp_runningversionphp.ini
answered Oct 24, 2014 at 5:48
Are you stuck with “PHPMailer could not instantiate mail function”?
PHPMailer helps to send emails safely and easily from a web server. However, it often errors out due to misconfigurations of the mail() function, absence of local mail server and so on.
At Bobcares, we often receive requests to fix this error as part of our Server Management Services.
Today, let’s have a deep look at this error and see how our Support Engineers fix PHPMailer easily.
Why does PHPMailer could not instantiate mail function occurs?
As we all know, PHPMailer is a popular code for sending email from PHP. And, many open-source projects like WordPress, Drupal, etc use them.
PHPMailer validates email addresses automatically and protects against header injection attacks.
Developers often prefer sending mail from their code. And, mail() is the only PHP function that supports this.
But, sometimes the incorrect PHP installation fails to call the mail() function correctly. This will cause mail function errors.
Similarly, in some cases, the absence of a local mail server will also cause this error.
How to fix “PHPMailer could not instantiate mail function”?
So far we have discussed the error in detail. Now, let’s have a look at some of its top fixes.
There are alternative ways to resolve this error easily.
1. Using SMTP to send the email
As we have already said, if the PHP installation is not configured to call the mail() function correctly, it will cause the error.
So, in such cases, it is better to use isSMTP() and send the email directly using SMTP.
This is faster, safer and easier to debug than using mail(). This will resolve the error easily.
2. Install a local mail server
The PHP mail() function usually sends the mail via a local mail server.
So, using SMTP will not resolve the error if a mail server is not set up on the localhost.
Therefore, it is necessary to install a local mail server. For instance, we can install PostFix to the server using the below command.
sudo apt-get install postfix
3. Other Solutions
The PHP mail() function works with the Sendmail binary on Linux, BSD, and macOS platforms.
So, it is important to ensure that the sendmail_path points at the Sendmail binary, which is usually /usr/sbin/sendmail in php.ini.
Similarly, sometimes when we try to send large emails, it returns “Could not instantiate mail function” error along with “Cannot send message: Too big” message in the PHP error log.
This means the mail transfer agent is refusing to deliver these emails.
So, we need to configure the MTA to allow larger attachments to resolve the error.
[Still facing difficulty to fix PHPMailer error?- We’ll help you.]
Conclusion
In short, PHPMailer could not instantiate mail function occurs due to misconfigurations of the mail() function, absence of local mail server and so on. In today’s writeup, we discussed this error in detail and saw some of the major fixes by our Support Engineers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
I’m using the mail() basic example modified slightly for my user id and I’m getting the error «Mailer Error: Could not instantiate mail function»
if I use the mail function —
mail($to, $subject, $message, $headers);
it works fine, though I’m having trouble sending HTML, which is why I’m trying PHPMailer.
this is the code:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[]",'',$body);
print ($body ); // to verify that I got the html
$mail->AddReplyTo("reply@example.com","my name");
$mail->SetFrom('from@example.com', 'my name');
$address = "to@example.com";
$mail->AddAddress($address, "her name");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$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!";
}
?>
asked Aug 18, 2009 at 23:20
3
Try using SMTP to send email:-
$mail->IsSMTP();
$mail->Host = "smtp.example.com";
// optional
// used only when SMTP requires authentication
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';
answered Aug 22, 2011 at 8:55
Mukesh ChapagainMukesh Chapagain
24.6k15 gold badges116 silver badges119 bronze badges
4
Your code looks good, did you forget to install PostFix on your server?
sudo apt-get install postfix
It worked for me 
Cheers
Andrew
17.8k12 gold badges102 silver badges112 bronze badges
answered Feb 6, 2018 at 13:22
IrwuinIrwuin
4933 silver badges9 bronze badges
2
This worked for me
$mail->SetFrom("from@domain.co","my name", 0); //notice the third parameter
answered Feb 27, 2016 at 20:52
Matías CánepaMatías Cánepa
5,5754 gold badges56 silver badges94 bronze badges
2
$mail->AddAddress($address, "her name");
should be changed to
$mail->AddAddress($address);
This worked for my case..
answered Aug 31, 2011 at 12:09
AvinashAvinash
6,00415 gold badges59 silver badges93 bronze badges
5
You need to make sure that your from address is a valid email account setup on that server.
answered Jun 19, 2010 at 7:31
D.F.D.F.
1851 silver badge6 bronze badges
0
If you are sending file attachments and your code works for small attachments but fails for large attachments:
If you get the error «Could not instantiate mail function» error when you try to send large emails and your PHP error log contains the message «Cannot send message: Too big» then your mail transfer agent (sendmail, postfix, exim, etc) is refusing to deliver these emails.
The solution is to configure the MTA to allow larger attachments. But this is not always possible. The alternate solution is to use SMTP. You will need access to a SMTP server (and login credentials if your SMTP server requires authentication):
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.example.com"; // set the SMTP server
$mail->Port = 26; // set the SMTP port
$mail->Username = "johndoe@example.com"; // SMTP account username
$mail->Password = "********"; // SMTP account password
PHPMailer defaults to using PHP mail() function which uses settings from php.ini which normally defaults to use sendmail (or something similar). In the above example we override the default behavior.
answered Aug 26, 2015 at 21:15
Salman ASalman A
255k81 gold badges426 silver badges515 bronze badges
The PHPMailer help docs on this specific error helped to get me on the right path.
What we found is that php.ini did not have the sendmail_path defined, so I added that with sendmail_path = /usr/sbin/sendmail -t -i;
answered May 4, 2017 at 1:24
Matt PopeMatt Pope
1672 silver badges11 bronze badges
1
In my case, it was the attachment size limit that causes the issue. Check and increase the size limit of mail worked for me.
answered Oct 31, 2018 at 17:59
1
Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.
answered Nov 10, 2016 at 10:32
AlexAlex
1,2571 gold badge15 silver badges12 bronze badges
I had this issue, and after doing some debugging, and searching I realized that the SERVER (Godaddy) can have issues.
I recommend you contact your Web hosting Provider and talk to them about Quota Restrictions on the mail function (They do this to prevent people doing spam bots or mass emailing (spam) ).
They may be able to advise you of their limits, and if you’re exceeding them. You can also possibly upgrade limit by going to private server.
After talking with GoDaddy for 15 minutes the tech support was able to resolve this within 20 minutes.
This helped me out a lot, and I wanted to share it so if someone else comes across this they can try this method if all fails, or before they try anything else.
answered Jan 21, 2017 at 7:47
kraykray
1,4802 gold badges18 silver badges36 bronze badges
An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini
answered Jun 6, 2013 at 0:38
I had this issue as well. My solution was to disable selinux. I tried allowing 2 different http settings in selinux (something like httpd_allow_email and http_can_connect) and that didn’t work, so I just disabled it completely and it started working.
answered Dec 30, 2014 at 19:53
iAndyiAndy
113 bronze badges
I was having this issue while sending files with regional characters in their names like: VęryRęgióńął file - name.pdf.
The solution was to clear filename before attaching it to the email.
answered Aug 20, 2016 at 19:20
jmarcelijmarceli
18.5k6 gold badges67 silver badges66 bronze badges
Check if sendmail is enabled, mostly if your server is provided by another company.
answered Oct 5, 2017 at 13:43
For what it’s worth I had this issue and had to go into cPanel where I saw the error message
«Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find «Registered Mail IDs» plugin in paper_lantern theme.»
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
answered Jun 21, 2018 at 10:19
MomasVIIMomasVII
4,3503 gold badges31 silver badges47 bronze badges
A lot of people often overlook the best/right way to call phpmailer and to put these:
require_once('../class.phpmailer.php');
or, something like this from the composer installation:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require_once "../../vendor/autoload.php";
on TOP of the page before calling or including anything else. That causes the «Could not instantiate mail function»-error by most folks.
Best solution: put all mail handling in a different file to have it as clean as possible. And always use SMTP.
If that is not working, check your DNS if your allowed to send mail.
answered Dec 24, 2021 at 22:20
KJSKJS
1,1561 gold badge12 silver badges28 bronze badges
My config: IIS + php7.4
I had the same issue as @Salman-A, where small attachments were emailed but large were causing the page to error out.
I have increased file and attachments limits in php.ini, but this has made no difference.
Then I found a configuration in IIS(6.0), and increased file limits in there.
Also here is my mail.php:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require '../_PHPMailer-master/src/Exception.php';
require '../_PHPMailer-master/src/PHPMailer.php';
try{
$email = new PHPMailer(true);
$email->SetFrom('internal@example.com', 'optional name');
$email->isHTML(true);
$email->Subject = 'my subject';
$email->Body = $emailContent;
$email->AddAddress( $eml_to );
$email->AddAttachment( $file_to_attach );
$email->Send();
}catch(phpmailerException $e){echo $e->errorMessage();}
future.
answered Sep 8, 2020 at 14:39
michalmichal
3274 silver badges15 bronze badges
We nee to change the values of ‘SMTP’ in php.ini file
php.ini file is located into
EasyPHP-DevServer-14.1VC11binariesphpphp_runningversionphp.ini
answered Oct 24, 2014 at 5:48
I’m using the mail() basic example modified slightly for my user id and I’m getting the error «Mailer Error: Could not instantiate mail function»
if I use the mail function —
mail($to, $subject, $message, $headers);
it works fine, though I’m having trouble sending HTML, which is why I’m trying PHPMailer.
this is the code:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[]",'',$body);
print ($body ); // to verify that I got the html
$mail->AddReplyTo("reply@example.com","my name");
$mail->SetFrom('from@example.com', 'my name');
$address = "to@example.com";
$mail->AddAddress($address, "her name");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$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!";
}
?>
asked Aug 18, 2009 at 23:20
3
Try using SMTP to send email:-
$mail->IsSMTP();
$mail->Host = "smtp.example.com";
// optional
// used only when SMTP requires authentication
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';
answered Aug 22, 2011 at 8:55
Mukesh ChapagainMukesh Chapagain
24.6k15 gold badges116 silver badges119 bronze badges
4
Your code looks good, did you forget to install PostFix on your server?
sudo apt-get install postfix
It worked for me 
Cheers
Andrew
17.8k12 gold badges102 silver badges112 bronze badges
answered Feb 6, 2018 at 13:22
IrwuinIrwuin
4933 silver badges9 bronze badges
2
This worked for me
$mail->SetFrom("from@domain.co","my name", 0); //notice the third parameter
answered Feb 27, 2016 at 20:52
Matías CánepaMatías Cánepa
5,5754 gold badges56 silver badges94 bronze badges
2
$mail->AddAddress($address, "her name");
should be changed to
$mail->AddAddress($address);
This worked for my case..
answered Aug 31, 2011 at 12:09
AvinashAvinash
6,00415 gold badges59 silver badges93 bronze badges
5
You need to make sure that your from address is a valid email account setup on that server.
answered Jun 19, 2010 at 7:31
D.F.D.F.
1851 silver badge6 bronze badges
0
If you are sending file attachments and your code works for small attachments but fails for large attachments:
If you get the error «Could not instantiate mail function» error when you try to send large emails and your PHP error log contains the message «Cannot send message: Too big» then your mail transfer agent (sendmail, postfix, exim, etc) is refusing to deliver these emails.
The solution is to configure the MTA to allow larger attachments. But this is not always possible. The alternate solution is to use SMTP. You will need access to a SMTP server (and login credentials if your SMTP server requires authentication):
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.example.com"; // set the SMTP server
$mail->Port = 26; // set the SMTP port
$mail->Username = "johndoe@example.com"; // SMTP account username
$mail->Password = "********"; // SMTP account password
PHPMailer defaults to using PHP mail() function which uses settings from php.ini which normally defaults to use sendmail (or something similar). In the above example we override the default behavior.
answered Aug 26, 2015 at 21:15
Salman ASalman A
255k81 gold badges426 silver badges515 bronze badges
The PHPMailer help docs on this specific error helped to get me on the right path.
What we found is that php.ini did not have the sendmail_path defined, so I added that with sendmail_path = /usr/sbin/sendmail -t -i;
answered May 4, 2017 at 1:24
Matt PopeMatt Pope
1672 silver badges11 bronze badges
1
In my case, it was the attachment size limit that causes the issue. Check and increase the size limit of mail worked for me.
answered Oct 31, 2018 at 17:59
1
Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.
answered Nov 10, 2016 at 10:32
AlexAlex
1,2571 gold badge15 silver badges12 bronze badges
I had this issue, and after doing some debugging, and searching I realized that the SERVER (Godaddy) can have issues.
I recommend you contact your Web hosting Provider and talk to them about Quota Restrictions on the mail function (They do this to prevent people doing spam bots or mass emailing (spam) ).
They may be able to advise you of their limits, and if you’re exceeding them. You can also possibly upgrade limit by going to private server.
After talking with GoDaddy for 15 minutes the tech support was able to resolve this within 20 minutes.
This helped me out a lot, and I wanted to share it so if someone else comes across this they can try this method if all fails, or before they try anything else.
answered Jan 21, 2017 at 7:47
kraykray
1,4802 gold badges18 silver badges36 bronze badges
An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini
answered Jun 6, 2013 at 0:38
I had this issue as well. My solution was to disable selinux. I tried allowing 2 different http settings in selinux (something like httpd_allow_email and http_can_connect) and that didn’t work, so I just disabled it completely and it started working.
answered Dec 30, 2014 at 19:53
iAndyiAndy
113 bronze badges
I was having this issue while sending files with regional characters in their names like: VęryRęgióńął file - name.pdf.
The solution was to clear filename before attaching it to the email.
answered Aug 20, 2016 at 19:20
jmarcelijmarceli
18.5k6 gold badges67 silver badges66 bronze badges
Check if sendmail is enabled, mostly if your server is provided by another company.
answered Oct 5, 2017 at 13:43
For what it’s worth I had this issue and had to go into cPanel where I saw the error message
«Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find «Registered Mail IDs» plugin in paper_lantern theme.»
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
answered Jun 21, 2018 at 10:19
MomasVIIMomasVII
4,3503 gold badges31 silver badges47 bronze badges
A lot of people often overlook the best/right way to call phpmailer and to put these:
require_once('../class.phpmailer.php');
or, something like this from the composer installation:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require_once "../../vendor/autoload.php";
on TOP of the page before calling or including anything else. That causes the «Could not instantiate mail function»-error by most folks.
Best solution: put all mail handling in a different file to have it as clean as possible. And always use SMTP.
If that is not working, check your DNS if your allowed to send mail.
answered Dec 24, 2021 at 22:20
KJSKJS
1,1561 gold badge12 silver badges28 bronze badges
My config: IIS + php7.4
I had the same issue as @Salman-A, where small attachments were emailed but large were causing the page to error out.
I have increased file and attachments limits in php.ini, but this has made no difference.
Then I found a configuration in IIS(6.0), and increased file limits in there.
Also here is my mail.php:
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require '../_PHPMailer-master/src/Exception.php';
require '../_PHPMailer-master/src/PHPMailer.php';
try{
$email = new PHPMailer(true);
$email->SetFrom('internal@example.com', 'optional name');
$email->isHTML(true);
$email->Subject = 'my subject';
$email->Body = $emailContent;
$email->AddAddress( $eml_to );
$email->AddAttachment( $file_to_attach );
$email->Send();
}catch(phpmailerException $e){echo $e->errorMessage();}
future.
answered Sep 8, 2020 at 14:39
michalmichal
3274 silver badges15 bronze badges
We nee to change the values of ‘SMTP’ in php.ini file
php.ini file is located into
EasyPHP-DevServer-14.1VC11binariesphpphp_runningversionphp.ini
answered Oct 24, 2014 at 5:48
В этой статье мы рассмотрим проблемы, возникающие с отправкой почты на CMS Joomla.
Наиболее часто встречаются ошибки вида «Could not instantiate mail function.» и «Не удалось вызвать функцию mail», также бывают случаи, когда никакой ошибки не отображается, тем не менее письма не приходят на почту. На всех этих случаях мы остановимся подробнее далее, если у вас возникают проблемы с отправкой почты по протоколу SMTP, то вам будет полезна эта статья.
Ошибки, описанные выше, могут быть вызваны рядом причин. В этой статье я попытался систематизировать информацию по проблемам с отправкой писем на Joomla и их решениям.
1. Вы настраиваете модуль обратный связи, отправку почты и тп на локальном сервере.
На локальных серверах вроде Denver или WAMP по умолчанию стоят заглушки, которые препятствуют отправке писем. Как правило, после переноса сайта на хостинг эти проблемы пропадут.
2. Вы получаете письма на yandex или mail почту.
Эти почтовые службы с большим подозрением относятся к получаемым сообщениям. Если, например, ваш сайт висит на одном IP c рассыльщиками спама, велика вероятность, что и вы попадете в список подозрительных отправителей и будете получать сообщения в папку спам либо с большой задержкой либо сообщения в принципе не будут доходить. Как можно решить эту проблему? Ниже мои советы от простого к сложному.
2а. Если письмо нашлось в спаме, просто добавьте адрес с которого оно пришло в адресную книгу, после этого письма начнут приходить в основные папки.
2б. Настройте отправку через SMTP. Это можно сделать буквально за 5 минут, инструкцию можно найти здесь. На мой взгляд самый простой и надежный способ.
2в. Если отправка через SMTP вам не подходит, можно попробовать создать ящик на вашем хостинге, он будет выглядеть примерно так название_ящика@ваш_домен.ru и добавить его в поле email-сайта на вкладке сервер. Почтовый сервер будет видеть в исходящих почту с вашим доменом и траст письма повысится. Сделать это можно в панели администратора, «System->Global configuration» («Система->Общие настройки»). В этом разделе открыть вкладку Server (Сервер) и в правом нижнем углу найти настройки отправления почты.
2г. Настройте spf. Spf это верификация вашего домена, настраивается на хостинге за пару минут при наличие инструкции. Так как я не знаю ваш хостинг, то инструкцию вам придется найти самостоятельно, обычно достаточно набрать в поиске что-то вроде «spf beget» (бегет это мой хостинг) и открыть первую ссылку. Перед гуглением можно попробовать посмотреть здесь, там размещены настройки для кучи популярных хостингов.
2д. Настроить DKIM. DKIM это цифровая подпись, настраивается тоже по инструкции хостинга, но в отличие от spf услуга может быть платной. Перед приобретением рекомендую вам связаться со своим хостером и уточнить возможные причины не прихода писем.
3. Проблемы с PHP Mailer.
Довольно распространенный случай. В Joomla предусмотрено 3 механизма отправки писем: PHP Mail, Sendmail и SMTP. По-умолчанию используется первый и с ним зачастую бывают проблемы. Ниже я предлагаю несколько путей решения проблемы.
2a. Самый простой способ решить проблему, это изменить способ отправки на Sendmail. Для этого в панели администратора надо перейти в «System->Global configuration» («Система->Общие настройки»), где открыть вкладку Server (Сервер). Справа внизу вы увидите настройки почты, в поле «Mailer» («Способ отправки») в выпадающем списке надо выбрать «Sendmail». Можно также поменять способ отправки на SMTP, как это сделать читайте здесь.
3б. Также можно попробовать починить PHP Mailer вручную . Для этого надо найти и открыть файл:»корень сайта/libraries/phpmailer/phpmailer.php» или «корень сайта/libraries/vendor/phpmailer/phpmailer/class.phpmailer.php» для поздних версий джумлы. Далее найти строчку:
$params = sprintf(‘-oi -f %s’, $this->Sender);
Вероятный номер строки 707 или 1161. И дописать под ней:
$params = ‘ ‘;
Ваш код теперь выглядит так:
if (empty($this->Sender)) {
$params = ‘-oi -f %s’;
} else {
$params = sprintf(‘-oi -f %s’, $this->Sender);
$params = ‘ ‘;
}
Или в случае более поздней версии заменить искомую строку:
Код:
$params = sprintf(‘-f%s’, $this->Sender);
Меняется на:
$params = sprintf(‘-f%s’);
4. Проблемы с хостингом.
Возможно вы используете бесплатный тариф, на котором закрыта отправка писем или он включает этот функционал по требования. Как бы то ни было, вам нужно написать в службу поддержки и объяснить проблему.
Joomla — хороший движок, но не идеальный. Даже на таком удобном конструкторе могут выскакивать весьма неудобные проблемы. К примеру, в CMS Joomla выскакивает белый экран при входе в админку. Либо возникают ошибки в результате активации человекопонятных ссылок в настройках.
Но одна из самых распространенных и непонятных для многих вебмастеров ошибка — это «сould not instantiate mail function».
Такое случается, когда вам не удалось вызвать функцию отправления электронного письма при помощи движка Joomla. Рассмотрим возможные причины возникновения ошибки и методы ее решения.
Почему не удалось вызвать функцию отправки на имейл в Joomla
Итак, попробуем определить причину появления навязчивого сообщения «сould not instantiate mail function» и почему не удалось вызвать функцию в разных ситуациях.
Первая причина, почему выскочила надпись «сould not instantiate mail function» при попытки отправить письмо на имейл — это ваш хостинг, а точнее ваш локальный сервер. Часто вебмастера перед тем, как что-то устанавливать на сайт или перед его публикацией, проводят эксперименты вдали от сети Интернет — у себя на компьютере на созданном виртуальном сервере. Если вы сейчас редактируете содержимое сайта именно при помощи локального сервера, то функцию не удалось вызвать по очень простой причине — у вас на компьютере нет куда отправлять имейл. То есть у вас нет сервера для отправки электронных писем. И неважно какой именно локальный хост вы используете, WAMP или Денвер — вы все равно не сможете отправлять с него электронные письма.
Порой надпись «сould not instantiate mail function» появляется, но не при каждом отправлении письма. К примеру, когда вы делаете рассылки своим подписчикам и из тысячи человек 20 не получают письма, так как не удалось вызвать эту функцию в Joomla. В таком случае объяснение простое — они ввели неправильный адрес электронной почты, когда подписывались на вашу рассылку. Решить такую проблему невозможно — придется удалить невнимательных подписчиков.
Иногда Joomla выдает надпись «сould not instantiate mail function» из-за того, что вы ввели в данных отправки какие-то специальные символы, которые сервер не воспринимает. Особенно часто эту случается в тех случаях, когда вы создаете скрипт рассылки и указываете в нем имя пользователя с какими-то особыми знаками. Если это так, то чтобы удалось вызвать функцию отправки электронного письма в Joomla, вам необходимо нажать пункт Yes возле графы Adds Names, чтобы сервис добавлял имена в письма и воспринимал специальные символы.
Еще одна причина, по которой вместо отчета об отправке сообщений вы увидите «сould not instantiate mail function» — это недействительный донорский адрес имейл. Дело в том, что даже если сообщения отправляет ваш сервер, они не придут получателю, если не будет указан отправитель. Возможно, вы указали неверный имейл отправителя, ведь эта почта должна быть зарегистрирована на вашем доменном имени.
Если все перечисленные причины не подходят для вашего случая, то попытайтесь разведать обстановку у хостинг-провайдера. Очень часто на хостинге ставят ограничения для различных услуг. Таким образом они завлекают клиентов покупать пакеты подороже. Есть вероятность, что не удалось вызвать функцию отправки сообщений в Joomla как раз из-за подобных ограничений. В частности, хостинг-провайдер мог поставить максимальный предел количества отправленных сообщений за час. Если это так, то вам остается немного подождать, чтобы отправить очередную партию электронных писем, либо приобрести пакет подороже, чтобы снять установленное ограничение.
Существуют и другие причины, из-за чего вылетает сообщение «сould not instantiate mail function» на сайте с движком Joomla. И вполне вероятно, что причины эти снова кроются в ограничениях вашего хостинга. Вам стоит заранее разведать допустимые параметры электронных сообщений для отправки, чтобы потом не возникало проблем. К примеру, некоторые хостинги априори отказывают отправлять сообщения, если в них закреплены какие-то файлы. Возможно, таким образом они пытаются избежать прецедентов спам-рассылок, а с другой стороны — не хотят отправлять слишком большие массивы информации, нагружая тем самым сервера. В любом случае вам нужно разведать обстановку в технической службе поддержки, а потом искать пути решения.
И последняя причина, по которой надпись «сould not instantiate mail function» не дает вам отправить электронные письма — это ошибки в поле «Тема» при отправке. Вы должны знать, какие лимиты длины «Темы» установлены на сервере. Превышение лимита — это однозначный отказ к отправке. Да и не стоит делать рассылку с громоздкими заголовками — это не эффективно. С другой стороны, вы могли использовать в пункте «Тема» какие-то запрещенные символы. В любом случае вам поможет поддержка!
If your Joomla server does not support the php mail() function and Joomla attempts to send an email (such as a new user registration email), any of the following message may appear:
- Could not instantiate mail function.
- The mail() function has been disabled and the mail cannot be sent.
- Registration failed: An error was encountered while sending the registration email. A message has been sent to the administrator of this site.
Not all servers support the php mail function, and if your Joomla hosting provider does not, you’re still in luck. To prevent the above error and to setup Joomla to be able to send email successfully, we have to adjust Joomla’s email settings. Besides the php mail function, Joomla 3.0 can use Sendmail or SMTP. In this tutorial, we are going to walk you through the steps for setting up SMTP with Joomla 3.0
Configuring Joomla 3.0 to send emails using SMTP:
- Configure your sending email account
When emailing using SMTP, we are also going to setup SMTP Authentication. What this means is that we are going to setup Joomla to log into the server using a username and password, and then send email as that user. SMTP Authentication is much like using Microsoft Outlook or Mozilla Thunderbird: you enter your email settings, a password, and then you can use that email account.
Creating email accounts is not the same on each hosting provider. If you use InMotion Hosting or use cPanel, click here to learn how to create an email address. Otherwise, you should contact your hosting provider for more help with setting up a new email account.
Be sure to keep track of the email account and password that you use. In our testing, we created [email protected].
- Log into your Joomla 3.0 admin dashboard
- In the left menu, click the Global Configuration link
- In the tabs at the top of the page, click the Server tab
- In the right column, find the Mail Settings. Update the settings as we describe below, and then click the Save button in the top left of the page.
Mailer Select SMTP From Email Enter the email address you created in step 1 above. In our testing, we entered [email protected] From Name Enter your name or the name of your website. In our testing, we entered Best Website Ever SendMail path Generally you can leave this setting alone SMTP Authentication Set SMTP Authentication to Yes SMTP Security If you want to send email, you may need to contact your hosting provider for the necessary settings. In our testing, set Security to SSL. SMTP Port As we are using SSL (see the setting above), we are setting the port to 465. Again, you may need to contact your joomla host for the correct settings. SMTP Username Enter the username of the email address you created in step 1. SMTP Password Enter the password of the email address you created in step 1. SMTP Host Most often, your STMP Host will be localhost. If you have any doubts, be sure you contact your joomla hosting provider for clarification. You can see in the screenshot below how the settings looked when we saved them in Joomla 3.0. We then signed up as a new user within our Joomla 3.0 website, and you can see how some of the SMTP settings we configured (such as From email and From Name) show up in our email client.
SMTP Settings Within Joomla 3.0 An email sent by Joomla with our new SMTP Settings
A common error but a difficult one to fix without help. Learn how to do it in this article.
This message means that your mail server (the mailing part of your host) failed to send an email.
This is the most common error message you will get if you have trouble sending e-mails using your server and unfortunately, this error message does not tell you how you can solve the issue.
You can find a detailed explanation as to why your mail server failed to send the email in its logs file. You can ask your host for it.
Based on our experience, your mail server can fail to send emails for these reasons:
You are on a local server (using WAMP for example)
You are on a local server (using WAMP for example)
This kind of web server does not have a mail server so you can’t send e-mails from your local server.
What’s the solution? Well, you should configure AcyMailing to use an external SMTP server instead of using the php Mail function to test Acy but you can consider it will work on your live server
Your receiver e-mail address is not valid
Your receiver e-mail address is not valid
Your mail server may refuse to deliver your message if the receiver e-mail address is not a valid one… So if you have this «could not instantiate mail function» for only a few of your subscribers, it may just be because their e-mail address is not valid!
You included a special character in the subject line
You included a special character in the subject line
Some mail servers will refuse to deliver your message if it contains special characters in the subject such as a quote or a comma or any other kind of special character (ùïä)…
Please create a new Newsletter, specify a standard subject line («test» for example) and give it a new try.
You included a special character in the sender/receiver information
You included a special character in the sender/receiver information
The same way, some mail server will refuse to deliver your message if the sender information contain special characters.
Please go on the AcyMailing configuration page, turn OFF the option «add Names» and give it a new try.
Your subject line is too long
Your subject line is too long
Some mail server may not authorize you to deliver your message if the subject line is too long…
Change your subject line to a single word to make sure it’s not a problem of subjet length.
The bounce address you specified is not accepted by your server
The bounce address you specified is not accepted by your server
Some servers won’t accept to deliver your message if you specify a bounce e-mail address.
Others will force you to apply a bounce address which belongs to your own domain…
Please go on the AcyMailing configuration page and leave the bounce address field empty.
You should specify a bounce e-mail address
You should specify a bounce e-mail address
Just like the previous point, some servers will only deliver messages if you specified a bounce e-mail address belonging to your own domain.
If removing the bounce e-mail address didn’t work, you should try to add it again and make sure it’s a valid e-mail address belonging to your own domain.
You already sent too many e-mails!
You already sent too many e-mails!
Most of hosting company will allow you send X e-mails per hour.
If you go over that limitation, the mail server will refuse to deliver more e-mails and will display this error message.
So for example if you successfully sent 480 e-mails and you can’t send e-mails any more, then it’s probably what happened and you should first wait one hour to deliver more e-mails and also make sure
AcyMailing is configured to stay below your sending limitations
.
You send multiple parts… and your host does not like it!
You send multiple parts… and your host does not like it!
Some hosts won’t enable you to send multiple parts…
That definitely a parameter we recommend you to keep enabled but you should try to turn it OFF to see if that solves the «could not instantiate mail function» issue.
You will find this option under the «Mail Configuration» tab on the AcyMailing configuration page.
Your host does not allow attachments
Your host does not allow attachments
Some hosts will not allow you to send a message with an attachment… so if you have this issue only on Newsletter with attachments, you could turn OFF the option «embed attachments» on the Acy configuration page to make sure Acy will add the file as a link in your message and not as a real attachment.
Still can’t make it work?
Still can’t make it work?
They provide with a really nice service and you will easily get rid of all those connexion issues.
If you’re receiving a Could not instantiate mail function error, this can be generated by a bunch of reasons — from improper RSMail! mailing configuration to server side mailer failure.
Troubleshooting steps:
- We will first have to identify what exactly is causing this — your RSMail! configuration, or your Joomla! installation. You can easily check this by creating a new Joomla! user. As you know, an automated email should be generated with the account details. If the same error is displayed (or the email hasn’t arrived to the newly user’s email address), then the issue is generated by one of two things:
- Mailer failure. If you are using PHP Mail (System > Global Configuration > Server), it would be best to contact the hosting provider. As an alternate solution, you could try switching the mailer type to an external service, such as SMTP. More details on the available configuration options can be found here (Joomla! 3.x) and here (Joomla! 2.5)
- Improper mail settings. In this case, you will have to make sure that you have specified a name and email, within the System > Global Configuration > Server area.
- If the Joomla! user related email worked fine, you should then check your RSMail! Mail Configuration and afterwards, email configuration. Mail Configuration can be accessed from backend > Components > RSMail! > Settings > Mail Configuration (these provide similar details as within your Global Configuration mailer setup).
Next, for all configured emails (backend > Components > RSMail! > Settings > Emails), you will need to check the following fields (where applicable):
- From — should contain a valid email address, or placeholder that is substituted with a valid email address.
- From name — should not be left empty.
- Subject — a value should be specified
Note:
Some email related errors can be generated if the RSMail! Emails From and From name fields do not match the ones provided within the System > Global Configuration > Server area.
One person found this article helpful.
Was this article helpful?
Yes
No
You Should Also Read











