Email.pm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package Trog::Email;
  2. use v5.36;
  3. use re '/aa';
  4. use Email::MIME;
  5. use Email::Sender::Simple;
  6. use Trog::Auth;
  7. use Trog::Log qw{:all};
  8. use Trog::Renderer;
  9. =head1 Trog::Email
  10. Sending mail out of tCMS.
  11. =head1 Termination Conditions
  12. Dies when asked to mail a user who has no contact email set on their profile.
  13. Failure to actually send is logged as FATAL rather than thrown, as by then the
  14. message has already been built and there's nothing the caller can do about it.
  15. =head1 FUNCTIONS
  16. =head2 contact(STRING user, STRING from, STRING subject, HASHREF data) = BOOL
  17. Send a templated message to a user's contact email.
  18. $data must have a 'template' key naming the template to render; everything else
  19. in it is passed through to that template as its data. The template is rendered
  20. twice, once as text and once as HTML, and both are attached to a multipart
  21. message so that the recipient's client can pick whichever it prefers.
  22. Returns 1.
  23. =cut
  24. sub contact ( $user, $from, $subject, $data ) {
  25. my $email = Trog::Auth::email4user($user);
  26. die "No contact email set for user $user!" unless $email;
  27. my $render = Trog::Renderer->render(
  28. contenttype => 'multipart/related',
  29. code => 200,
  30. template => $data->{template},
  31. data => {
  32. method => 'EMAIL',
  33. # Important - this will prevent caching
  34. route => '',
  35. %$data,
  36. },
  37. );
  38. my $text = $render->{text}[2][0];
  39. my $html = $render->{html}[2][0];
  40. my @parts = (
  41. Email::MIME->create(
  42. attributes => {
  43. content_type => "text/plain",
  44. disposition => "attachment",
  45. charset => 'UTF-8',
  46. },
  47. body => $text,
  48. ),
  49. Email::MIME->create(
  50. attributes => {
  51. content_type => "text/html",
  52. disposition => "attachment",
  53. charset => "UTF-8",
  54. },
  55. body => $html,
  56. ),
  57. );
  58. my $mail = Email::MIME->create(
  59. header_str => [
  60. From => $from,
  61. To => [$email],
  62. Subject => $subject,
  63. ],
  64. parts => \@parts,
  65. );
  66. Email::Sender::Simple->try_to_send($mail) or do {
  67. FATAL("Could not send email from $from to $email!");
  68. };
  69. return 1;
  70. }
  71. 1;