MyRedland/lib/MyRedland/Mail.pm

118 lines
2.9 KiB
Perl

package MyRedland::Mail;
use v5.34.1;
use strict;
use warnings;
use Mojolicious;
use Encode qw/decode/;
use Moo;
use Types::Standard qw/InstanceOf Str/;
use Params::ValidationCompiler qw/validation_for/;
use Email::MIME;
use Email::Sender::Simple;
use Email::Sender::Transport::SMTP;
has app => (
is => 'ro',
isa => InstanceOf ['Mojolicious'],
);
has _config => ( is => 'lazy', );
has _transport => ( is => 'lazy', );
sub _build__config {
my $self = shift;
my $app = $self->app;
if ( defined $app->config->{smtp} ) {
return $app->config->{smtp};
}
return;
}
sub _build__transport {
my $self = shift;
my $smtp_config = $self->_config;
if ( !$smtp_config ) {
die "Unable to build transport due the lack of related config.";
}
my %options = %$smtp_config;
delete $options{From};
my $tranport = Email::Sender::Transport::SMTP->new(%$smtp_config);
return $tranport;
}
{
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 $transport = $self->_transport;
my $from = $self->_config->{From};
my ( $text, $html, $to, $subject ) = @params{qw/text html to subject/};
my @parts = (
Email::MIME->create(
attributes => {
charset => 'UTF-8',
content_type => 'text/plain',
encoding => 'base64',
disposition => 'inline',
},
body_str => $text,
),
Email::MIME->create(
attributes => {
charset => 'UTF-8',
content_type => 'text/html',
encoding => 'base64',
disposition => 'inline',
},
body_str => $html,
),
);
my $email = Email::MIME->create(
header_str => [
From => $from,
to => $to,
subject => $subject,
],
attributes => {
encoding => 'base64',
content_type => 'multipart/mixed',
},
parts => [
Email::MIME->create(
attributes => {
content_type => 'multipart/alternative',
encoding => 'base64',
},
parts => [ @parts, ],
)
]
);
eval {
Email::Sender::Simple->send( $email, { transport => $self->_transport });
};
if ($@) {
warn $@;
return 0;
}
return 1;
}
}
1;