54f2c50b2102348386309515ad71e43599c8094c
[catagits/Catalyst-Plugin-Email.git] / Email.pm
1 package Catalyst::Plugin::Email;
2
3 use strict;
4 use Email::Send;
5 use Email::MIME;
6 use Email::MIME::Creator;
7
8 our $VERSION = '0.05';
9
10 =head1 NAME
11
12 Catalyst::Plugin::Email - Send emails with Catalyst
13
14 =head1 SYNOPSIS
15
16     use Catalyst 'Email';
17
18     __PACKAGE__->config->{email} = [qw/SMTP smtp.oook.de/];
19
20     $c->email(
21         header => [
22             From    => 'sri@oook.de',
23             To      => 'sri@cpan.org',
24             Subject => 'Hello!'
25         ],
26         body => 'Hello sri'
27     );
28
29 =head1 DESCRIPTION
30
31 Send emails with Catalyst and L<Email::Send> and L<Email::MIME::Creator>.
32
33 =head1 USING WITH A VIEW
34
35 A common practice is to handle emails using the same template language used
36 for HTML pages.  This can be accomplished by pairing this plugin with
37 L<Catalyst::Plugin::SubRequest>.
38
39 Here is a short example of rendering an email from a Template Toolkit source
40 file.  The call to $c->subreq makes an internal call to the render_email
41 method just like an external call from a browser.  The request will pass
42 through the end method to be processed by your View class.
43
44     sub send_email : Local {
45         my ( $self, $c ) = @_;  
46
47         $c->email(
48             header => [
49                 To      => 'me@localhost',
50                 Subject => 'A TT Email',
51             ],
52             body => $c->subreq( '/render_email' ),
53         );
54         # redirect or display a message
55     }
56     
57     sub render_email : Local {
58         my ( $self, $c ) = @_;
59         
60         $c->stash(
61             names    => [ qw/andyg sri mst/ ],
62             template => 'email.tt',
63         );
64     }
65     
66 And the template:
67
68     [%- FOREACH name IN names -%]
69     Hi, [% name %]!
70     [%- END -%]
71     
72     --
73     Regards,
74     Us
75
76 Output:
77
78     Hi, andyg!
79     Hi, sri!
80     Hi, mst!
81     
82     --
83     Regards,
84     Us
85
86 =head1 METHODS
87
88 =head2 email
89
90 =cut
91
92 sub email {
93     my $c = shift;
94     my $email = $_[1] ? {@_} : $_[0];
95     $email = Email::MIME->create(%$email);
96     my $args = $c->config->{email} || [];
97     my @args = @{$args};
98     my $class;
99     unless ( $class = shift @args ) {
100         $class = 'SMTP';
101         unshift @args, 'localhost';
102     }
103     send $class => $email, @args;
104 }
105
106 =head1 SEE ALSO
107
108 L<Catalyst>, L<Catalyst::Plugin::SubRequest>, L<Email::Send>,
109 L<Email::MIME::Creator>
110
111 =head1 AUTHOR
112
113 Sebastian Riedel, C<sri@cpan.org>
114
115 =head1 COPYRIGHT
116
117 This program is free software, you can redistribute it and/or modify it 
118 under the same terms as Perl itself.
119
120 =cut
121
122 1;