Ошибка сервера номер 500 phpmailer

I’m trying to send an email using the following code and I’m getting Internal Server Error. I am not sure why I am having this trouble.

PHP code:

<?php
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465; 
    $mail->Username = 'myemail@gmail.com';  
    $mail->Password = "mypasswordhere";           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress('myemail@gmail.com');
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }
?>

I just placed this file as test.php inside the PhpMail folder after extracting it. Like the below

enter image description here

Пытаюсь отправить письмо через smtp Яндекса. При отправке формы получаю ошибку «send.php Status Code: 500 Internal Server Error»

Что сделал:
1. Изменил MX-запись. В настройках домена в сервисе connect.yandex.ru написано «Домен подтверждён и готов к работе»
2. Залил PHPMailer на хостинг. Три файла в папку /PHPMailer/PHPMailer/ (Exception.php, PHPMailer.php, SMTP.php) и send.php с моими настройками в корень сайта.

Кусочек send.php:

$mail->Host       = 'smtp.yandex.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'mail@mydomain.ru';                     // SMTP username
    $mail->Password   = 'password';                               // SMTP password
    $mail->SMTPSecure = 'ssl';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 465;

В строчке «$mail->Password» использую пароль для приложения, который выдается в настройках почты в Яндексе.

Что может быть не так?

Я продолжаю иметь внутреннюю ошибку 500 на моем веб-сервере, размещенном на GoDaddy с использованием PHPmailer; Я попробовал несколько решений, доступных на StackOverflow, касающихся моей задачи, но ни одно из них не сработало.

Вот мой код:

require 'phpmailer/PHPMailerAutoload.php';
$feedback='';
$flag = array();
if(isset($_POST["submitlogin"]) and $_SERVER['REQUEST_METHOD'] == "POST"){

$name = seo_friendly_url($_POST['name']);
$email = seo_friendly_url($_POST['email']);
$subject = seo_friendly_url($_POST['subject']);
$message = seo_friendly_url($_POST['message']);

//Email

if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email)) {
$feedback="Invalid email format";
array_push($flag,"false");
}else {
array_push($flag,"true");
}
//Email

//Name
if (preg_match('/^[-a-zA-Z0-9._]+$/', $name)){
array_push($flag,"true");
}else {
$feedback="Invalid name format";
array_push($flag,"false");
}
//Nameif (!in_array("false", $flag)) {

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "smtpout.asia.secureserver.net";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
//$mail->Username = 'email@email.com';
//$mail->Password = 'password';
$mail->SMTPAuth = false;
//Set who the message is to be sent from
$mail->setFrom('email@email.com');
//Set an alternative reply-to address
$mail->addReplyTo($email);
//Set who the message is to be sent to
$mail->addAddress('email@email.com');     // Add a recipient
$mail->addAddress('email@email.com');
$mail->addAddress('email@email.com);
//Set the subject line
$mail->Subject = 'HLS Inquiry';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($message);$email_ar = $email;
$subject_ar = $name.", Thank you for your Inquiry";
$acknowledgement_receipt = '
<div style="padding:10px 20px;font-size:16px;">

<p>Dear '.$name.',</p>

<p>We've received your message and would like to thank you for contacting us. We will reply by email shortly.</p>

<p>Talk to you soon,</p>

<p>
<div>Customer Service</div>

</p>

</div>
';if ($mail->send()) {
$feedback = "<span style='color:green;'>Thank you for your inquiry. We will respond to you within 24 hours.</span>";
}

}

Обратите внимание, что я заменил некоторые из значений электронной почты как: email@email.com для моей конфиденциальности.

Я считал, что настройки электронной почты верны, потому что я уже использовал эти настройки с сайта моего друга, размещенного на JustHost.

0

Решение

В этой строке отсутствует ни одна кавычка:

