Перейти к публикации
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

[Решено] Проблемы с обратной связью


 Погделиться

Рекомендованные сообещёния

При отправке письма через обратную связь выводится на экран вот икая ошибка.
А вот полный код данного файла. Возможно кто-то знает как это исправить.
 

<?php
class Mail {
	protected $to;
	protected $from;
	protected $sender;
	protected $reply_to;
	protected $subject;
	protected $text;
	protected $html;
	protected $attachments = array();
	public $protocol = 'mail';
	public $smtp_hostname;
	public $smtp_username;
	public $smtp_password;
	public $smtp_port = 25;
	public $smtp_timeout = 5;
	public $verp = false;
	public $parameter = '';

	public function __construct($config = array()) {
		foreach ($config as $key => $value) {
			$this->$key = $value;
		}
	}

	public function setTo($to) {
		$this->to = $to;
	}

	public function setFrom($from) {
		$this->from = $from;
	}

	public function setSender($sender) {
		$this->sender = $sender;
	}

	public function setReplyTo($reply_to) {
		$this->reply_to = $reply_to;
	}

	public function setSubject($subject) {
		$this->subject = $subject;
	}

	public function setText($text) {
		$this->text = $text;
	}

	public function setHtml($html) {
		$this->html = $html;
	}

	public function addAttachment($filename) {
		$this->attachments[] = $filename;
	}

