1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package MyApp::Mailer;
use Moo;
use Email::MIME;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP;
use Template;
has smtp_host => (is => 'ro', required => 1);
has smtp_port => (is => 'ro', default => 587);
has smtp_username => (is => 'ro', required => 1);
has smtp_password => (is => 'ro', required => 1);
has from_address => (is => 'ro', required => 1);
has transport => (is => 'lazy');
has template => (is => 'lazy');
sub _build_transport {
my $self = shift;
Email::Sender::Transport::SMTP->new({
host => $self->smtp_host,
port => $self->smtp_port,
sasl_username => $self->smtp_username,
sasl_password => $self->smtp_password,
ssl => 'starttls',
});
}
sub _build_template {
Template->new;
}
sub send_template_email {
my ($self, %args) = @_;
my $to = $args{to} or die "to is required";
my $subject = $args{subject} or die "subject is required";
my $template = $args{template} or die "template is required";
my $vars = $args{vars} || {};
# テンプレート処理
my $body;
$self->template->process(\$template, $vars, \$body)
or die $self->template->error;
# メール作成
my $email = Email::MIME->create(
header_str => [
To => $to,
From => $self->from_address,
Subject => $subject,
],
attributes => {
content_type => 'text/plain',
charset => 'UTF-8',
},
body_str => $body,
);
# 送信
eval {
sendmail($email, { transport => $self->transport });
};
if ($@) {
warn "Failed to send email: $@";
return 0;
}
return 1;
}
# 使用例
package main;
my $mailer = MyApp::Mailer->new(
smtp_host => 'smtp.example.com',
smtp_username => 'user',
smtp_password => 'pass',
from_address => 'noreply@example.com',
);
my $template = <<'TMPL';
こんにちは、[% name %]さん
あなたの申し込みを受け付けました。
ID: [% user_id %]
よろしくお願いします。
TMPL
$mailer->send_template_email(
to => 'user@example.com',
subject => '登録完了',
template => $template,
vars => { name => '山田太郎', user_id => 12345 },
);
|