Peace/lib/Peace/Email.pm

147 lines
3.6 KiB
Perl

package Peace::Email;
use v5.30.0;
use strict;
use warnings;
use Encode qw/decode/;
use Peace;
use Params::ValidationCompiler qw/validation_for/;
use Types::Standard qw/Str/;
use Email::MIME;
use Email::Sender::Simple;
use Email::Sender::Transport::SMTP;
sub new {
my $class = shift;
return bless {}, $class;
}
{
my $validator = validation_for(
params => {
text => { type => Str },
html => { type => Str },
to => { type => Str },
subject => { type => Str },
}
);
sub sendmail {
my $self = shift;
my %params = $validator->(@_);
my ( $text, $html, $to, $subject ) = @params{qw/text html to subject/};
my @parts = (
Email::MIME->create(
attributes => {
content_type => 'multipart/alternative',
encoding => 'base64',
},
parts => [
Email::MIME->create(
attributes => {
charset => 'UTF-8',
content_type => 'text/plain',
encoding => 'base64',
disposition => 'inline',
},
body_str => decode('utf-8', $text),
),
Email::MIME->create(
attributes => {
charset => 'UTF-8',
content_type => 'text/html',
encoding => 'base64',
disposition => 'inline',
},
body_str => decode('utf-8', $html),
)
]
)
);
my $email = Email::MIME->create(
header_str => [
From => Peace->new->peace_config->{smtp}{sasl_username},
To => $to,
Subject => $subject,
],
attributes => {
encoding => 'base64',
content_type => 'multipart/mixed'
},
parts => [@parts],
);
Email::Sender::Simple::send( 'Email::Sender::Simple', $email,
{ transport => $self->_generate_transport } );
}
}
sub _generate_transport {
my $peace_config = Peace->new->peace_config;
my $transport = Email::Sender::Transport::SMTP->new(
hosts => [ $peace_config->{smtp}{smtp_host} ],
ssl => 1,
port => $peace_config->{smtp}{smtp_port},
sasl_username => $peace_config->{smtp}{sasl_username},
sasl_password => $peace_config->{smtp}{sasl_password},
);
return $transport;
}
1;
=encoding utf8
=head1 NAME
Peace::Email - The mail sender module for Peace.
=head1 SYNOPSIS
my $mailer = Peace::Email->new;
$mailer->sendmail(
to => 'larry@perl,org',
text => 'hola',
html => '<b>hola</b>',
subject => 'Patch',
);
=head1 DESCRIPTION
Peace::Email reads the Peace config to determine the credentials
to send mail and does an abstraction around those.
=head1 INSTANCE METHODS
Peace::Email implements the following instance methods:
=head2 new
my $mailer = Peace::Email->new;
Instances a new mailer.
=head1 METHODS
Peace::Email implements the following methods:
=head2 sendmail
$mailer->sendmail(
to => 'larry@perl,org',
text => 'hola',
html => '<b>hola</b>',
subject => 'Patch',
);
Sends a mail to the given mail address.
=head1 SEE ALSO
L<Peace>
=cut