Ошибки при отправке mail php

Почему не отправляется письмо? (php)

Всех приветствую! В PHP не силен. Нужно сделать так, чтобы скрипт отправлял письмо на email.

Есть файл index.html и в нем форма отправки выглядит так:

И есть отдельный файл mail.php

Мне надо чтобы после того, как человек оставил заявку мне оно ушло на почту

lesha_firs

А ты случайно не локально тестируешь? ну opneServer или Денвер ? если да то ищи письма в папки !send или tmp !

Чтобы функция mail(); работала, у вас как минимум должен быть установлен SMTP служба на сервере, а также настроена обратная зона. Если для вас это сложно, то попробуйте такой вариант:

1. Качайте: swiftmailer.org/download
2. Напишите такой скрипт, который будет отправлять почту через ваш GMAIL аккаунт

setSubject($title) ->setFrom(array($from)) ->setTo(array($to)) ->setBody($mess); // настраиваем подключение к gmail $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl') ->setUsername('username@gmail.com') ->setPassword('password'); // отправляем $mailer = Swift_Mailer::newInstance($transport); $mailer->send($message);

@dos охх как сложно все 🙁 Мне надо то всего лишь, чтобы когда человек оставил заявку на сайте она приходила ко мне на почту

Ок, но чтобы письмо отправилось и не попало в спам-фильтр вашего почтового сервера, на вашем сервере, где расположен сайт, должна быть настроена smtp-служба и прописана обратная зона вашего домена. Если вы это не делали, значит стандартная функция mail(); работать не будет.

Ещё проще письмо можно отправить через PHPMailer.
Да, лучше использовать авторизацию, чтобы письмо с большей вероятностью не попадало в спам.

alekciy

Авторизацию нужно использовать не для того, что бы оно не попало в спам, а для того, что бы быть уверенным, что оно вообще куда-то попало. А для «не попало в спам» нужны SPF и PTR (при обеспечении коих можно и прямо с сервера фигачить письма без авторизации и не попасть в спам).

TARAKANhoy

Телефон: ".$phone."
Текст: ".$text."
"; //содержание сообщение $emailto = "emailto@mail.ru"; //e-mail кому $emailfrom = "emailfrom@mail.ru"; //e-mail от кого $chek = mail($emailto, $subject, $message, "Content-type:text/html; Charset=utf-8\r\nFrom:".$emailfrom."\r\n"); //отправляем сообщение if($chek) echo "Ваше письмо успешно отправлено!"; else echo "Ваше письмо не отправлено!"; > else < echo "Вы заполнили не все поля!"; >?>

p.s. проблема неработоспособности твоего кода была в том что ты не передавал значение submit и проверка if($_POST[‘submit’]) не проходила. Мой вариант отправки письма лучше, но и его можно дорабатывать под особые случаи, но в 90% случая будет работать как надо. Сам я использую именно такой.

Источник

PHP Mail Not Working Not Sending (How To Fix It!)

After spending some time setting up your web server and writing up the scripts, the PHP mail function is not sending emails out as expected. Tutorials from all over the Internet show different solutions, and just what the heck is happening!? How do we fix it?

PHP mail requires a mail delivery server (SMTP) to send out emails, and there are 2 possible solutions:

  1. Install a local SMTP server.
    • Windows – Use Papercut for local testing.
    • Linux – Use sendmail or postfix, sudo apt-get install postfix .
  2. Use a remote SMTP server, simply point the SMTP settings in the php.ini file to the mail server.

That is the gist of it, but let us go through the actual steps on fixing the mail problem – Read on!

TLDR – QUICK SLIDES

Fix Mail Not Working Not Sending In PHP

TABLE OF CONTENTS

INSTALLING A LOCAL SMTP SERVER

All right, let us get started with the first solution – Installing a mail server on your own machine.

WINDOWS USERS – PAPERCUT SMTP FOR LOCAL TESTING

For Windows users, try out Papercut SMTP. Papercut is probably the fastest and fuss-free SMTP server for testing. While it can be configured to relay email out, I don’t really recommend using this for a production server.

LINUX USERS – POSTFIX OR SENDMAIL

For you guys who are on Linux, simply install Sendmail or Postfix –

sudo apt-get install postfix

But different flavors of Linux has a different package manager – YUM or RPM , just use whichever is correct.

UPDATE THE PHP.INI FILE

[mail function] SMTP=localhost smtp_port=25 ; For Win32 only. sendmail_from = doge@codeboxx.com

Finally in the php.ini file, simply ensure that SMTP is pointing to localhost . Also for the Windows users, set sendmail_from or you will get a “bad message return path” error message.

OTHER MAIL SERVERS – FOR PRODUCTION SERVERS

USING A REMOTE SMTP SERVER

Don’t want to install anything? Then use an existing SMTP server that you have access to.

POINT PHP.INI TO THE SMTP SERVER

To use an existing SMTP server, just update the php.ini file and point to the SMTP server accordingly. For example, we can actually point to the Gmail SMTP server:

