blib/lib/Mojolicious/Plugin/SendEmail.pm

filter: Statementstmt 75.0% 6 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 81.8% 9 / 11 CC 1 SCAR 0.9
CC
1
Cov
75%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Mojolicious::Plugin::SendEmail 0.02;
2 1 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: Easily send emails from Mojolicious applications
6  
7 =encoding utf-8
8  
9 =head1 NAME
10  
11 Mojolicious::Plugin::SendEmail - Easily send emails from Mojolicious applications
12  
13 Inspired by both L<Mojolicious::Plugin::Mail> and L<Mojolicious::Plugin::EmailMailer>
14  
15 =head1 SYNOPSIS
16  
17 # Register plugin
18 $self->plugin('SendEmail' => {
19 from => '"My Application" <myapp@tyrrminal.dev>',
20 host => ...,
21 port => ...,
22 recipient_resolver => sub { ... },
23 ...
24 });
25  
26 ...
27  
28 # Send simple email
29 $c->send_email(
30 to => 'mark@tyrrminal.dev',
31 subject => "Alert: MyApp failure",
32 body => "An error occurred when processing nightly data"
33 );
34  
35 ...
36  
37 # Send template-based email with attachments
38 $c->send_email(
39 to => 'daily',
40 subject => 'Nightly Attendance Report',
41 template => 'reports/nightly_attendance',
42 params => {
43 data => $report_data
44 },
45 files => ['generated/Nightly_Attendance_Report.xlsx']
46 );
47  
48 =head1 DESCRIPTION
49  
50 Mojolicious::Plugin::SendEmail is a convenient wrapper for L<Email::Stuffer> and
51 L<Email::Sender::Transport::SMTP> for sending email from Mojolicious commands
52 and controllers, etc.
53  
54 The basic concept here is that it sets up the SMTP details at initial plugin load
55 and then every subsequent call to L</create_email> or L</send_email> uses those
56 values, so that subsequently you don't need to worry about them.
57  
58 A little bit of "added value" functionality exists in this module as well:
59  
60 =over
61  
62 =item * Unlike L<Email::Stuffer> you I<usually> don't need to tell it whether
63 your body is text or HTML. See L</html> below for details
64  
65 =item * This module uses the concept of recipient resolution to support "faux
66 distribution lists". See L</recipient_resolver> below for details
67  
68 =back
69  
70 =cut
71  
72 0 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=2.6
73  
74 use Email::Stuffer;
75 use Params::Util qw(_INSTANCEDOES);
76 use Email::Sender::Transport::SMTP;
77  
78 use experimental qw(signatures);
79  
80 =pod
81  
82 =head1 METHODS
83  
84 L<Mojolicious::Plugin::SendEmail> inherits all methods from L<Mojolicious::Plugin>
85 and implements the following new ones
86  
87 =head2 register
88  
89 Register plugin in L<Mojolicious> application. All parameters given are passed
90 on to L<Email::Sender::Transport::SMTP> except for:
91  
92 =head4 from
93  
94 Sets the default C<from> address for all emails. If not given,
95 L<"from"|/from1> will be required in all calls to L</create_email> and L</send_email>
96  
97 =head4 recipient_resolver
98  
99 Sets the function that will be used for resolving recipient aliases
100  
101 =cut
102  
103 sub register($self, $app, $conf = {}) {
104 my $from = delete($conf->{from});
105 my $rr = delete($conf->{recipient_resolver}) // sub($add) {$add};
106 delete($conf->{sasl_username}) unless (defined($conf->{sasl_username}));
107 delete($conf->{sasl_password}) unless (defined($conf->{sasl_password}));
108  
109 my $transport = Email::Sender::Transport::SMTP->new($conf);
110  
111 =pod
112  
113 =head2 send_email
114  
115 Construct and send an email based on configuration and the following parameters:
116  
117 =head4 from
118  
119 Overrides configured from address (if present) for the specific email. If from
120 address was not configured at plugin registration time, this parameter is required.
121  
122 =head4 subject
123  
124 Email message subject. Defaults to empty string if not given.
125  
126 =head4 to
127  
128 =head4 cc
129  
130 =head4 bcc
131  
132 Recipient address parameters for `to`, `cc`, and `bcc`, respectively.
133 C<Mojolicious::Plugin::SendEmail> resolves all such recipients through the
134 L</recipient_resolver> function. Takes a single argument, which can be either
135 a string or an ArrayRef (which can contain other arrayrefs if the recipient
136 resolver function handles recursive resolution).
137  
138 =head4 body
139  
140 The content of the email body. Can be plain text or HTML (see L</html> for
141 details) Ignored if L</template> is given.
142  
143 =head4 template
144  
145 The name of a Mojolicious template to use for the email message body. L</body>
146 is ignored if C<template> is given. Template format is I<mail>, so, e.g.,
147 C<user/signup> would use the file C<$TEMPLATES_DIR/user/signup.mail.ep>. Parameters
148 for the template should be provided (if needed) via L</params>
149  
150 =head4 params
151  
152 A hashref of parameters to be used for template rendering. Optional. Ignored unless
153 L</template> is specified.
154  
155 =head4 html
156  
157 A boolean flag to manually set message body content type: 1 for HTML, 0 for
158 plain text. If not given, content type will be inferred automatically based on
159 the absence or presence of the string "<HTML" in the message body.
160  
161 =head4 attachments
162  
163 An ArrayRef of email attachments whose data is stored in memory. Each item may
164 either be a string, or an ArrayRef of the form [$data, $attributes] where C<$data>
165 is the attachment contents and C<$attributes> is a HashRef of additonal headers
166  
167 See L<Email::Stuffer/attach> for details.
168  
169 =head4 files
170  
171 An ArrayRef of email attachments whose data is stored on disk. Each item may
172 either be a filename, or an ArrayRef of the form [$filename, $attributes] where
173 C<$filename> is the relative or absolute path of the file to be attached and
174 C<$attributes> is a HashRef of additonal headers
175  
176 See L<Email::Stuffer/attach_file> for details.
177  
178 =cut
179  
180 $app->helper(
181 create_email => sub ($c, %args) {
182 my $mail_from = $args{from} // $from;
183 die("Can't send email: no from address given") unless ($mail_from);
184 die("Can't send email: no to address given") unless ($args{to});
185 my $mail = Email::Stuffer->new(
186 {
187 transport => $transport, # from config
188 from => $mail_from, # from config, overridable, required
189 to => $rr->($args{to}), # required
190 subject => $args{subject} // '', # optional, default empty string
191 }
192 );
193 my $unarray = sub ($x) {ref($x) eq 'ARRAY' ? $x->@* : $x};
194 $mail->cc($unarray->($rr->($args{cc}))) if ($args{cc});
195 $mail->bcc($unarray->($rr->($args{bcc}))) if ($args{bcc});
196  
197 my $body = '';
198 if ($args{template}) {
199 my $bs = $c->render_to_string(
200 format => 'mail',
201 template => $args{template},
202 ($args{params} // {})->%*
203 );
204 $body = $bs->to_string if ($bs);
205 } elsif ($args{body}) {
206 $body = $args{body};
207 }
208 $args{html} = index($body, '<html') != -1 unless (defined($args{html}));
209 if ($args{html}) {
210 $mail->html_body($body);
211 } else {
212 $mail->text_body($body);
213 }
214  
215 foreach my $header (($args{headers} // [])->@*) {
216 $mail->header($header->%*);
217 }
218  
219 foreach my $att (($args{attachments} // [])->@*) {
220 if (ref($att) eq 'ARRAY') {
221 $mail->attach($att->[0], ($att->[1] // {})->%*);
222 } else {
223 $mail->attach($att);
224 }
225 }
226  
227 foreach my $att (($args{files} // [])->@*) {
228 if (ref($att) eq 'ARRAY') {
229 $mail->attach_file($att->[0], ($att->[1] // {})->%*);
230 } else {
231 $mail->attach_file($att);
232 }
233 }
234 return $mail;
235 }
236 );
237  
238 =pod
239  
240 =head2 create_email
241  
242 Just like L</send_email> except that instead of sending the email and returning
243 the result, the unsent L<Email::Stuffer> instance is returned instead, facilitating
244 further customization, serialization, delayed sending, etc.
245  
246 =cut
247  
248 $app->helper(
249 send_email => sub($c, %args) {
250 $c->create_email(%args)->send();
251 }
252 );
253  
254 =head2 email_transport( [$transport] )
255  
256 If C<$transport> is provided, sets the email transport used for all future mail
257 sending. Must be a L<Email::Sender::Transport>. Returns the transport object.
258  
259 =cut
260  
261 $app->helper(
262 email_transport => sub ($c, $t = undef) {
263 if (defined($t)) {
264 if (_INSTANCEDOES($t, 'Email::Sender::Transport')) {
265 $transport = $t;
266 } else {
267 die("email_transport argument must be an Email::Sender::Transport instance");
268 }
269 }
270 return $transport;
271 }
272 );
273  
274 }
275  
276 =head1 AUTHOR
277  
278 Mark Tyrrell C<< <mark@tyrrminal.dev> >>
279  
280 =head1 LICENSE
281  
282 Copyright (c) 2024 Mark Tyrrell
283  
284 Permission is hereby granted, free of charge, to any person obtaining a copy
285 of this software and associated documentation files (the "Software"), to deal
286 in the Software without restriction, including without limitation the rights
287 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
288 copies of the Software, and to permit persons to whom the Software is
289 furnished to do so, subject to the following conditions:
290  
291 The above copyright notice and this permission notice shall be included in all
292 copies or substantial portions of the Software.
293  
294 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
295 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
296 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
297 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
298 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
299 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
300 SOFTWARE.
301  
302 =cut
303  
304 1;
305  
306 __END__
↑ Summary