+ # If we don't have any recipients to send to, don't send a message;
+ unless ( $args{'Entity'}->head->get('To')
+ || $args{'Entity'}->head->get('Cc')
+ || $args{'Entity'}->head->get('Bcc') )
+ {
+ $RT::Logger->info( $msgid . " No recipients found. Not sending." );
+ return -1;
+ }
+
+ if ($args{'Entity'}->head->get('X-RT-Squelch')) {
+ $RT::Logger->info( $msgid . " Squelch header found. Not sending." );
+ return -1;
+ }
+
+ if ( $TransactionObj && !$TicketObj
+ && $TransactionObj->ObjectType eq 'RT::Ticket' )
+ {
+ $TicketObj = $TransactionObj->Object;
+ }
+
+ if ( RT->Config->Get('GnuPG')->{'Enable'} ) {
+ %args = WillSignEncrypt(
+ %args,
+ Attachment => $TransactionObj ? $TransactionObj->Attachments->First : undef,
+ Ticket => $TicketObj,
+ );
+ my $res = SignEncrypt( %args );
+ return $res unless $res > 0;
+ }
+
+ unless ( $args{'Entity'}->head->get('Date') ) {
+ require RT::Date;
+ my $date = RT::Date->new( RT->SystemUser );
+ $date->SetToNow;
+ $args{'Entity'}->head->set( 'Date', Encode::encode( "UTF-8", $date->RFC2822( Timezone => 'server' ) ) );
+ }
+
+ my $mail_command = RT->Config->Get('MailCommand');
+
+ if ($mail_command eq 'testfile' and not $Mail::Mailer::testfile::config{outfile}) {
+ $Mail::Mailer::testfile::config{outfile} = File::Temp->new;
+ $RT::Logger->info("Storing outgoing emails in $Mail::Mailer::testfile::config{outfile}");
+ }
+
+ # if it is a sub routine, we just return it;
+ return $mail_command->($args{'Entity'}) if UNIVERSAL::isa( $mail_command, 'CODE' );
+
+ if ( $mail_command eq 'sendmailpipe' ) {
+ my $path = RT->Config->Get('SendmailPath');
+ my @args = shellwords(RT->Config->Get('SendmailArguments'));
+
+ # SetOutgoingMailFrom and bounces conflict, since they both want -f
+ if ( $args{'Bounce'} ) {
+ push @args, shellwords(RT->Config->Get('SendmailBounceArguments'));
+ } elsif ( my $MailFrom = RT->Config->Get('SetOutgoingMailFrom') ) {
+ my $OutgoingMailAddress = $MailFrom =~ /\@/ ? $MailFrom : undef;
+ my $Overrides = RT->Config->Get('OverrideOutgoingMailFrom') || {};
+
+ if ($TicketObj) {
+ my $QueueName = $TicketObj->QueueObj->Name;
+ my $QueueAddressOverride = $Overrides->{$QueueName};
+
+ if ($QueueAddressOverride) {
+ $OutgoingMailAddress = $QueueAddressOverride;
+ } else {
+ $OutgoingMailAddress ||= $TicketObj->QueueObj->CorrespondAddress
+ || RT->Config->Get('CorrespondAddress');
+ }
+ }
+ elsif ($Overrides->{'Default'}) {
+ $OutgoingMailAddress = $Overrides->{'Default'};
+ }
+
+ push @args, "-f", $OutgoingMailAddress
+ if $OutgoingMailAddress;
+ }
+
+ # VERP
+ if ( $TransactionObj and
+ my $prefix = RT->Config->Get('VERPPrefix') and
+ my $domain = RT->Config->Get('VERPDomain') )
+ {
+ my $from = $TransactionObj->CreatorObj->EmailAddress;
+ $from =~ s/@/=/g;
+ $from =~ s/\s//g;
+ push @args, "-f", "$prefix$from\@$domain";
+ }
+
+ eval {
+ # don't ignore CHLD signal to get proper exit code
+ local $SIG{'CHLD'} = 'DEFAULT';
+
+ # if something wrong with $mail->print we will get PIPE signal, handle it
+ local $SIG{'PIPE'} = sub { die "program unexpectedly closed pipe" };
+
+ require IPC::Open2;
+ my ($mail, $stdout);
+ my $pid = IPC::Open2::open2( $stdout, $mail, $path, @args )
+ or die "couldn't execute program: $!";
+
+ $args{'Entity'}->print($mail);
+ close $mail or die "close pipe failed: $!";
+
+ waitpid($pid, 0);
+ if ($?) {
+ # sendmail exit statuses mostly errors with data not software
+ # TODO: status parsing: core dump, exit on signal or EX_*
+ my $msg = "$msgid: `$path @args` exited with code ". ($?>>8);
+ $msg = ", interrupted by signal ". ($?&127) if $?&127;
+ $RT::Logger->error( $msg );
+ die $msg;
+ }
+ };
+ if ( $@ ) {
+ $RT::Logger->crit( "$msgid: Could not send mail with command `$path @args`: " . $@ );
+ if ( $TicketObj ) {
+ _RecordSendEmailFailure( $TicketObj );
+ }
+ return 0;
+ }
+ }
+ elsif ( $mail_command eq 'smtp' ) {
+ require Net::SMTP;
+ my $smtp = do { local $@; eval { Net::SMTP->new(
+ Host => RT->Config->Get('SMTPServer'),
+ Debug => RT->Config->Get('SMTPDebug'),
+ ) } };
+ unless ( $smtp ) {
+ $RT::Logger->crit( "Could not connect to SMTP server.");
+ if ($TicketObj) {
+ _RecordSendEmailFailure( $TicketObj );
+ }
+ return 0;
+ }
+
+ # duplicate head as we want drop Bcc field
+ my $head = $args{'Entity'}->head->dup;
+ my @recipients = map $_->address, map
+ Email::Address->parse(Encode::decode("UTF-8", $head->get($_))),
+ qw(To Cc Bcc);
+ $head->delete('Bcc');
+
+ my $sender = RT->Config->Get('SMTPFrom')
+ || Encode::decode( "UTF-8", $args{'Entity'}->head->get('From') );
+ chomp $sender;
+
+ my $status = $smtp->mail( $sender )
+ && $smtp->recipient( @recipients );
+
+ if ( $status ) {
+ $smtp->data;
+ my $fh = $smtp->tied_fh;
+ $head->print( $fh );
+ print $fh "\n";
+ $args{'Entity'}->print_body( $fh );
+ $smtp->dataend;
+ }
+ $smtp->quit;
+
+ unless ( $status ) {
+ $RT::Logger->crit( "$msgid: Could not send mail via SMTP." );
+ if ( $TicketObj ) {
+ _RecordSendEmailFailure( $TicketObj );
+ }
+ return 0;
+ }
+ }
+ else {
+ local ($ENV{'MAILADDRESS'}, $ENV{'PERL_MAILERS'});
+
+ my @mailer_args = ($mail_command);
+ if ( $mail_command eq 'sendmail' ) {
+ $ENV{'PERL_MAILERS'} = RT->Config->Get('SendmailPath');
+ push @mailer_args, split(/\s+/, RT->Config->Get('SendmailArguments'));
+ }
+ else {
+ push @mailer_args, RT->Config->Get('MailParams');
+ }
+
+ unless ( $args{'Entity'}->send( @mailer_args ) ) {
+ $RT::Logger->crit( "$msgid: Could not send mail." );
+ if ( $TicketObj ) {
+ _RecordSendEmailFailure( $TicketObj );
+ }
+ return 0;
+ }
+ }
+ return 1;
+}
+
+=head2 PrepareEmailUsingTemplate Template => '', Arguments => {}
+
+Loads a template. Parses it using arguments if it's not empty.
+Returns a tuple (L<RT::Template> object, error message).
+
+Note that even if a template object is returned MIMEObj method
+may return undef for empty templates.
+
+=cut
+
+sub PrepareEmailUsingTemplate {
+ my %args = (
+ Template => '',
+ Arguments => {},
+ @_
+ );
+
+ my $template = RT::Template->new( RT->SystemUser );
+ $template->LoadGlobalTemplate( $args{'Template'} );
+ unless ( $template->id ) {
+ return (undef, "Couldn't load template '". $args{'Template'} ."'");
+ }
+ return $template if $template->IsEmpty;
+
+ my ($status, $msg) = $template->Parse( %{ $args{'Arguments'} } );
+ return (undef, $msg) unless $status;
+
+ return $template;
+}
+
+=head2 SendEmailUsingTemplate Template => '', Arguments => {}, From => CorrespondAddress, To => '', Cc => '', Bcc => ''
+
+Sends email using a template, takes name of template, arguments for it and recipients.
+
+=cut
+
+sub SendEmailUsingTemplate {
+ my %args = (
+ Template => '',
+ Arguments => {},
+ To => undef,
+ Cc => undef,
+ Bcc => undef,
+ From => RT->Config->Get('CorrespondAddress'),
+ InReplyTo => undef,
+ ExtraHeaders => {},
+ @_
+ );
+
+ my ($template, $msg) = PrepareEmailUsingTemplate( %args );
+ return (0, $msg) unless $template;
+
+ my $mail = $template->MIMEObj;
+ unless ( $mail ) {
+ $RT::Logger->info("Message is not sent as template #". $template->id ." is empty");
+ return -1;
+ }
+
+ $mail->head->set( $_ => Encode::encode( "UTF-8", $args{ $_ } ) )
+ foreach grep defined $args{$_}, qw(To Cc Bcc From);
+
+ $mail->head->set( $_ => Encode::encode( "UTF-8", $args{ExtraHeaders}{$_} ) )
+ foreach keys %{ $args{ExtraHeaders} };
+
+ SetInReplyTo( Message => $mail, InReplyTo => $args{'InReplyTo'} );
+
+ return SendEmail( Entity => $mail );
+}
+
+=head2 ForwardTransaction TRANSACTION, To => '', Cc => '', Bcc => ''
+
+Forwards transaction with all attachments as 'message/rfc822'.
+
+=cut
+
+sub ForwardTransaction {
+ my $txn = shift;
+ my %args = ( To => '', Cc => '', Bcc => '', @_ );
+
+ my $entity = $txn->ContentAsMIME;
+
+ my ( $ret, $msg ) = SendForward( %args, Entity => $entity, Transaction => $txn );
+ if ($ret) {
+ my $ticket = $txn->TicketObj;
+ my ( $ret, $msg ) = $ticket->_NewTransaction(
+ Type => 'Forward Transaction',
+ Field => $txn->id,
+ Data => join ', ', grep { length } $args{To}, $args{Cc}, $args{Bcc},
+ );
+ unless ($ret) {
+ $RT::Logger->error("Failed to create transaction: $msg");
+ }
+ }
+ return ( $ret, $msg );
+}
+
+=head2 ForwardTicket TICKET, To => '', Cc => '', Bcc => ''
+
+Forwards a ticket's Create and Correspond Transactions and their Attachments as 'message/rfc822'.
+
+=cut
+
+sub ForwardTicket {
+ my $ticket = shift;
+ my %args = ( To => '', Cc => '', Bcc => '', @_ );
+
+ my $txns = $ticket->Transactions;
+ $txns->Limit(
+ FIELD => 'Type',
+ VALUE => $_,
+ ) for qw(Create Correspond);
+
+ my $entity = MIME::Entity->build(
+ Type => 'multipart/mixed',
+ Description => 'forwarded ticket',
+ );
+ $entity->add_part( $_ ) foreach
+ map $_->ContentAsMIME,
+ @{ $txns->ItemsArrayRef };
+
+ my ( $ret, $msg ) = SendForward(
+ %args,
+ Entity => $entity,
+ Ticket => $ticket,
+ Template => 'Forward Ticket',
+ );
+
+ if ($ret) {
+ my ( $ret, $msg ) = $ticket->_NewTransaction(
+ Type => 'Forward Ticket',
+ Field => $ticket->id,
+ Data => join ', ', grep { length } $args{To}, $args{Cc}, $args{Bcc},
+ );
+ unless ($ret) {
+ $RT::Logger->error("Failed to create transaction: $msg");
+ }
+ }
+
+ return ( $ret, $msg );
+
+}
+
+=head2 SendForward Entity => undef, Ticket => undef, Transaction => undef, Template => undef, To => '', Cc => '', Bcc => ''
+
+Forwards an Entity representing Ticket or Transaction as 'message/rfc822'. Entity is wrapped into Template.
+
+=cut
+
+sub SendForward {
+ my (%args) = (
+ Entity => undef,
+ Ticket => undef,
+ Transaction => undef,
+ Template => 'Forward',
+ To => '', Cc => '', Bcc => '',
+ @_
+ );
+
+ my $txn = $args{'Transaction'};
+ my $ticket = $args{'Ticket'};
+ $ticket ||= $txn->Object if $txn;
+
+ my $entity = $args{'Entity'};
+ unless ( $entity ) {
+ require Carp;
+ $RT::Logger->error(Carp::longmess("No entity provided"));
+ return (0, $ticket->loc("Couldn't send email"));
+ }
+
+ my ($template, $msg) = PrepareEmailUsingTemplate(
+ Template => $args{'Template'},
+ Arguments => {
+ Ticket => $ticket,
+ Transaction => $txn,
+ },
+ );
+
+ my $mail;
+ if ( $template ) {
+ $mail = $template->MIMEObj;
+ } else {
+ $RT::Logger->warning($msg);
+ }
+ unless ( $mail ) {
+ $RT::Logger->warning("Couldn't generate email using template '$args{Template}'");
+
+ my $description;
+ unless ( $args{'Transaction'} ) {
+ $description = 'This is forward of ticket #'. $ticket->id;
+ } else {
+ $description = 'This is forward of transaction #'
+ . $txn->id ." of a ticket #". $txn->ObjectId;
+ }
+ $mail = MIME::Entity->build(
+ Type => 'text/plain',
+ Charset => "UTF-8",
+ Data => Encode::encode( "UTF-8", $description ),
+ );
+ }
+
+ $mail->head->set( $_ => EncodeToMIME( String => $args{$_} ) )
+ foreach grep defined $args{$_}, qw(To Cc Bcc);
+
+ $mail->make_multipart unless $mail->is_multipart;
+ $mail->add_part( $entity );
+
+ my $from;
+ unless (defined $mail->head->get('Subject')) {
+ my $subject = '';
+ $subject = $txn->Subject if $txn;
+ $subject ||= $ticket->Subject if $ticket;
+
+ unless ( RT->Config->Get('ForwardFromUser') ) {
+ # XXX: what if want to forward txn of other object than ticket?
+ $subject = AddSubjectTag( $subject, $ticket );
+ }
+
+ $mail->head->set( Subject => EncodeToMIME( String => "Fwd: $subject" ) );
+ }
+
+ $mail->head->set(
+ From => EncodeToMIME(
+ String => GetForwardFrom( Transaction => $txn, Ticket => $ticket )
+ )
+ );
+
+ my $status = RT->Config->Get('ForwardFromUser')
+ # never sign if we forward from User
+ ? SendEmail( %args, Entity => $mail, Sign => 0 )
+ : SendEmail( %args, Entity => $mail );
+ return (0, $ticket->loc("Couldn't send email")) unless $status;
+ return (1, $ticket->loc("Sent email successfully"));
+}
+
+=head2 GetForwardFrom Ticket => undef, Transaction => undef
+
+Resolve the From field to use in forward mail
+
+=cut
+
+sub GetForwardFrom {
+ my %args = ( Ticket => undef, Transaction => undef, @_ );
+ my $txn = $args{Transaction};
+ my $ticket = $args{Ticket} || $txn->Object;
+
+ if ( RT->Config->Get('ForwardFromUser') ) {
+ return ( $txn || $ticket )->CurrentUser->EmailAddress;