How do I use action mailer / create and send emails in Trax?
From PHP on Trax
Generate Mailer Templates
[root@bsd1 /home/phpontrax/dev/trax]# php script/generate.php mailer
Usage: php script/generate.php mailer MailerName [view1 view2 ...]
Description:
The mailer generator creates class methods for a new mailer and its views.
The generator takes a mailer name and a list of views as arguments.
The mailer name may be given in CamelCase or under_score.
The generator creates a mailer class in app/models with view templates
in app/views/mailer_name.
Example:
php script/generate.php mailer Notifications signup forgot_password invoice
This will create a Notifications mailer class:
Mailer: app/models/notifications.php
Views: app/views/notifications/signup.phtml [...]
Example Code
After you generate your Mailer you will have a model in the models folder and a view foreach method in the views/mailer_name folder.
Mailer Model (app/models/notifications.php)
<?php
class Notifications extends ActionMailer {
function send_password($user) {
$this->subject = 'Your new password';
$this->recipients = $user->email;
$this->from = 'Admin <me@myserver.com>';
$this->body = array("user" => $user);
}
}
?>
View for send_password() (app/views/notifications/send_password.phtml)
Dear <?= $user->first_name ?>
Your password is <?= $user->password ?>.
Thank you,
Our site management
Now to use the Mailer you will just do the following:
<?
class LoginController extends ApplicationController {
function send_password() {
$user = new User;
$user = $user->find_by_email($_REQUEST['email']);
$mail = new Notifications;
$mail->deliver_send_password($user);
}
}
?>
You will notice that there is no deliver_send_password() method in our class... to make ActionMailer actually create and send the email all you have to do is prepend the method call with "deliver_". You can also use "create_" which will not send the email but return an object with the generated email in it, then if you want to send you can call plain deliver() on the returned object.
Lastly if you want to see the email Action Mailer is generating you can call the encoded() method on your object and it will return a string of the email it sent / created.
# encoded() output
MIME-Version: 1.0
To: john@test.com
From: nobody@myserver.com
Subject: JohnMailer->send
Date: Tue, 23 May 2006 04:14:20 -0600
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
JohnMailer->send
Find me in app/views/notifications/send_password.phtml
If you want to send HTML emails in your model all need to do is set the variable
<? $this->content_type = "html"; # html | text | both ?>
If you are testing and don't want a bunch of emails going out you can also set the variable
<? $this->delivery_method = "test"; ?>
This will make it store the email it would have sent in the class variable $deliveries. (an array)