	public function send() {
		if (!$this->to) {
			throw new \Exception('Error: E-Mail to required!');
		}

		if (!$this->from) {
			throw new \Exception('Error: E-Mail from required!');
		}

		if (!$this->sender) {
			throw new \Exception('Error: E-Mail sender required!');
		}

		if (!$this->subject) {
			throw new \Exception('Error: E-Mail subject required!');
		}

		if ((!$this->text) && (!$this->html)) {
			throw new \Exception('Error: E-Mail message required!');
		}

		if (is_array($this->to)) {
			$to = implode(',', $this->to);
		} else {
			$to = $this->to;
		}

		$boundary = '----=_NextPart_' . md5(time());

		$header = 'MIME-Version: 1.0' . PHP_EOL;

		if ($this->protocol != 'mail') {
			$header .= 'To: <' . $to . '>' . PHP_EOL;
			$header .= 'Subject: =?UTF-8?B?' . base64_encode($this->subject) . '?=' . PHP_EOL;
		}

		$header .= 'Date: ' . date('D, d M Y H:i:s O') . PHP_EOL;
		$header .= 'From: =?UTF-8?B?' . base64_encode($this->sender) . '?= <' . $this->from . '>' . PHP_EOL;
		
		if (!$this->reply_to) {
			$header .= 'Reply-To: =?UTF-8?B?' . base64_encode($this->sender) . '?= <' . $this->from . '>' . PHP_EOL;
		} else {
			$header .= 'Reply-To: =?UTF-8?B?' . base64_encode($this->reply_to) . '?= <' . $this->reply_to . '>' . PHP_EOL;
		}
		
		$header .= 'Return-Path: ' . $this->from . PHP_EOL;
		$header .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
		$header .= 'Content-Type: multipart/mixed; boundary="' . $boundary . '"' . PHP_EOL . PHP_EOL;

		if (!$this->html) {
			$message  = '--' . $boundary . PHP_EOL;
			$message .= 'Content-Type: text/plain; charset="utf-8"' . PHP_EOL;
			$message .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL;
			$message .= $this->text . PHP_EOL;
		} else {
			$message  = '--' . $boundary . PHP_EOL;
			$message .= 'Content-Type: multipart/alternative; boundary="' . $boundary . '_alt"' . PHP_EOL . PHP_EOL;
			$message .= '--' . $boundary . '_alt' . PHP_EOL;
			$message .= 'Content-Type: text/plain; charset="utf-8"' . PHP_EOL;
			$message .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL;

			if ($this->text) {
				$message .= $this->text . PHP_EOL;
			} else {
				$message .= 'This is a HTML email and your email client software does not support HTML email!' . PHP_EOL;
			}

			$message .= '--' . $boundary . '_alt' . PHP_EOL;
			$message .= 'Content-Type: text/html; charset="utf-8"' . PHP_EOL;
			$message .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL;
			$message .= $this->html . PHP_EOL;
			$message .= '--' . $boundary . '_alt--' . PHP_EOL;
		}

		foreach ($this->attachments as $attachment) {
			if (file_exists($attachment)) {
				$handle = fopen($attachment, 'r');

				$content = fread($handle, filesize($attachment));

				fclose($handle);

				$message .= '--' . $boundary . PHP_EOL;
				$message .= 'Content-Type: application/octet-stream; name="' . basename($attachment) . '"' . PHP_EOL;
				$message .= 'Content-Transfer-Encoding: base64' . PHP_EOL;
				$message .= 'Content-Disposition: attachment; filename="' . basename($attachment) . '"' . PHP_EOL;
				$message .= 'Content-ID: <' . urlencode(basename($attachment)) . '>' . PHP_EOL;
				$message .= 'X-Attachment-Id: ' . urlencode(basename($attachment)) . PHP_EOL . PHP_EOL;
				$message .= chunk_split(base64_encode($content));
			}
		}

		$message .= '--' . $boundary . '--' . PHP_EOL;

		if ($this->protocol == 'mail') {
			ini_set('sendmail_from', $this->from);

			if ($this->parameter) {
				mail($to, '=?UTF-8?B?' . base64_encode($this->subject) . '?=', $message, $header, $this->parameter);
			} else {
				mail($to, '=?UTF-8?B?' . base64_encode($this->subject) . '?=', $message, $header);
			}
		} elseif ($this->protocol == 'smtp') {
			if (substr($this->smtp_hostname, 0, 3) == 'tls') {
				$hostname = substr($this->smtp_hostname, 6);
			} else {
				$hostname = $this->smtp_hostname;
			}

			$handle = fsockopen($hostname, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);

			if (!$handle) {
				throw new \Exception('Error: ' . $errstr . ' (' . $errno . ')');
			} else {
				if (substr(PHP_OS, 0, 3) != 'WIN') {
					socket_set_timeout($handle, $this->smtp_timeout, 0);
				}
	
		
				while ($line = fgets($handle, 515)) {
					if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				fputs($handle, 'EHLO ' . getenv('SERVER_NAME') . "\r\n");

				$reply = '';

				while ($line = fgets($handle, 515)) {
					$reply .= $line;

					//some SMTP servers respond with 220 code before responding with 250. hence, we need to ignore 220 response string
					if (substr($reply, 0, 3) == 220 && substr($line, 3, 1) == ' ') {
						$reply = '';
						continue;
					}
					else if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				if (substr($reply, 0, 3) != 250) {
					throw new \Exception('Error: EHLO not accepted from server!');
				}

				if (substr($this->smtp_hostname, 0, 3) == 'tls') {
					fputs($handle, 'STARTTLS' . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 220) {
						throw new \Exception('Error: STARTTLS not accepted from server!');
					}

					stream_socket_enable_crypto($handle, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
				}

				if (!empty($this->smtp_username)  && !empty($this->smtp_password)) {
					fputs($handle, 'EHLO ' . getenv('SERVER_NAME') . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 250) {
						throw new \Exception('Error: EHLO not accepted from server!');
					}

					fputs($handle, 'AUTH LOGIN' . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 334) {
						throw new \Exception('Error: AUTH LOGIN not accepted from server!');
					}

					fputs($handle, base64_encode($this->smtp_username) . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 334) {
						throw new \Exception('Error: Username not accepted from server!');
					}

					fputs($handle, base64_encode($this->smtp_password) . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 235) {
						throw new \Exception('Error: Password not accepted from server!');
					}
				} else {
					fputs($handle, 'HELO ' . getenv('SERVER_NAME') . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if (substr($reply, 0, 3) != 250) {
						throw new \Exception('Error: HELO not accepted from server!');
					}
				}

				if ($this->verp) {
					fputs($handle, 'MAIL FROM: <' . $this->from . '>XVERP' . "\r\n");
				} else {
					fputs($handle, 'MAIL FROM: <' . $this->from . '>' . "\r\n");
				}

				$reply = '';

				while ($line = fgets($handle, 515)) {
					$reply .= $line;

					if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				if (substr($reply, 0, 3) != 250) {
					throw new \Exception('Error: MAIL FROM not accepted from server!');
				}

				if (!is_array($this->to)) {
					fputs($handle, 'RCPT TO: <' . $this->to . '>' . "\r\n");

					$reply = '';

					while ($line = fgets($handle, 515)) {
						$reply .= $line;

						if (substr($line, 3, 1) == ' ') {
							break;
						}
					}

					if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
						throw new \Exception('Error: RCPT TO not accepted from server!');
					}
				} else {
					foreach ($this->to as $recipient) {
						fputs($handle, 'RCPT TO: <' . $recipient . '>' . "\r\n");

						$reply = '';

						while ($line = fgets($handle, 515)) {
							$reply .= $line;

							if (substr($line, 3, 1) == ' ') {
								break;
							}
						}

						if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
							throw new \Exception('Error: RCPT TO not accepted from server!');
						}
					}
				}

				fputs($handle, 'DATA' . "\r\n");

				$reply = '';

				while ($line = fgets($handle, 515)) {
					$reply .= $line;

					if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				if (substr($reply, 0, 3) != 354) {
					throw new \Exception('Error: DATA not accepted from server!');
				}

				// According to rfc 821 we should not send more than 1000 including the CRLF
				$message = str_replace("\r\n", "\n", $header . $message);
				$message = str_replace("\r", "\n", $message);

				$lines = explode("\n", $message);

				foreach ($lines as $line) {
					$results = str_split($line, 998);

					foreach ($results as $result) {
						if (substr(PHP_OS, 0, 3) != 'WIN') {
							fputs($handle, $result . "\r\n");
						} else {
							fputs($handle, str_replace("\n", "\r\n", $result) . "\r\n");
						}
					}
				}

				fputs($handle, '.' . "\r\n");

				$reply = '';

				while ($line = fgets($handle, 515)) {
					$reply .= $line;

					if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				if (substr($reply, 0, 3) != 250) {
					throw new \Exception('Error: DATA not accepted from server!');
				}

				fputs($handle, 'QUIT' . "\r\n");

				$reply = '';

				while ($line = fgets($handle, 515)) {
					$reply .= $line;

					if (substr($line, 3, 1) == ' ') {
						break;
					}
				}

				if (substr($reply, 0, 3) != 221) {
					throw new \Exception('Error: QUIT not accepted from server!');
				}

				fclose($handle);
			}
		}
	}
}

А вот листо тот кусок на который ссылается ошибка. 

if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
						throw new \Exception('Error: RCPT TO not accepted from server!');

 

Ссылка на комменирий
Погделиться на других сайих


Система-Настройки вкладка поли...Видимо стоит криво настроенный SMTP.

  • +1 1
Ссылка на комменирий
Погделиться на других сайих

Tom, Сообещёния о покупках и прочем приходят хорошо и мне на почту магазина и на почту покупателя.

 

Ссылка на комменирий
Погделиться на других сайих


Да что им в настройках? SMTP ?Если да то как вариант попробуйте в файл \catalog\controller\information\contact.php

найти

$mail->setFrom($this->request->post['email']);

и заменить на

$mail->setFrom($this->config->get('config_email'));

 

  • +1 1
Ссылка на комменирий
Погделиться на других сайих

  • 4 года спустя...
В 18.07.2017 в 05:05, Tom сказал:

Да что им в настройках? SMTP ?Если да то как вариант попробуйте в файл \catalog\controller\information\contact.php

найти

$mail->setFrom($this->request->post['email']);

и заменить на

$mail->setFrom($this->config->get('config_email'));

 

Прости, Дюдя, что беспокою тебя спустя столько времени после решения вопроса, но это единственный пост на весь интернет с похожей ошибкой.

У меня тоже настроено на SMTP. Суть в том, что обратная связь как-раз рилииет без проблем, но если пользователь указывает несуещёствующий адрес почты при оформлении заказа, то админ не получает уведомление о заказе (сам заказ создаётся и в админке вигден). А если несуещёствующую почту указать при регистрации, то вылезает ошибка (учётная запись при этом в админке создаётся):

 

Fatal error: Uncaught Exception: Error: RCPT TO not accepted from server! in .../system/library/mail.php:340 Stack trace: #0 .../catalog/model/account/customer.php(56): Mail->send() #1 .../system/storage/modification/system/engine/loader.php(178): ModelAccountCustomer->addCustomer(Array) #2 .../system/engine/proxy.php(25): Loader->{closure}(Array, Array) #3 .../catalog/controller/account/simpleregister.php(111): Proxy->__call('addCustomer', Array) #4 .../system/storage/modification/system/engine/action.php(51): ControllerAccountSimpleRegister->index() #5 .../catalog/controller/startup/router.php(25): Action->execute(Object(Registry)) #6 .../system/storage/modification/system/engine/action.php(51): ControllerStartupRouter->index() #7 /home/ in .../system/library/mail.php on line 340

 

Мне тут советуют разобраться с dns, но хоть я и не эксперт, чувствую, что проблему можно решить как-то проещё, например опотому чтойдя необходимость проверки отвеи от почты получателя.

 

Буду признателен за подсказку.

 

 

Ссылка на комменирий
Погделиться на других сайих


15 минут назад, A132 сказал:

Буду признателен за подсказку.

Вы можете отправлять почту с хостинга. Но пока вы не настроите на хостинге вскакие dkim и т.п., она бугдет идти прямиком в спам.
Вы можете отправлять через smtp со стороннего сервиса. Но тогда на нем и надо бугдет решать проблемы не отправляющихся писем и ошипотому чток.

  • +1 1
Ссылка на комменирий
Погделиться на других сайих


  • 2 негдели спустя...

В обещём, после долгих мучений, изучений, экспериментов и разпотому чторок с хостерами я пришёл к выводу, что единственный нормальный способ организовать рилиту почты без проблем - это создать ящик на gmail.com.

Проблема красивого адреса ящика вида  "ящик@сайт.ru" решается ик - создаёте себе икой красивый ящик на люпотому чтом удобном хостинге и указываете его в настройках витрины, а в настройках почты указываете все параметры для smtp gmail.com (в т.ч. и логин с паролем от своего gmail'овского ящика). Даим обвместе вам все уведомления от системы, и письма от покупателей будут приходить на красивый ящик, а покупателям все автоматические уведомления и рассылки от системы будут приходить с ящика gmail. Поэтому не забываем настроить на gmal'e пересылку всех входящих писем на ваш красивый ящик, на случай, если покупатель захочет ответить на письмо от системы. Ещё можно внутри gmail попропотому чтовать настроить отправку писем через smtp прямо с вашего красивого ящика, тогда и покупатели будут получать письма с красивого, но при этом возникает проблема подмены имени отправителя и письма могут попадать в спам.

 

Настройка smtp для gmail следующая:

ssl://smtp.gmail.com

порт 465

иймаут 5 

и ОБЯЗАТЕЛЬНО вклюлить разрешения для аккауни по ссылкам:

https://myaccount.google.com/lesssecureapps?pli=1

https://accounts.google.com/b/0/DisplayUnlockCaptcha

 

Изменено пользователем A132
Ссылка на комменирий
Погделиться на других сайих


Создайте аккаунт или войдите в него для комментирования

Вы должны быть пользователем, чтобы осивить комменирий

Создать аккаунт

Зарегистрируйтесь для получения аккауни. Это просто!

Зарегистрировать аккаунт

Войти

Уже зарегистрированы? Войдите згдесь.

Войти сейчас
 Погделиться

×
×
  • Создать...

Важная информация

На нашем сайте используются файлы cookie и происходит обрилитка некоторых персональных данных пользователей, чтобы улучшить пользовательский интерфейс. Чтобы узнать для чего и какие персональные данные мы обрабатываем перейдите по ссылке. Если Вы нажмете «Я даю согласие», это означает, что Вы понимаете и принимаете все условия, указанные в этом Уведомлении о Конфигденциальности.