Email.pm 2.4 KB

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