[mail function] SMTP=smtp.gmail.com smtp_port=587 auth_username=YOUR-ID@gmail.com auth_password=YOUR-PASSWORD

That’s it, but I will not recommend using your personal Gmail, Yahoo, or Outlook accounts on production servers… At least use one of their business accounts.

EXTRA – GMAIL AUTHENTICATION

Is Google rejecting the SMTP requests? Authentication failure? That is because Google will simply not allow any Tom, Dick, and Harry to access your email account. Thankfully, we only need to do some security setting stuff to get past this issue.

ENABLE 2-STEP AUTHENTICATION

Firstly, enable the 2-step authentication on your Google account if you have not already done so. That is basically, sending a PIN code to your mobile phone when Google detects login from an unknown device.

CREATE AN APP PASSWORD

But of course, we are not going to answer a PIN code challenge whenever we try to send an email from the server… So what we are going to do instead, is to create an app password.

Select “Other (Custom Name)” under the drop-down menu.

You can name it whatever you want…

DONE!

Finally, just copy that email/password into php.ini .

EXTRA BITS

That’s all for the tutorial, and here is a small section on some extras that may be useful to you.

PHP MAIL DEBUGGING

  1. In your PHP script, check the error message after sending out the email – if (!mail(TO, SUBJECT, MESSAGE)) < print_r(error_get_last()); >
  2. Set mail.log = FOLDER/mail.log in php.ini .
  3. Also, set a mail log on the SMTP server itself.

That’s all. Do a test mail send and trace the log files – Did PHP send out the email? Did the SMTP server send out the email? Are the configurations correct? Lastly, also very important – Did you send it to the correct email address, is it even a valid email?

TONE DOWN FIREWALLS, ANTI-VIRUS, CHECK SPAM FOLDER

  • Windows – Check and allow an exception in the Windows firewall.
  • Linux – Allow an exception in iptables .
  • Elsewhere – Maybe a hardware firewall that is somewhere in the network, or an anti-virus stopping the SMTP send.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped to solve your email problems, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

Источник

Почему возникает ошибка при отправке формы на почту?

Пытаюсь настроить отправку формы на почту при сабмите. С php сталкиваюсь впервые, как и с fetch, но вот что получается: (использую библиотеку bouncer.js):

form.addEventListener('bouncerFormValid', formSend); async function formSend(e) < let formData = new FormData(form); let response = await fetch('mail.php', < method: ('POST'), body: FormData, >); if (response.ok) < let result = await response.json(); alert(result.message); form.reset(); >else < alert('Упс, что-то пошло не так'); >>;
CharSet = 'UTF-8'; $mail->setLanguage('ru', 'phpmailer/language/'); $mail->IsHTML(true); $mail->setFrom('info@chipdip33.ru', 'Чип и Дип'); $mail->addAdress('milan7457@yandex.ru'); $mail->Subject = 'Привет'; $body = '

Тело письма

'; if(trim(!empty($_POST['name'])))< $body.='

Имя '.$_POST['name'].'

'; > if(trim(!empty($_POST['tel'])))< $body.='

Имя '.$_POST['tel'].'

'; > if(!$mail->send()) < $message = 'Ошибка'; >else < $message = 'Данные отправлены'; >$response = ['message' => $message]; header('Content-type: application.json'); echo json_encode($response); ?>

5fe9bef8093c9137519422.jpeg
5fe9c7cf8bbf6317549065.jpeg

файл mail.php находится на одном уровне с index.html. В качестве отправителя письма указана доменная почта сайта. Сайт лежит на хостинге без всяких cms. Никакой настройки почты на хостинге я не делал , только создал, да и без понятия нужна ли какая настройка. все делаю впервые. Буду рад любой помощи, спасибо.

UPD 1. Добавил логи из девтулз в спойлер с ошибкой.
UPD 2. Логи сервера с ошибкой

[Mon Dec 28 23:07:21 2020] [php7:error] [pid 168688] [client 95.106.199.138:0] PHP Fatal error: Uncaught PHPMailer\\PHPMailer\\Exception: \xd0\x9f\xd1\x83\xd1\x81\xd1\x82\xd0\xbe\xd0\xb5 \xd1\x81\xd0\xbe\xd0\xbe\xd0\xb1\xd1\x89\xd0\xb5\xd0\xbd\xd0\xb8\xd0\xb5 in /home/m/milan7457y/public_html/resources/phpmailer/src/PHPMailer.php:1535\nStack trace:\n#0 /home/m/milan7457y/public_html/resources/phpmailer/src/PHPMailer.php(1438): PHPMailer\\PHPMailer\\PHPMailer->preSend()\n#1 /home/m/milan7457y/public_html/mail.php(26): PHPMailer\\PHPMailer\\PHPMailer->send()\n#2 \n thrown in /home/m/milan7457y/public_html/resources/phpmailer/src/PHPMailer.php on line 1535, referer: https://chipdip33.ru/

Простой 15 комментариев

Источник

Читайте также:  Php ubuntu apache2 настройка
Оцените статью