- added cc and bcc attributes to simple api
[catagits/Catalyst-View-Email.git] / lib / Catalyst / View / Email / Template.pm
1 package Catalyst::View::Email::Template;
2
3 use warnings;
4 use strict;
5
6 use Class::C3;
7 use Carp;
8 use Scalar::Util qw/ blessed /;
9
10 use Email::MIME::Creator;
11
12 use base qw/ Catalyst::View::Email /;
13
14 our $VERSION = '0.09999_01';
15
16 =head1 NAME
17
18 Catalyst::View::Email::Template - Send Templated Email from Catalyst
19
20 =head1 SYNOPSIS
21
22 Sends Templated mail, based upon your default view. It captures the output
23 of the rendering path, slurps in based on mime-types and assembles a multi-part
24 email using Email::MIME::Creator and sends it out.
25
26 =head1 CONFIGURATION
27
28 Use the helper to create your View:
29     
30     $ script/myapp_create.pl view Email::Template Email::Template
31
32 In your app configuration (example in L<YAML>):
33
34     View::Email::Template:
35         # Optional prefix to look somewhere under the existing configured
36         # template  paths.
37         # Default: none
38         template_prefix: email
39         # Where to look in the stash for the email information.
40         # Default: email
41         stash_key: email
42         # Define the defaults for the mail
43         default:
44             # Defines the default content type (mime type).
45             # Mandatory
46             content_type: text/html
47             # Defines the default charset for every MIME part with the content
48             # type text.
49             # According to RFC2049 a MIME part without a charset should
50             # be treated as US-ASCII by the mail client.
51             # If the charset is not set it won't be set for all MIME parts
52             # without an overridden one.
53             # Default: none
54             charset: utf-8
55             # Defines the default view used to render the templates.
56             # If none is specified neither here nor in the stash
57             # Catalysts default view is used.
58             # Warning: if you don't tell Catalyst explicit which of your views should
59             # be its default one, C::V::Email::Template may choose the wrong one!
60             view: TT
61         # Setup how to send the email
62         # All those options are passed directly to Email::Send,
63         # for all available options look at its docs.
64         sender:
65             mailer: SMTP
66             mailer_args:
67                 Host:       smtp.example.com # defaults to localhost
68                 username:   username
69                 password:   password
70
71 =head1 SENDING EMAIL
72
73 Sending email is just setting up your defaults, the stash key and forwarding to the view.
74
75     $c->stash->{email} = {
76         to      => 'jshirley@gmail.com',
77         from    => 'no-reply@foobar.com',
78         subject => 'I am a Catalyst generated email',
79         template => 'test.tt',
80     };
81     $c->forward('View::Email::Template');
82
83 Alternatively if you want more control over your templates you can use the following idiom
84 to override the defaults:
85
86     templates => [
87         {
88             template        => 'email/test.html.tt',
89             content_type    => 'text/html',
90             charset         => 'utf-8',
91             view            => 'TT', 
92         },
93         {
94             template        => 'email/test.plain.mason',
95             content_type    => 'text/plain',
96             charset         => 'utf-8',
97             view            => 'Mason', 
98         }
99     ]
100
101
102 If it fails $c->error will have the error message.
103
104 =cut
105
106 # here the defaults of Catalyst::View::Email are extended by the additional
107 # ones Template.pm needs.
108
109 __PACKAGE__->config(
110     template_prefix => '',
111 );
112
113
114 # This view hitches into your default view and will call the render function
115 # on the templates provided.  This means that you have a layer of abstraction
116 # and you aren't required to modify your templates based on your desired engine
117 # (Template Toolkit or Mason, for example).  As long as the view adequately
118 # supports ->render, all things are good.  Mason, and others, are not good.
119
120 #
121 # The path here is to check configuration for the template root, and then
122 # proceed to call render on the subsequent templates and stuff each one
123 # into an Email::MIME container.  The mime-type will be stupidly guessed with
124 # the subdir on the template.
125 #
126
127 # Set it up so if you have multiple parts, they're alternatives.
128 # This is on the top-level message, not the individual parts.
129 #multipart/alternative
130
131 sub _validate_view {
132     my ($self, $view) = @_;
133     
134     croak "Email::Template's configured view '$view' isn't an object!"
135         unless (blessed($view));
136
137     croak "Email::Template's configured view '$view' isn't an Catalyst::View!"
138         unless ($view->isa('Catalyst::View'));
139
140     croak "Email::Template's configured view '$view' doesn't have a render method!"
141         unless ($view->can('render'));
142 }
143
144 sub _generate_part {
145     my ($self, $c, $attrs) = @_;
146     
147     my $template_prefix         = $self->{template_prefix};
148     my $default_view            = $self->{default}->{view};
149     my $default_content_type    = $self->{default}->{content_type};
150     my $default_charset         = $self->{default}->{charset};
151
152     my $e_m_attrs = {};
153
154     my $view;
155     # use the view specified for the email part
156     if (exists $attrs->{view} && defined $attrs->{view} && $attrs->{view} ne '') {
157         $view = $c->view($attrs->{view});
158         $c->log->debug("C::V::Email::Template uses specified view $view for rendering.") if $c->debug;
159     }
160     # if none specified use the configured default view
161     elsif ($default_view) {
162         $view = $c->view($default_view);
163         $c->log->debug("C::V::Email::Template uses default view $view for rendering.") if $c->debug;;
164     }
165     # else fallback to Catalysts default view
166     else {
167         $view = $c->view;
168         $c->log->debug("C::V::Email::Template uses back to catalysts default view $view for rendering.") if $c->debug;;
169     }
170
171     # validate the per template view
172     $self->_validate_view($view);
173     
174     # prefix with template_prefix if configured
175     my $template = $template_prefix ne '' ? join('/', $template_prefix, $attrs->{template}) : $attrs->{template};
176     
177     if (exists $attrs->{content_type} && defined $attrs->{content_type} && $attrs->{content_type} ne '') {
178         $e_m_attrs->{content_type} = $attrs->{content_type};
179     }
180     elsif (defined $default_content_type && $default_content_type ne '') {
181         $e_m_attrs->{content_type} = $default_content_type;
182     }
183    
184     if (exists $attrs->{charset} && defined $attrs->{charset} && $attrs->{charset} ne '') {
185         $e_m_attrs->{charset} = $attrs->{charset};
186     }
187     elsif (defined $default_charset && $default_charset ne '') {
188         $e_m_attrs->{charset} = $default_charset;
189     }
190
191     # render the email part
192     my $output = $view->render( $c, $template, { 
193         content_type    => $e_m_attrs->{content_type},
194         stash_key       => $self->{stash_key},
195         %{$c->stash},
196     });
197                                 
198     if (ref $output) {
199         croak $output->can('as_string') ? $output->as_string : $output;
200     }
201         
202     return Email::MIME->create(
203         attributes => $e_m_attrs,
204         body => $output,
205     );
206 }
207
208 sub process {
209     my ( $self, $c ) = @_;
210
211     # don't validate template_prefix
212
213     # the default view is validated if used
214
215     # the content type should be validated by Email::MIME::Creator
216     
217     my $stash_key = $self->{stash_key};
218
219     croak "No template specified for rendering"
220         unless $c->stash->{$stash_key}->{template}
221             or $c->stash->{$stash_key}->{templates};
222     
223     # this array holds the Email::MIME objects
224     # in case of the simple api only one
225     my @parts = (); 
226
227     # now find out if the single or multipart api was used
228     # prefer the multipart one
229     
230     # multipart api
231     if ($c->stash->{$stash_key}->{templates}
232         && ref $c->stash->{$stash_key}->{templates} eq 'ARRAY'
233         && ref $c->stash->{$stash_key}->{templates}[0] eq 'HASH') {
234         # loop through all parts of the mail
235         foreach my $part (@{$c->stash->{$stash_key}->{templates}}) {
236             push @parts, $self->_generate_part($c, {
237                 view            => $part->{view},
238                 template        => $part->{template},
239                 content_type    => $part->{content_type},
240                 charset         => $part->{charset},
241             });
242         }
243     }
244     # single part api
245     elsif($c->stash->{$stash_key}->{template}) {
246         push @parts, $self->_generate_part($c, {
247             template    => $c->stash->{$stash_key}->{template},
248         });
249     }
250     
251     delete $c->stash->{$stash_key}->{body};
252     $c->stash->{$stash_key}->{parts} ||= [];
253     push @{$c->stash->{$stash_key}->{parts}}, @parts;
254
255     # Let C::V::Email do the actual sending.  We just assemble the tasty bits.
256     return $self->next::method($c);
257 }
258
259 =head1 TODO
260
261 =head2 ATTACHMENTS
262
263 There needs to be a method to support attachments.  What I am thinking is
264 something along these lines:
265
266     attachments => [
267         # Set the body to a file handle object, specify content_type and
268         # the file name. (name is what it is sent at, not the file)
269         { body => $fh, name => "foo.pdf", content_type => "application/pdf" },
270         # Or, specify a filename that is added, and hey, encoding!
271         { filename => "foo.gif", name => "foo.gif", content_type => "application/pdf", encoding => "quoted-printable" },
272         # Or, just a path to a file, and do some guesswork for the content type
273         "/path/to/somefile.pdf",
274     ]
275
276 =head1 SEE ALSO
277
278 =head2 L<Catalyst::View::Email> - Send plain boring emails with Catalyst
279
280 =head2 L<Catalyst::Manual> - The Catalyst Manual
281
282 =head2 L<Catalyst::Manual::Cookbook> - The Catalyst Cookbook
283
284 =head1 AUTHORS
285
286 J. Shirley <jshirley@gmail.com>
287
288 Simon Elliott <cpan@browsing.co.uk>
289
290 Alexander Hartmaier <alex_hartmaier@hotmail.com>
291
292 =head1 LICENSE
293
294 This library is free software, you can redistribute it and/or modify it under
295 the same terms as Perl itself.
296
297 =cut
298
299 1;