Back to the module list

Send mails by SMTP protocol

The SMTP protocol allow the PHP to send emails. It supports the encryption with the server, in the connection (STARTTLS), authentication. To create valid emails, use the mail class. Then use

echo $smtp->send ("sender@example.com",
                  "recipient@example.com",
                  $mail->getMail ());

If there is an error, an exception is raised

Light example

Use the local server and STARTTLS if the server support it. On port 25 by default.

$smtp = new smtp ();
$smtp->connect ();
$rc = $smtp->send ("sender@example.com", "recipient@example.com",
                   "From: Sender <sender@example.com>\r\n".
                   "To: Recipient <recipient@example.com>\r\n".
                   "Subject: Test\r\n".
                   "Message-ID: ".md5 (rand ().time ()). "\r\n".
                   "Date: ".date ("r")."\r\n".
                   "\r\n".
                   "Message\r\n");
$smtp->disconnect ();

The result of $smtp->send is the last valid message from the server.
Example : 250 2.0.0 Ok: queued as DF735C3BBA

With SSL support

Use the port 465 by default. The server must be defined as the certificate is

validated, or an exception will be raised.
   $smtp = new smtp ();
   $smtp->server = "smtp.example.com";
   $smtp->ssl = true;
   $smtp->connect ();
   $rc = $smtp->send ("sender@example.com", "recipient@example.com",
                      "From: Sender <sender@example.com>\r\n".
                      "To: Recipient <recipient@example.com>\r\n".
                      "Subject: Test\r\n".
                      "Message-ID: ".md5 (rand ().time ()). "\r\n".
                      "Date: ".date ("r")."\r\n".
                      "\r\n".
                      "Message\r\n");
   $smtp->reset ();
   $smtp->disconnect ();

With SSL support and authentication

Use the port 465 by default. The server must be defined as the certificate is

validated, or an exception will be raised.
   $smtp = new smtp ();
   $smtp->server = "smtp.example.com";
   $smtp->ssl = true;
   $smtp->user = "user@domain.tld";
   $smtp->password = "*********";
   $smtp->connect ();
   $rc = $smtp->send ("sender@example.com", "recipient@example.com",
                      "From: Sender <sender@example.com>\r\n".
                      "To: Recipient <recipient@example.com>\r\n".
                      "Subject: Test\r\n".
                      "Message-ID: ".md5 (rand ().time ()). "\r\n".
                      "Date: ".date ("r")."\r\n".
                      "\r\n".
                      "Message\r\n");
   $smtp->reset ();
   $smtp->disconnect ();