laravel5已經有很好的郵件發送功能,但都是常規 tls 不加密協議,如今有的雲服務器已經慢慢禁止使用不加密協議,要求使用ssl加密協議;如阿里雲新購買的服務器都開始禁止。php
因爲laravel5默認使用的是 swiftmailer 擴展。發送使用的是 stream 其中並未對ssl提供證書等內容配置,因此當使用ssl時又未指定證書時會錯:laravel
Connection could not be established with host *******.com [ #0]git
鏈接失敗,形成錯誤的地方:vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php 類
github
Swift_Transport_StreamBuffer 的 _establishSocketConnection 方法在調用 stream_context_create 時缺乏證書相關配置。swift
看看PHP官方文檔:http://php.net/manual/zh/context.ssl.php
服務器
其中須要注意的是 verify_peer_name 要求驗證證書名默認值爲true,這裏是問題因此,當沒有指定證書時該值會影響鏈接驗證失敗致使整個鏈接失敗。所以須要修改代碼並把 verify_peer_name 設置爲 false。socket
這個問題在 https://github.com/swiftmailer/swiftmailer/issues/544 中已經有說明。ide
但其增長了兩行代碼把 verify_peer 和 verify_peer_name 都設置爲false 。依文檔中看,verify_peer 默認值已是 false ,因此能夠不加。this
修改代碼以下:阿里雲
/** * Establishes a connection to a remote server. */ private function _establishSocketConnection() { $host = $this->_params['host']; if (!empty($this->_params['protocol'])) { $host = $this->_params['protocol'].'://'.$host; } $timeout = 15; if (!empty($this->_params['timeout'])) { $timeout = $this->_params['timeout']; } $options = array(); if (!empty($this->_params['sourceIp'])) { $options['socket']['bindto'] = $this->_params['sourceIp'].':0'; } //在這裏增長代碼,修改默認值 $options['ssl']['verify_peer_name'] = FALSE; $this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options)); if (false === $this->_stream) { throw new Swift_TransportException( 'Connection could not be established with host '.$this->_params['host']. ' ['.$errstr.' #'.$errno.']' ); } if (!empty($this->_params['blocking'])) { stream_set_blocking($this->_stream, 1); } else { stream_set_blocking($this->_stream, 0); } stream_set_timeout($this->_stream, $timeout); $this->_in = &$this->_stream; $this->_out = &$this->_stream; }
固然若是把 verify_peer 加上也沒有問題。