Using Magento 2 Version 2.1.0 on WAMP Windows 10
As continue with this question Magento 2: SMTP Email gives error «Invalid sender data»
Now this is my code
$storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
$templateId = $this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE);
$transport = $this->_transportBuilder->setTemplateIdentifier($templateId)
->setTemplateOptions(['area' => MagentoBackendAppAreaFrontNameResolver::AREA_CODE, 'store' => 1])
->setTemplateVars(['data' => $postObject])
->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
->addTo('xxxxxx@gmail.com')
->setReplyTo('xxxxx@gmail.com')
->getTransport();
echo $transport->sendMessage();
exit;
Now it’s giving below error
2 exception(s): Exception #0
(MagentoFrameworkExceptionMailException): Could not open socket
Exception #1 (Zend_Mail_Protocol_Exception): Could not open socket
I have already followed https://stackoverflow.com/questions/28433816/how-to-fix-could-not-open-socket-in-zend-mail-zend-framework-2
But still same issue. OpenSSL is enabled on WAMP. When i’m trying to uncomment
#LoadModule ssl_module modules/mod_ssl.so
in httpd.conf & trying to restart WAMP Server. It pauses on Yellow not become Green.
asked Sep 7, 2016 at 1:23
SELINUX BLOCKING If you are getting error message like SMTP -> ERROR: Failed to connect to server: Permission denied (13), Permission denied, and your are hosting on RedHat / Fedora / Centos this is more than likely cause by SELinux preventing PHP or the web server from sending email. . Using the getsebool command we can check if the httpd daemon is allowed to make a connection over the network and send an email:
getsebool httpd_can_sendmail
getsebool httpd_can_network_connect
This command will return a boolean on or off. If it’s off, we can turn it on:
sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_can_network_connect 1
Thanks to MagePal here is their full documentation
answered Jun 14, 2020 at 0:15
Helped for me: solution for smtp servers (including gmail):
$ php --version
PHP 7.0.13 (cli) (built: Nov 8 2016 20:41:42) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
vendor/magento/zendframework1/library/Zend/Mail/Protocol/Abstract.php function _connect($remote)
remove ‘@’ at line: 267 like an example:
// $this->_socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION);
$this->_socket = stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION);
for self-signed SSL certificates:
comment line: 267 and add additional code like an example:
// $this->_socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION);
$ctx = stream_context_create(['ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]]);
$this->_socket = stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION, STREAM_CLIENT_CONNECT, $ctx);
vendor/magepal/magento2-gmailsmtpapp/Controller/Adminhtml/Test/Index.php:73
for chrome/chromium browsers,
during ‘Sending test email’, force email password like an example:
// ‘password’ => $password,
‘password’ => ‘your email password’,
-

Member
- Join Date: Feb 2017
- Posts: 41
Hello,
I have e fresh installed EspoCRM (4.4.1) running under Debian with Apache 2.4 and PHP 7.0 (exact Version 7.0.16). I try to configure the Email account for outgoing Emails by using our Windows Exchange Server 2010 via SMTP. In a first step I’ve got always the error «Could not open socket, Code: 500 URL: /api/v1/Email/action/sendTestEmail [] []»
After some investigation I could fix this error by inserting the Statement ‘openssl.cafile’ in the php.ini. But now I get another error. That’s the snippet from the log:
——————
[2017-02-27 14:02:27] Espo.WARNING: E_WARNING: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed {«code»:2,»message»:»stream_socket_enable_crypto() : SSL operation failed with code 1. OpenSSL Error messages:nerror:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed»,»file»:»/var/www/crm/vendor/zendframework/zend-mail/src/Protocol/Smtp.php»,»line»:178,»context»:{«host»:»admin»}} []
[2017-02-27 14:02:27] Espo.ERROR: API [POST]:/:controller/action/:action, Params:Array ( [controller] => Email [action] => sendTestEmail ) , InputData: {«server»:»XXX.XXX.XXX.XXX»,»port»:587,»auth»:true ,»security»:»TLS»,»username»:»XYZUser»,»password»: «*****»,»fromName»:»»,»fromAddress»:»XYZ@XXX.de»,» type»:»outboundEmail»,»emailAddress»:»ABC@DEF.de»} — Unable to connect via TLS [] []
[2017-02-27 14:02:27] Espo.ERROR: Display Error: Unable to connect via TLS, Code: 500 URL: /api/v1/Email/action/sendTestEmail [] []
——————
It seems, that the System is using the host «admin» instead of the real name/IP adress. And I have no idea where I can fix it.Can anyone help me?
-

Junior Member
- Join Date: Mar 2018
- Posts: 1
Hi!
This error is associated with a self-signed certificate on the server.
2 solutions:
1. Use the correct certificate on the server (Let’s Encrypt or other)
2. Make changes to the certificate validation when connecting via SSL.Code:
vendor/zendframework/zend-mail/src/Protocol/AbstractProtocol.php
change function _connect.
replacePHP Code:
// open connection
$this->socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION);
with
PHP Code:
$contextOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false
)
);$context = stream_context_create($contextOptions);// open connection
$this->socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION, STREAM_CLIENT_CONNECT, $context);
Comment
-

