]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Mail.pm
fix mistake in the import options of POSIX
[debbugs.git] / Debbugs / Mail.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later
3 # version at your option.
4 # See the file README and COPYING for more information.
5 #
6 # Copyright 2004-7 by Don Armstrong <don@donarmstrong.com>.
7
8 package Debbugs::Mail;
9
10 =head1 NAME
11
12 Debbugs::Mail -- Outgoing Mail Handling
13
14 =head1 SYNOPSIS
15
16 use Debbugs::Mail qw(send_mail_message get_addresses);
17
18 my @addresses = get_addresses('blah blah blah foo@bar.com')
19 send_mail_message(message => <<END, recipients=>[@addresses]);
20 To: $addresses[0]
21 Subject: Testing
22
23 Testing 1 2 3
24 END
25
26 =head1 EXPORT TAGS
27
28 =over
29
30 =item :all -- all functions that can be exported
31
32 =back
33
34 =head1 FUNCTIONS
35
36
37 =cut
38
39 use warnings;
40 use strict;
41 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
42 use base qw(Exporter);
43
44 use IPC::Open3;
45 use POSIX qw(:sys_wait_h strftime);
46 use Time::HiRes qw(usleep);
47 use Mail::Address ();
48 use Debbugs::MIME qw(encode_rfc1522);
49 use Debbugs::Config qw(:config);
50 use Params::Validate qw(:types validate_with);
51
52 BEGIN{
53      ($VERSION) = q$Revision: 1.1 $ =~ /^Revision:\s+([^\s+])/;
54      $DEBUG = 0 unless defined $DEBUG;
55
56      @EXPORT = ();
57      @EXPORT_OK = qw(send_mail_message get_addresses encode_headers rfc822_date);
58      $EXPORT_TAGS{all} = [@EXPORT_OK];
59
60 }
61
62 # We set this here so it can be overridden for testing purposes
63 our $SENDMAIL = $config{sendmail};
64
65 =head2 get_addresses
66
67      my @addresses = get_addresses('don@debian.org blars@debian.org
68                                     kamion@debian.org ajt@debian.org');
69
70 Given a string containing some e-mail addresses, parses the string
71 using Mail::Address->parse and returns a list of the addresses.
72
73 =cut
74
75 sub get_addresses {
76      return map { $_->address() } map { Mail::Address->parse($_) } @_;
77 }
78
79
80
81 =head2 send_mail_message
82
83      send_mail_message(message    => $message,
84                        recipients => [@recipients],
85                        envelope_from => 'don@debian.org',
86                       );
87
88
89 =over
90
91 =item message -- message to send out
92
93 =item recipients -- recipients to send the message to. If undefed or
94 an empty arrayref, will use '-t' to parse the message for recipients.
95
96 =item envelope_from -- envelope_from for outgoing messages
97
98 =item encode_headers -- encode headers using RFC1522 (default)
99
100 =item parse_for_recipients -- use -t to parse the message for
101 recipients in addition to those specified. [Can be used to set Bcc
102 recipients, for example.]
103
104 =back
105
106 Returns true on success, false on failures. All errors are indicated
107 using warn.
108
109 =cut
110
111 sub send_mail_message{
112      my %param = validate_with(params => \@_,
113                                spec  => {sendmail_arguments => {type => ARRAYREF,
114                                                                 default => [qw(-odq -oem -oi)],
115                                                                },
116                                          parse_for_recipients => {type => BOOLEAN,
117                                                                   default => 0,
118                                                                  },
119                                          encode_headers       => {type => BOOLEAN,
120                                                                   default => 1,
121                                                                  },
122                                          message              => {type => SCALAR,
123                                                                  },
124                                          envelope_from        => {type => SCALAR,
125                                                                   optional => 1,
126                                                                  },
127                                          recipients           => {type => ARRAYREF|UNDEF,
128                                                                   optional => 1,
129                                                                  },
130                                         },
131                               );
132      my @sendmail_arguments = qw(-odq -oem -oi);
133      push @sendmail_arguments, '-f', $param{envelope_from} if exists $param{envelope_from};
134
135      my @recipients;
136      @recipients = @{$param{recipients}} if defined $param{recipients} and
137           ref($param{recipients}) eq 'ARRAY';
138      my %recipients;
139      @recipients{@recipients} = (1) x @recipients;
140      @recipients = keys %recipients;
141      # If there are no recipients, use -t to parse the message
142      if (@recipients == 0) {
143           $param{parse_for_recipients} = 1 unless exists $param{parse_for_recipients};
144      }
145      # Encode headers if necessary
146      $param{encode_headers} = 1 if not exists $param{encode_headers};
147      if ($param{encode_headers}) {
148           $param{message} = encode_headers($param{message});
149      }
150
151      # First, try to send the message as is.
152      eval {
153           _send_message($param{message},
154                         @sendmail_arguments,
155                         $param{parse_for_recipients}?q(-t):(),
156                         @recipients);
157      };
158      return 1 unless $@;
159      # If there's only one recipient, there's nothing more we can do,
160      # so bail out.
161      warn $@ and return 0 if $@ and @recipients == 0;
162      # If that fails, try to send the message to each of the
163      # recipients separately. We also send the -t option separately in
164      # case one of the @recipients is ok, but the addresses in the
165      # mail message itself are malformed.
166      my @errors;
167      for my $recipient ($param{parse_for_recipients}?q(-t):(),@recipients) {
168           eval {
169                _send_message($param{message},@sendmail_arguments,$recipient);
170           };
171           push @errors, "Sending to $recipient failed with $@" if $@;
172      }
173      # If it still fails, complain bitterly but don't die.
174      warn join(qq(\n),@errors) and return 0 if @errors;
175      return 1;
176 }
177
178 =head2 encode_headers
179
180      $message = encode_heeaders($message);
181
182 RFC 1522 encodes the headers of a message
183
184 =cut
185
186 sub encode_headers{
187      my ($message) = @_;
188
189      my ($header,$body) = split /\n\n/, $message, 2;
190      $header = encode_rfc1522($header);
191      return $header . qq(\n\n). $body;
192 }
193
194 =head2 rfc822_date
195
196      rfc822_date
197
198 Return the current date in RFC822 format in the UTC timezone
199
200 =cut
201
202 sub rfc822_date{
203      return scalar strftime "%a, %d %h %Y %T +0000", gmtime;
204 }
205
206 =head1 PRIVATE FUNCTIONS
207
208 =head2 _send_message
209
210      _send_message($message,@sendmail_args);
211
212 Private function that actually calls sendmail with @sendmail_args and
213 sends message $message.
214
215 dies with errors, so calls to this function in send_mail_message
216 should be wrapped in eval.
217
218 =cut
219
220 sub _send_message{
221      my ($message,@sendmail_args) = @_;
222
223      my ($wfh,$rfh);
224      my $pid = open3($wfh,$rfh,$rfh,$SENDMAIL,@sendmail_args)
225           or die "Unable to fork off $SENDMAIL: $!";
226      local $SIG{PIPE} = 'IGNORE';
227      eval {
228           print {$wfh} $message or die "Unable to write to $SENDMAIL: $!";
229           close $wfh or die "$SENDMAIL exited with $?";
230      };
231      if ($@) {
232           local $\;
233           # Reap the zombie
234           waitpid($pid,WNOHANG);
235           # This shouldn't block because the pipe closing is the only
236           # way this should be triggered.
237           my $message = <$rfh>;
238           die "$@$message";
239      }
240      # Wait for sendmail to exit for at most 30 seconds.
241      my $loop = 0;
242      while (waitpid($pid, WNOHANG) == 0 or $loop++ >= 600){
243           # sleep for a 20th of a second
244           usleep(50_000);
245      }
246      if ($loop >= 600) {
247           warn "$SENDMAIL didn't exit within 30 seconds";
248      }
249 }
250
251
252 1;
253
254
255 __END__
256
257
258
259
260
261