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