$mail->addAddress('email@email.com);

Это довольно очевидно в SO, потому что вы можете видеть, как подсветка синтаксиса ломается в этой точке.

Когда вы получаете ошибку 500 и ничего не отображается, это признак того, что вы должны искать в журнале ошибок вашего веб-сервера.

0

Другие решения

Других решений пока нет …

yes I have commented that line and the error still exist, composer validate gives the following output:

./composer.json is valid for simple usage with composer but has
strict errors that make it unable to be published as a package:
See https://getcomposer.org/doc/04-schema.md for details on the schema
name : The property name is required
description : The property description is required

here is the apache error log:
[Tue Sep 21 06:43:03.126210 2021] [php7:warn] [pid 26269] [client IP:PORT] PHP Warning: Use of undefined constant xe2x80x98FS_METHODxe2x80x99 — assumed ‘xe2x80x98FS$

and this is my composer.lock code:
{ "_readme": [ "This file locks the dependencies of your project to a known state", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], "content-hash": "90bbf95869b4e88bf0dc5022e708a458", "packages": [ { "name": "phpmailer/phpmailer", "version": "v6.5.1", "source": { "type": "git", "url": "https://github.com/PHPMailer/PHPMailer.git", "reference": "dd803df5ad7492e1b40637f7ebd258fee5ca7355" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/dd803df5ad7492e1b40637f7ebd258fee5ca7355", "reference": "dd803df5ad7492e1b40637f7ebd258fee5ca7355", "shasum": "" }, "require": { "ext-ctype": "*", "ext-filter": "*", "ext-hash": "*", "php": ">=5.5.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", "doctrine/annotations": "^1.2", "php-parallel-lint/php-console-highlighter": "^0.5.0", "php-parallel-lint/php-parallel-lint": "^1.3", "phpcompatibility/php-compatibility": "^9.3.5", "roave/security-advisories": "dev-latest", "squizlabs/php_codesniffer": "^3.6.0", "yoast/phpunit-polyfills": "^1.0.0" }, "suggest": { "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", "league/oauth2-google": "Needed for Google XOAUTH2 authentication", "psr/log": "For optional PSR-3 debug logging", "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" }, "type": "library", "autoload": { "psr-4": { "PHPMailer\PHPMailer\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-2.1-only" ], "authors": [ { "name": "Marcus Bointon", "email": "phpmailer@synchromedia.co.uk" }, { "name": "Jim Jagielski", "email": "jimjag@gmail.com" }, { "name": "Andy Prevost", "email": "codeworxtech@users.sourceforge.net" }, { "name": "Brent R. Matzelle" } ], "description": "PHPMailer is a full-featured email creation and transfer class for PHP", "support": { "issues": "https://github.com/PHPMailer/PHPMailer/issues", "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.5.1" }, "funding": [ { "url": "https://github.com/Synchro", "type": "github" } ], "time": "2021-08-18T09:14:16+00:00" } ], "packages-dev": [], "aliases": [], "minimum-stability": "stable", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, "platform": [], "platform-dev": [], "plugin-api-version": "2.1.0" }

Solution 1

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   = "[email protected]";  // GMAIL username
    $mail->Password   = "yourpassword";            // GMAIL password

    $mail->SetFrom('nam[email protected]', 'First Last');

    $mail->AddReplyTo("[email protected]","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 = "[email protected]";
    $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('[email protected]***.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 localphpextphp_openssl.dll

Directory of C:localphpext

php_openssl.dll

2. Create the PHP configuration file, localphpphp.ini, if it does not exist:

C:user>copy localphpphp.ini-production localphpphp.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.

Solution 2

I have tried with you code, and i have only changed this line :

require_once ("inclPHPMailerPHPMailerAutoload.php");

by this one :

require_once ("inclPHPMailerclass.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

Solution 3

This problem is slashes ( )

Edit

require_once ("incl\PHPMailer\PHPMailerAutoload.php");

Solution 4

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.

Solution 5

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:inetpublogsLogFiles or C:WindowsSystem32LogFiles 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)

Comments

  • 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 ("inclPHPMailerPHPMailerAutoload.php");
    
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "tls";
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 587;
    $mail->Username = "[email protected]";
    $mail->Password = "mypassword";
    $mail->SetFrom('[email protected]','Me');
    $mail->AddAddress("[email protected]");
    $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 System32LogFileshttperr1.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:inetpubwwwrootinclPHPMailerclass.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:PHPphp.ini on line 101

    That line is:

    php_flag display_errors on

Recents

  • Ошибка сервера недопустимый получатель outlook
  • Ошибка сервера не удалось загрузить результаты экзаменов
  • Ошибка сервера не закончена сессия на другом сервере world of tanks
  • Ошибка сервиса dhcp 17 800
  • Ошибка сервиса 400 на ютуб на телефоне