Junior Member
- Join Date: Apr 2019
- Posts: 6
This solution worked fine until the last update (5.9.0). Is there a new solution for this problem?
Many thanks
-
Likes
1
Comment
-
Member
- Join Date: Mar 2014
- Posts: 6313
zendframework was renamed to laminas. You need to make the same changed in vendor/laminas.
-
Likes
1
Comment
-

Junior Member
- Join Date: Apr 2019
- Posts: 6
I already tried this, emptied the cache, restarted the webserver and reloaded the page. But still the same error …
Comment
-

Active Community Member
- Join Date: Jan 2020
- Posts: 1541
Is your error exactly like the first post? If not perhaps trying copy/paste it and someone might be able to provide insight.
Considering you have (full?) access to your Server, why not use Let’s Encrypt SSL?
Comment
-

Junior Member
- Join Date: Apr 2019
- Posts: 6
Hi,
the error points to an invalid certificate (self-signed). The exact errormessage is: Fehler 500: Could not open socket: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:, error:1416F086:SSL routines:tls_process_server_certificate:certificat e verify failedThe reason was my self-signed certificate, which normally doesn’t cause trouble after I added the lines from the second post.
My solution is now: I installed a Let’s Encrypt certificate and this fixed my problem (at least for the next 90 days).
Comment
-

Active Community Member
- Join Date: Jan 2020
- Posts: 1541
Originally posted by boris
View Post
My solution is now: I installed a Let’s Encrypt certificate and this fixed my problem (at least for the next 90 days).
Glad to hear you found a solutions. My host only give 1 SSL, if I want more I have to manually do it with Let’s Encrypt. Fortunately there is a system where you can make this automated, perhaps look into that. My host won’t let me but sound like you have free reign in your server:
Please refer to here:
Comment
#1
![]()
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 17:32
Проблема:
пользователям не приходят письма с форума
При проверке работы почты выдает ошибку:
Could not open a socket to the SMTP server (111:В соединении отказано)
настройки на фото
У кого нибудь была такая проблема, или похожая с настройкой отправки сообщений?
Форум IPB 3.4.6, стоит на Хостинге MyArena!
Прикрепленные файлы
- Наверх
#2
![]()
Kakoin
Отправлено 14 Июль 2015 — 17:35
Проблема:
пользователям не приходят письма с форума
При проверке работы почты выдает ошибку:
Could not open a socket to the SMTP server (111:В соединении отказано)
настройки на фото
У кого нибудь была такая проблема, или похожая с настройкой отправки сообщений?
Форум IPB 3.4.6, стоит на Хостинге MyArena!
http://wiki.myarena…._популярных_CMS
- Наверх
#3
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 17:48
Делал я уже так, какой порт SMTP у MyArena даже тех поддрежка не знает! Когда выставил настройки как на фото, выдает такую ошибку
Could not open a socket to the SMTP server (0:)
Пробовал прописать smtp.myarena.ru. стал выдавать ошибку
Password not accepted from the server
Прикрепленные файлы
-

