Email.pm 2.3 KB

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