Ошибка could not instantiate mail function

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!";
    }
?>

Stephen Ostermiller on Strike's user avatar

asked Aug 18, 2009 at 23:20

sdfor's user avatar

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 Chapagain's user avatar

Mukesh ChapagainMukesh Chapagain

24.9k15 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's user avatar

Andrew

18.3k12 gold badges102 silver badges117 bronze badges

answered Feb 6, 2018 at 13:22

Irwuin's user avatar

IrwuinIrwuin

5033 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ánepa's user avatar

Matías CánepaMatías Cánepa

5,6734 gold badges57 silver badges96 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

Avinash's user avatar

AvinashAvinash

6,01415 gold badges60 silver badges95 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.'s user avatar

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 A's user avatar

Salman ASalman A

260k82 gold badges429 silver badges521 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 Pope's user avatar

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

fiskcn's user avatar

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

Alex's user avatar

AlexAlex

1,2971 gold badge16 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

levi's user avatar

levilevi

1,5363 gold badges20 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

Atif.SQL's user avatar

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

iAndy's user avatar

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

jmarceli's user avatar

jmarcelijmarceli

18.9k6 gold badges69 silver badges67 bronze badges

Check if sendmail is enabled, mostly if your server is provided by another company.

answered Oct 5, 2017 at 13:43

Gianluca Demarinis's user avatar

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

MomasVII's user avatar

MomasVIIMomasVII

4,5014 gold badges33 silver badges48 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

KJS's user avatar

KJSKJS

1,1761 gold badge13 silver badges29 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.
iis config image

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.

Stephen Ostermiller on Strike's user avatar

answered Sep 8, 2020 at 14:39

michal's user avatar

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

user3595601's user avatar

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»;

В этой статье мы рассмотрим проблемы, возникающие с отправкой почты на 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 (Сервер) и в правом нижнем углу найти настройки отправления почты.

options

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, как это сделать читайте здесь.

Joomla не отправляются письма

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. Проблемы с хостингом.

Возможно вы используете бесплатный тариф, на котором закрыта отправка писем или он включает этот функционал по требования. Как бы то ни было, вам нужно написать в службу поддержки и объяснить проблему.

  • Knowledge Base
  • Troubleshooting

Error “Could not instantiate mail function” When Sending Emails

If you are getting the error “Could not instantiate mail function” when trying to use the Send Email action, your server may be misconfigured for sending emails.

This is not a WS Form bug.

By default, WS Form sends emails to:

  • #blog_admin_email – The ‘Administration Email Address’ found in WordPress Settings > General
  • #blog_name – The ‘Site Title’ found in WordPress Settings > General

You can change these settings.

This article describes possible solutions to this problem:

Using a Local Web Server (e.g. WAMP)

Local web servers typically do not have a mail server running. This will prevent emails from being sent.

You should use an external SMTP server in conjunction with an SMTP plugin.

An Email Address is Invalid

Ensure your ‘Send Email’ settings are correct and that your From and To email addresses are valid.

Sending emails From and To the same email address may, on occasion, cause issues.

Learn More

Your SMTP Plugin Cannot Accept Display Names

WS Form supports display names for email addresses (per RFC 2822). The WordPress wp_mail function also supports this format.

An example of this email address format is: joe.bloggs@emailtmp.com <Joe Bloggs>

We have found that some SMTP plugins have a bug that causes email addresses in this format to break the sending of emails.

Known plugins with this issue:

  • FluentSMTP
  • SendInBlue (Fixed in version 3.1.38)

We would suggest trying to remove the Display Name setting and then try to send the email again to confirm if this is the case with your SMTP plugin.

WS Form - Send Email - Clear Display Name

Invalid Subject Line

Avoid punctuation and special characters in your email subject line. Some mail servers will reject emails that contain certain characters. Keeping your subject line to alpha-numeric characters will increase your chance of deliverability.

Also ensure your subject line is not too long. We recommend keeping subject lines between 10 and 60 characters long.

Exceeding Quotas

Some SMTP providers impose quotas on how many emails you can send. If that quota is exceeded you will no longer be able to send emails. Login to your SMTP provider account to check your send count, quotas and frequency caps.

More Information

  • Email Notifications Not Working
  • Email Settings
  • Send Email Action
  • Emails sent from my site by WordPress intermittently fail. The error message shown by WP Mail Logging plugin is “Could not instantiate mail function”. The emails fail both from our Contact Us page, and from comments added to WordPress Posts. It is intermittent, so it sometimes works.

    I (may) have narrowed the focus to the /usr/sbin/sendmail bash script, which is 38 lines long! (Not 100% sure that is what my system uses though.)

    Is there a level of logging or error reporting that I can enable to understand better why this is happening? (Already tried enabling “display errors” and “error_reporting” in cPanel “PHP Selector”, but that seemed to have no effect.)

    The page I need help with: [log in to see the link]

  • Like this post? Please share to your friends:
  • Ошибка could not initialize direct3d
  • Ошибка could not init 3d system
  • Ошибка could not get temp directory
  • Ошибка could not find zone
  • Ошибка could not find steam api dll