PHP code example of smalot / smtp-server

1. Go to this page and download the library: Download smalot/smtp-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

smalot / smtp-server example snippets


class MyServer extends \Smalot\Smtp\Server\Server
{
    /**
     * @param Connection $connection
     * @param MethodInterface $method
     * @return bool
     */
    public function checkAuth(Connection $connection, MethodInterface $method)
    {
        $username = $method->getUsername();
        $password = $this->getPasswordForUsername();
    
        return $method->validateIdentity($password);
    }
    
    /**
     * @param string $username
     * @return string
     */
    protected function getPasswordForUsername($username)
    {
        // @Todo: Load password from Database or somewhere else.
        $password = '';
    
        return $password;
    }
}



try {
    $dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();

    $logger = new \Monolog\Logger('log');
    $dispatcher->addSubscriber(new \Smalot\Smtp\Server\Event\LogSubscriber($logger));
    
    $loop = React\EventLoop\Factory::create();
    $server = new \Smalot\Smtp\Server\Server($loop, $dispatcher);
    // Enable 3 authentication methods.
    $server->authMethods = [
      \Smalot\Smtp\Server\Connection::AUTH_METHOD_LOGIN,
      \Smalot\Smtp\Server\Connection::AUTH_METHOD_PLAIN,
      \Smalot\Smtp\Server\Connection::AUTH_METHOD_CRAM_MD5,
    ];
    // Listen on port 25.
    $server->listen(25);
    $loop->run();
}
catch(\Exception $e) {
    var_dump($e);
}



try {
    $mail = new PHPMailer();

    $mail->isSMTP();
    $mail->Host = 'localhost';
    $mail->Port = 25;
    $mail->SMTPDebug = true;

    $mail->SMTPAuth = true;
    $mail->Username = "[email protected]";
    $mail->Password = "[email protected]";

    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
    $mail->addAddress('[email protected]');               // Name is optional
    $mail->addReplyTo('[email protected]', 'Information');
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
}
catch(\Exception $e) {
    var_dump($e);
}