Use SSL or TLS with SMTP in ZF2
If you want to use an SMTP server when sending e-mail through Zend Framework 2, you might be left wondering how to make use of a secure connection. In fact, the official documentation states nothing about this, and searching the Zend\Mail\Transport\SmtpOptions and Zend\Mail\Transport\Smtp classes gives no indication on how to accomplish this.
However, by taking a look at the Zend\Mail\Protocol\Smtp class’ constructor, it quickly becomes clear how to use a secure connection with an SMTP server:
public function __construct($host = '127.0.0.1', $port = null, array $config = null)
{
/* Some code omitted */
if (isset($config['ssl'])) {
switch (strtolower($config['ssl'])) {
case 'tls':
$this->secure = 'tls';
break;
case 'ssl':
$this->transport = 'ssl';
$this->secure = 'ssl';
if ($port == null) {
$port = 465;
}
break;
default:
throw new Exception\InvalidArgumentException($config['ssl'] . ' is unsupported SSL type');
break;
}
}
}
Because our SMTP transport class has a Zend\Mail\Protocol\Smtp connection variable, we can configure this to use a secure connection like shown below.
/* Setup of the Zend\Mail\Message instance is omitted */
$smtpOptions = new \Zend\Mail\Transport\SmtpOptions();
$smtpOptions->setHost('smtp.gmail.com')
->setConnectionClass('login')
->setName('smtp.gmail.com')
->setConnectionConfig(array(
'username' => '[email protected]',
'password' => 'some_password',
'ssl' => 'tls',
));
$transport = new \Zend\Mail\Transport\Smtp($smtpOptions);
$transport->send($message);
The above example uses Gmail’s SMTP server to send an e-mail over a secure connection. This is specified by configuring the connection by passing an array that includes the ssl key. As we saw in the source code a moment ago, the valid values are ssl and tls.
For information about the various classes used to send e-mail through Zend Framework 2, please see the official documentation about this subject.
Here is what you will learn:
- Understand the theory of Zend Framework in details
- How to implement an enterprise-ready architecture
- Develop professional applications in Zend Framework
- Proficiently work with databases in Zend Framework
- ... and much more!