]> git.donarmstrong.com Git - bin.git/blob - delay_mail
should be /m when testing for subject
[bin.git] / delay_mail
1 #! /usr/bin/perl
2 # delay_mail delays mail and requeus it, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2006 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 495 2006-08-10 08:02:01Z don $
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 =head1 NAME
16
17 delay_mail - Delay mail to a specific time and send it back
18
19 =head1 SYNOPSIS
20
21  delay_mail [options] < mail_message
22
23  Options:
24   --enqueue enqueues a message for sending out later
25   --delay length of delay (suitable for passing to at)
26   --email pull delay out from email address
27   --list list emails in queue
28   --queue directory to use as a queue
29   --process sends out a specific message that was enqueued
30   --debug, -d debugging level (Default 0)
31   --help, -h display this help
32   --man, -m display manual
33
34 =head1 OPTIONS
35
36 =over
37
38 =item B<--enqueue>
39
40 Enqueue a message which should be sent out later
41
42 =item B<--delay>
43
44 Length of delay (man at for details of specification)
45
46 =item B<--email>
47
48 The delay option is actually an email address; apply the following
49 regex to parse it:
50
51     $delay =~ m/[+-]d(?:ela?y?)?[-+]([^\@]+)/;
52     $delay = $1; $delay =~ s/_/ /;
53
54 Thus, foo-delay-now+5_min@bar.baz becomes now+5 min
55
56 =item B<--list>
57
58 List entries which are in the queue
59
60 =item B<--dequeue>
61
62 Delete an entry from the queue
63
64 =item B<--mailto>
65
66 Who to mail the delayed mail to
67
68 =item B<--queue>
69
70 The queue directory to use; defaults to ~/.delay_mail_queue
71
72 =item B<--process>
73
74 Process a specific entry in the queue (this is called by at at the
75 appropriate time; you shouldn't need call it manually.)
76
77 =item B<--debug, -d>
78
79 Debug verbosity. (Default 0)
80
81 =item B<--help, -h>
82
83 Display brief useage information.
84
85 =item B<--man, -m>
86
87 Display this manual.
88
89 =back
90
91 =head1 EXAMPLES
92
93
94 =cut
95
96
97 use vars qw($DEBUG);
98
99 my %options = (debug           => 0,
100                help            => 0,
101                man             => 0,
102                email           => 0,
103               );
104
105 GetOptions(\%options,'debug|d+','help|h|?','man|m',
106            'list|l','dequeue=s','process|p=s','enqueue|e',
107            'delay|D=s','email|E',
108            'mailto|mail-to|M=s',
109           );
110
111 pod2usage() if $options{help};
112 pod2usage({verbose=>2}) if $options{man};
113
114 $DEBUG = $options{debug};
115
116 use List::Util qw(sum);
117 use MIME::WordDecoder;
118 use IO::File;
119 use IO::Dir;
120
121 my $ERROR = '';
122 if (1 < grep {exists $options{$_}} qw(enqueue list process dequeue)) {
123      $ERROR .= "Exactly one of --enque, --list, --process, or --dequeue must be specified\n";
124 }
125 if (not $options{enqueue} and ($options{email} or exists $options{delay})) {
126      $ERROR .= "Setting email or delay is nonsensical unless enqueuing\n";
127 }
128
129 pod2usage($ERROR) if length $ERROR;
130
131 # create queue directory if it doesn't already exist
132 if (not exists $options{queue}) {
133      $options{queue} = "$ENV{HOME}/.delay_mail_queue";
134 }
135 if (not -d $options{queue}) {
136      mkdir($options{queue}) or
137           die "Unable to create queue directory $options{queue}: $!";
138 }
139
140 if (not exists $options{mailto}) {
141      if (exists $ENV{EMAIL}) {
142           $options{mailto} = $ENV{EMAIL};
143      }
144      elsif (exists $ENV{USER}) {
145           $options{mailto} = $ENV{USER};
146      }
147      else {
148           $options{mailto} = qx(id -nu);
149      }
150 }
151 $options{mailto} =~ s/\n//g;
152
153 if (exists $options{enqueue}) {
154      # parse delay
155      my $delay = $options{delay};
156      $delay =~ s/\n//g;
157      if ($options{email}) {
158           $delay =~ m/[+-]d(?:ela?y?)?[-+]([^\@]+)/;
159           $delay = $1; $delay =~ s/_/ /;
160      }
161      # slurp email
162      local $/;
163      my $email = <STDIN>;
164      # rip subject out of email
165      # we cheat for now; this isn't correct at all.
166      my ($subject) = $email =~ /^Subject:\s*(.+)/mi;
167      $subject = decode_rfc1522($subject);
168      $subject =~ s/\n//g;
169      # create a queue entry
170      my $queue_fn = time . $$;
171      my $q_fh = IO::File->new("$options{queue}/$queue_fn",'w') or
172           die "Unable to open $options{queue}/$queue_fn for writing";
173      print {$q_fh} "delay: $delay\n";
174      print {$q_fh} "mailto: $options{mailto}\n";
175      print {$q_fh} "entry: $queue_fn\n";
176      print {$q_fh} "subject: $subject\n";
177      print {$q_fh} "#####\n";
178      print {$q_fh} $email;
179      my $at_fh;
180      open($at_fh,'|-','at',$delay) or exit 1;
181      print {$at_fh} "$0 '--queue' '$options{queue}' '--process' '$queue_fn';\n";
182      close $at_fh;
183      waitpid(-1,0);
184      exit $?;
185 }
186 elsif ($options{list}) {
187      my $dir = IO::Dir->new($options{queue}) or
188           die "Unable to list contents of $options{queue}: $!";
189      my $entry;
190      my @queue;
191      while (defined($entry = $dir->read)) {
192           #valid queue entries are entirely numeric
193           print STDERR "Dealing with $entry\n" if $DEBUG;
194           last if not defined $entry;
195           next if $entry !~ /^\d+$/;
196           # they're also just readable files
197           next if not -f "$options{queue}/$entry" or not -r "$options{queue}/$entry";
198           print STDERR "Still dealing with $entry\n" if $DEBUG;
199           push @queue,parse_queue_entry($entry);
200      }
201      for my $q_e (@queue) {
202           print "$q_e->{entry}: send $q_e->{subject} to $q_e->{mailto} at $q_e->{delay}\n";
203      }
204 }
205 elsif ($options{dequeue}) {
206      if (-e "$options{queue}/$options{dequeue}") {
207           unlink("$options{queue}/$options{dequeue}") or
208                die "Unable to unlink $options{queue}/$options{dequeue}";
209      }
210      else {
211           print STDERR "$options{queue}/$options{dequeue} doesn't exist\n"
212      }
213 }
214 elsif ($options{process}) {
215      my $q_e;
216      if (-e "$options{queue}/$options{process}") {
217           my $q_e = parse_queue_entry($options{process});
218           if (not defined $q_e) {
219                die "Unable to parse $options{process}";
220           }
221           # munge the message id
222           my ($message_id) = $q_e->{email} =~ m/^Message-Id:\s*(.+)/;
223           if (not $message_id =~ s/\@/delay$q_e->{entry}@/){
224                $message_id =~ s/(\w)/delay$q_e->{entry}$1/;
225           }
226           $q_e->{email} =~ s/^(Message-Id:\s*)(.+)/$1$message_id/;
227           # send the message
228           my $sendmail_fh;
229           open($sendmail_fh,'|-','/usr/sbin/sendmail',$q_e->{mailto}) or
230                die "Unable to open sendmail to send message";
231           print {$sendmail_fh} $q_e->{email};
232           close($sendmail_fh);
233           waitpid(-1,0);
234           if ($?) {
235                print STDERR "Sendmail failed with $?\n";
236                exit $?;
237           }
238           unlink("$options{queue}/$options{process}");
239      }
240      else {
241           print STDERR "$options{queue}/$options{process} doesn't exist\n"
242      }
243 }
244
245
246 sub parse_queue_entry{
247      my ($entry) = @_;
248
249      my $entry_fh = IO::File->new("$options{queue}/$entry",'r') or
250           return undef;
251      my $queue_entry = {};
252      while (<$entry_fh>) {
253           last if /^#####/;
254           chomp;
255           my $line = $_;
256           my ($key,$value) = split /: /, $line,2;
257           $queue_entry->{$key} = $value;
258      }
259      local $/;
260      $queue_entry->{email} = <$entry_fh>;
261      return $queue_entry;
262 }
263
264
265 # These functions below I've jacked from Debbugs::MIME which I also
266 # wrote; probably should put them somewhere else eventually.
267
268 sub convert_to_utf8 {
269      my ($data, $charset) = @_;
270      # raw data just gets returned (that's the charset WordDecorder
271      # uses when it doesn't know what to do)
272      return $data if $charset eq 'raw' or is_utf8($data,1);
273      my $result;
274      eval {
275           # this encode/decode madness is to make sure that the data
276           # really is valid utf8 and that the is_utf8 flag is off.
277           $result = encode("utf8",decode($charset,$data))
278      };
279      if ($@) {
280           warn "Unable to decode charset; '$charset' and '$data': $@";
281           return $data;
282      }
283      return $result;
284 }
285
286
287 BEGIN {
288     # Set up the default RFC1522 decoder, which turns all charsets that
289     # are supported into the appropriate UTF-8 charset.
290     MIME::WordDecoder->default(new MIME::WordDecoder(
291         ['*' => \&convert_to_utf8,
292         ]));
293 }
294
295 sub decode_rfc1522
296 {
297     my ($string) = @_;
298
299     # this is craptacular, but leading space is hacked off by unmime.
300     # Save it.
301     my $leading_space = '';
302     $leading_space = $1 if $string =~ s/^(\s+)//;
303     # unmime calls the default MIME::WordDecoder handler set up at
304     # initialization time.
305     return $leading_space . MIME::WordDecoder::unmime($string);
306 }
307
308
309
310 __END__
311
312