Use SSL or TLS with SMTP in ZF2

Published on February 28, 2013 by

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.

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

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!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.