sshot-4.jpg 12,15К
1 Количество загрузок:
Сообщение отредактировал artpalas: 14 Июль 2015 — 17:52
- Наверх
#4
![]()
Kakoin
Отправлено 14 Июль 2015 — 17:54
Делал я уже так, какой порт SMTP у MyArena даже тех поддрежка не знает! Когда выставил настройки как на фото, выдает такую ошибку
Could not open a socket to the SMTP server (0:)
Не знаю что уже сделать(((((((
точка вроде не нужна в конце
- Наверх
#5
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 18:06
точку убрал, но изменений нету, а вот в логах пишутся ошибки типа:
Password not accepted from the server
535 535 5.7.8 Error: authentication failed: UGFzc3dvcmQ6 (какая-то ошибка аутентификации)
В настройки email форума я вписывал логин и пароль из Панели управления MyArena, там где создавал почтовый ящик! по идее должны пароли совпадать, а в действительности это не так!
- Наверх
#6
![]()
Kakoin
Отправлено 14 Июль 2015 — 18:06
точку убрал, но изменений нету, а вот в логах пишутся ошибки типа:
Password not accepted from the server
535 535 5.7.8 Error: authentication failed: UGFzc3dvcmQ6 (какая-то ошибка аутентификации)В настройки email форума я вписывал логин и пароль из Панели управления MyArena, там где создавал почтовый ящик! по идее должны пароли совпадать, а в действительности это не так!
логин и пароль должны быть от почтового ящика
- Наверх
#7
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 18:16
так и есть, вот тут (как на фото) я создал почтовый ящик и пароль для него и их ввел на форуме в настройках mail
Прикрепленные файлы
-

sshot-2.jpg 9,56К
0 Количество загрузок:
- Наверх
#8
![]()
aza
Отправлено 14 Июль 2015 — 18:16
так и есть, вот тут (как на фото) я создал почтовый ящик и пароль для него и их ввел на форуме в настройках mail
это не работает =)
- Наверх
#9
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 18:24
это не работает =)
Это я уже знаю, подскажите что даст результат!
Сообщение отредактировал artpalas: 14 Июль 2015 — 18:24
- Наверх
#10
![]()
Kakoin
Отправлено 14 Июль 2015 — 18:26
Это я уже знаю, подскажите что даст результат!
ничего. настраивай через яндекс
- Наверх
#11
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 18:52
через яндекс заработало, Спасибо! (я думал что обязательно надо через MyArena)
- Наверх
#12
![]()
Kakoin
Отправлено 14 Июль 2015 — 18:55
через яндекс заработало, Спасибо! (я думал что обязательно надо через MyArena)
где ты такое увидел ?
- Наверх
#13
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 19:10
где ты такое увидел ?
http://wiki.myarena…._популярных_CMS
твоя же ссылка, вот все что там на примере яндекса было написано я вставил все оттуда, и письма идут нормально! А больше мне ниче не надо, хоть с луны пустьь идут эти письма, главное работает!
- Наверх
#14
![]()
Kakoin
Отправлено 14 Июль 2015 — 19:12
http://wiki.myarena…._популярных_CMS
твоя же ссылка, вот все что там на примере яндекса было написано я вставил все оттуда, и письма идут нормально! А больше мне ниче не надо, хоть с луны пустьь идут эти письма, главное работает!
через яндекс заработало, Спасибо! (я думал что обязательно надо через MyArena)
я про это.. где ты это увидел ?
- Наверх
#15
![]()
artpalas
artpalas
-

- Пользователь
-

- 9 сообщений
Новичок
Отправлено 14 Июль 2015 — 19:19
Да нигде не увидел, просто я не такой спец в этом как многие из присутсвтующих тут!
- Наверх
-
#1
in ipb 3.3.4 (invision power board) i am trying to use email user validation.
in the attachment below you can see my email setup settings.
I purchased my domain name from godaddy so the email is also from them.
info@grantmods.net
In my error logs of my admin control panel of ipb i get an error of : Could not open a socket to the SMTP server (110:Connection timed out).
The email verification is not sent to the user, i need this fix ASAP!
i am trying to use port 25, now knowing x10hosting blocks port 25 after some research.. what ports am i aloud to use in place of port 25?
-

Capture.PNG
45.5 KB · Views: 166
Last edited: Oct 9, 2012
-
#2
I do have a free hosting plan from when i purchased ipb but i want to use Cpanel. i think i solved this issue though thanks.
~Answer is~ You can not do this unless you use localhost.
![]()
-
#4
You can either use x10Hosting’s SMTP server on localhost or PHP’s mail() function to send emails, we do not allow outgoing SMTP connections to other servers, as per http://x10hosting.com/forums/news-a…garding-external-smtp-services-gmail-etc.html
i noticed that and the staff at ipb told me that as well. But i set up a email through Cpanel using local host port 25.
The email was grantmods.net, instead of doing it with godaddy, i seen i could do it in Cpanel as well. Is it suppose to work? or must the email be .x10.mx? so far .x10.mx is the only one that has ever worked for me.
This is no longer an issue as i am going to purchase hosting here soon anyways.
А я слышал и давно, да и здесь это было, про проблемы у всей третьей линейки конкретно c mail.ru и inbox.ua
Проблема smtp авторизации на mail.ru действительно есть. Согласно RFC в EHLO (HELO) нужно указать имя хоста откуда происходит запрос. В запросе EHLO прописано имя smtp сервера и, хотя это не соответствует стандарту, проблема на самом деле заключается в том, что хост содержит протокол с которым в команде EHLO он не валидный, поэтому майл не принимает авторизацию.
220 smtp8.mail.ru ESMTP ready > EHLO ssl://smtp.mail.ru 250-smtp8.mail.ru 250-SIZE 73400320 250-8BITMIME 250-PIPELINING 250 AUTH PLAIN LOGIN XOAUTH2 > AUTH LOGIN 334 VXNlcm5hbWU6 > dGVzdA== 334 UGFzc3dvcmQ6 > dGVzdA== 501 Syntactically invalid EHLO argument(s)
Исправить это можно в /ips_kernel/classEmail.php
$this->_smtpSendCmd( "{$this->smtp_helo} " . $this->smtp_host );
Заменив на:
$this->_smtpSendCmd( "{$this->smtp_helo} " . str_replace( array( 'ssl://', 'tls://' ), '', $this->smtp_host ) );
Или на: (согласно RFC2821)
$this->_smtpSendCmd( "{$this->smtp_helo} " . $_SERVER['SERVER_NAME'] );
Кроме того, mail.ru требует чтобы адрес отправителя (Email адрес для поля От) был из его зоны.
> MAIL FROM:no-reply@ipbskins.ru 550 not local sender over smtp
Загрузите sendmail.zip
Создайте папку с именем «sendmail» в «C:wamp». Извлеките эти 4 файла в папку «sendmail»: «sendmail.exe», «libeay32.dll», «ssleay32.dll» и «sendmail.ini». Откройте файл sendmail.ini и настройте его следующим образом:
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=ssl
default_domain=localhost
error_logfile=error.log
debug_logfile=debug.log
auth_username=[your_gmail_account_username]@gmail.com
auth_password=[your_gmail_account_password]
pop3_server=
pop3_username=
pop3_password=
force_sender=
force_recipient=
hostname=localhost
Вам не нужно указывать какое-либо значение для этих свойств: pop3_server, pop3_username, pop3_password, force_sender, force_recipient. Параметры error_logfile и debug_logfile должны быть пустыми, если вы уже отправили успешные электронные письма, в противном случае размер этого файла будет увеличиваться. Включите эти параметры файла журнала, если вы не можете отправлять электронную почту с помощью sendmail.
Включить IMAP-доступ в настройках GMail → Пересылка и POP/IMAP → Доступ к IMAP:
Enable "php_openssl" and "php_sockets" extensions for PHP compiler:
Open php.ini from "C:wampbinapacheApache2.2.17bin" and configure it as following (The php.ini at "C:wampbinphpphp5.3.x" would not work) (You just need to configure the last line in the following code, prefix semicolon (;) against other lines):
Перезапустите WAMP Server. Создайте файл PHP и напишите в нем следующий код:
<?php
$to = '[email protected]';
$subject = 'Testing sendmail.exe';
$message = 'Hi, you just received an email using sendmail!';
$headers = 'From: [your_gmail_account_username]@gmail.com' . "rn" .
'MIME-Version: 1.0' . "rn" .
'Content-type: text/html; charset=utf-8';
if(mail($to, $subject, $message, $headers))
echo "Email sent";
else
echo "Email sending failed";
?>
Внесите соответствующие изменения в переменные $ to и $ headers, чтобы указать адреса получателя и отправителя («От»). Сохраните его как «send-mail.php». (Вы можете сохранить его в любом месте или внутри любой подпапки в папке «C:wampwww».) Откройте этот файл в браузере, он ДОЛЖЕН работать сейчас