User Tools

Site Tools


tina4:messenger

Sending email with Tina4 Messenger

Tina4 Messenger can send email using PHP's built-in mail() function or PHPMailer. We recommend PHPMailer if you're going to need encryption, SMTP authentication, attachments or html emails as these features are not supported by mail().

Did you know Tina4 Messenger can also send SMS through BulkSMS.com?

Sending Email Example

This example sends email from a route.

Add phpmailer to your project for best results

composer require phpmailer/phpmailer

Define your SMTP Constants

.env
[Email]
SMTP_USERNAME="hello@example.com"
SMTP_PASSWORD="your-mail-password"
SMTP_HOST="mail.example.com"
SMTP_PORT=587
SMTP_USE_PHPMAILER=true

Define your Route You'll need a get route as well do display your form if you're building out a reset password form with email response. Learn Tina4 Routing

index.php
\Tina4\Post::add("/forgotten-password", function (\Tina4\Response $response, \Tina4\Request $request) {
 
 $user = (new User()); // user ORM object
 
 $settings = new \Tina4\MessengerSettings(SMTP_USE_PHPMAILER);
        $settings->smtpUsername = SMTP_USERNAME;
        $settings->smtpPassword = SMTP_PASSWORD;
        $settings->smtpServer = SMTP_HOST;
        $settings->smtpPort = SMTP_PORT;
 
  $recipients[] = ["name" => "{$user->firstName} {$user->lastName}", "email" => $user->email];
 
//$data depends on the handlebars variables in your email template. Send email parses the twig template file and replaces these values for you.
 
   (new \Tina4\Messenger($settings))->sendEmail($recipients, "Email Subject",
            ["template" => "/messages/reset.twig", "data" => ["firstName" => $user->firstName, "username" => $user->email, "activationLink" => "//".$_SERVER["HTTP_HOST"]."/activate/{$user->verificationCode}"] ],
            "example.com", "hello@example.com");
 
 // Add your redirect code here after Debugging the email send             
}            

Add your email template to the templates directory. In this case reset.twig is in /templates/messages, so we include the /messages/reset.twig

Write out your template file Note the handlebars variables in the template file and how they are included above as key value pairs in the data array that your parse to Tina4's Messenger sendMail method.

reset.twig
Dear {{ firstName }}
<br>
You or someone requested a password reset link from our website, it is important you reset your password.
<br>
Your username is <b>{{ username }}</b>
<br>
Please click on the following <a href="{{ activationLink }}">link</a> to activate your account and choose a new password
<br>
<br>
Example.com Team

Don't redirect your page when testing your email route. Tina4 Messenger will return useful debugging information in the browser.

tina4/messenger.txt · Last modified: 2021/05/31 14:51 by cris