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
Я продолжаю иметь внутреннюю ошибку 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
Другие решения
Других решений пока нет …
Пытаюсь отправить письмо через 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» использую пароль для приложения, который выдается в настройках почты в Яндексе.
Что может быть не так?
Issue
I am trying to email a form data with phpmailer. I am stuck with it.
for some reason I am getting Failed to load resource: the server responded with a status of 500 (Internal Server Error).
I have 2 pages. the index.php and sendit.php.
the index.php has a bootstrap modal box (the form data to be send to the user email).
the user fill in the form, click on save. the data will save into the database, and call the sendMail function to perform the sending operation.
The sendMail function make a ajax call to the sendit.php and send the data
When I hard code the data in the data array in the sendit.php, it will work. when I change it to $_POST[‘name’], don’t work.
Need HELP
Thanks in advance.
the code:
this is the index.php snippet code
$('#btnSave').on('click', function() {
// some code
// the ajax call
$.ajax({
type: "POST",
url: 'addEvent.php',
data: thedata,
success: function(d) {
if (d == 'sucess') {
// data to send to client email
data = {
"name": $('#inpName').val(),
}
sendMail(data); // call the function sendMail.
resetForm(); // reset the form
} else if (d === 'false') {
//show some message
},
error: function(error) {
alert(error);
}
});
}
// the sendMail function
function sendMail(theData)
{
$.ajax({
type: "POST",
url: "sendit.php",
data: theData
})
}
Here is the snippet code for the sendit.php
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require '../sendmail/mailer/autoload.php';
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = '[email protected]'; //SMTP username
$mail->Password = 'thepassword'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('client email adres', 'client name');
$data=[
lastName=>$_POST('name'),
];
// the message body
$body='
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Afspraak kaart</title>
</head>
<body>
<div class="afspraak-container">
<h2 class="afspraal-head">
Afspraak kaart
</h2>
<hr>
<div class="afspraak-body">
<p>Mr/Mevr '.$data[lastName].'</p>
<p>Bedankt voor uw afspraak bij het Kadaster en Openbare Registers.
</p>
<p>
Uw afspraak gegevens:
</p>
<div class="afspraak-card">
<div class="afspraak-card-head">
24 mei 2021,10:20 AM
</div>
<ul>
<li>Afspraak volgnr: 101</li>
<li>Naam: Joel Goncalves de Freitas</li>
<li>Product: Meetbrief</li>
</ul>
</div>
</div>
<footer>
</footer>
</div>
</body>
</html>';
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'test';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Solution
A 500 Error means that you have a server error on that file.
The PHP code is formally correct – at least if you’re running a recent enough PHP – but on second thought, this is wrong:
$_POST('name')
The code will try to call the $_POST function, and crash. It should be $_POST['name']
.
Answered By – LSerni
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.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 \xe2\x80\x98FS_METHOD\xe2\x80\x99 — assumed ‘\xe2\x80\x98FS$
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" }