File: send-reminders

package info (click to toggle)
email-reminder 0.7.8-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 744 kB
  • ctags: 154
  • sloc: perl: 2,302; xml: 112; sh: 75; makefile: 11
file content (355 lines) | stat: -rwxr-xr-x 11,069 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/perl -T

=head1 NAME

Send-reminders - send email reminders for special occasions

=head1 SYNOPSIS

Send emails reminders set by users for special occasions.

=head1 DESCRIPTION

Email-reminder allows users to define events that they want to be
reminded of by email.  Possible events include birthdays,
anniversaries and yearly events.  Reminders can be sent on the day of
the event and a few days beforehand.

This script is meant to be invoked everyday by a cron job.  It mails
the actual reminders out.

When run by the root user, it processes all of the spooled reminders.
When run by a specific user, it only processes reminders set by that
user.

=head1 OPTIONS

=over 6

=item B<--help>

Displays basic usage message.

=item B<--simulate>

Does not actually send any emails out.

=item B<--verbose>

Prints out information about what the program is doing, including the
full emails being sent out.

=item B<--version>

Displays the version number.

=back

=head1 FILES

F<~/.email-reminders>, F</etc/email-reminder.conf>

=head1 AUTHOR

Francois Marier <francois@fmarier.org>

=head1 SEE ALSO

email-reminder-editor, collect-reminders

=head1 COPYRIGHT

Copyright (C) 2004-2014 by Francois Marier

Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.

Email-Reminder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.

=cut

use strict;
use warnings;

use Encode;
use Getopt::Long;
use MIME::Base64;
use MIME::QuotedPrint;
use Pod::Usage;

use EmailReminder::EventList;
use EmailReminder::Utils;
use Date::Manip qw(ParseDate UnixDate);

# Default preferences
my $PREFERENCE_FILE = '/etc/email-reminder.conf';
my %preferences;
$preferences{"send_reminders"}   = 1;
$preferences{"smtp_server"}      = 'localhost';
$preferences{"smtp_ssl"}         = 0;
$preferences{"smtp_username"}    = '';
$preferences{"smtp_password"}    = '';
$preferences{"mail_from"}        = 'root@localhost';
read_config(); 

# Global variables
my $user_fname;
my $user_lname;

# Command-line parameters
my $verbose  = 0;
my $simulate = 0;
my $version  = 0;
my $help  = 0;
GetOptions( "verbose"  => \$verbose,
            "simulate" => \$simulate,
            "version"  => \$version,
            "help"     => \$help,
    );

# Override preferences with system values
sub read_config
{
    print "Reading preferences from '$PREFERENCE_FILE'\n" if $verbose;

    if (open my $config_fh, '<', $PREFERENCE_FILE) {
        # Stolen off of the Cookbook (section 8.16)
        while (<$config_fh>) {
            chomp;                  # no newline
            s/#.*//;                # no comments
            s/^\s+//;               # no leading white
            s/\s+$//;               # no trailing white
            next unless length;     # anything left?
            my ($var, $value) = split(/\s*=\s*/, $_, 2);
            $value = 1 if $value eq 'true' or $value eq 'yes';
            $value = 0 if $value eq 'false' or $value eq 'no';
            $preferences{$var} = $value;
        }
        close $config_fh;
    }
    else {
        print "Warning: cannot read configuration file at $PREFERENCE_FILE.\nMake sure that the user running $0 has read permissions on that configuration file.\n";
        return;
    }
    return 1;
}

sub send_email
{
    my $message = shift;
    my $subject = shift;
    my $user_name = shift;
    my $user_email = shift;

    unless ($user_email) {
        return 0;
    }

    my $to = $user_email;
    $to = "$user_name <$user_email>" if ($user_name);

    print "--> Emailing '$to':\n".encode("UTF-8", $subject."\n\n".$message) if $verbose;
    
    unless ($simulate) {
        my $smtp_server = '';
        if ($preferences{"smtp_server"} =~ /^([A-Za-z_0-9\-\/.]+)$/) {
            $smtp_server = $1;
        }
        my $smtp = undef;
        if ($preferences{"smtp_ssl"}) {
            eval 'use Net::SMTP::SSL';
            die "Couldn't load module : $!" if ($@);
            $smtp = Net::SMTP::SSL->new($smtp_server, Port => 465, Debug => 0);
        }
        else {
            use Net::SMTP;
            $smtp = Net::SMTP->new($smtp_server, Debug => 0);
        }
        die "Error: couldn't connect to server '$smtp_server'\n" unless $smtp;

        # SMTP SASL authentication (if necessary)
        if ($preferences{"smtp_username"} and $preferences{"smtp_password"}) {
            unless ($smtp->auth($preferences{"smtp_username"}, $preferences{"smtp_password"})) {
                die "Error: authentication with the SMTP server failed with error code ".$smtp->status."\n";
            }
        }

        unless ($smtp->mail($preferences{"mail_from"})) {
            die "Error: the sending address was not accepted. Try setting the 'mail_from' variable to a valid email address in the configuration file\n";
        }

        my $ok = 1;
        $ok = $ok && $smtp->to($to);
        $ok = $ok && $smtp->data();
        $ok = $ok && $smtp->datasend("From: Email-Reminder <" . $preferences{"mail_from"} . ">\n");
        
        # Create an RFC822 compliant date (current time)
        my $rfc822_format = "%a, %d %b %Y %H:%M %z";
        my $today         = ParseDate("Now");
        my $rfc822_date = UnixDate($today,$rfc822_format);
        $ok = $ok && $smtp->datasend("Date: $rfc822_date\n");
        
        $ok = $ok && $smtp->datasend("To: $to\n");
        $ok = $ok && $smtp->datasend("Subject: =?utf-8?B?".encode_base64(encode("UTF-8", $subject), '')."?=\n");
        $ok = $ok && $smtp->datasend("Mime-Version: 1.0\n");
        $ok = $ok && $smtp->datasend("Content-Type: text/plain; charset=utf-8\n");
        $ok = $ok && $smtp->datasend("Content-Disposition: inline\n");
        $ok = $ok && $smtp->datasend("Content-Transfer-Encoding: quoted-printable\n");
        $ok = $ok && $smtp->datasend("\n");
        $ok = $ok && $smtp->datasend(encode_qp(encode("UTF-8", $message)));
        $ok = $ok && $smtp->dataend();

        $smtp->quit();

        die "Error: could not mail the reminder out\n" unless $ok;
    }

    return 1;
}

sub process_file
{
    my $file = shift;

    print "==> Processing $file\n" if $verbose;

    my $list = EmailReminder::EventList->new($file);

    my @fullname = $list->get_user_name();
    my $user_fname = $fullname[0];
    my $user_lname = $fullname[1];
    my $user_name = $user_fname;
    $user_name .= " " . $user_lname if defined($user_lname);
    my $user_email = $list->get_user_email();

    foreach my $event ($list->get_events()) {
        print '--> Processing event '.$event->get_name()."\n" if $verbose;

        if ($event->is_occurring()) {
            print '--> Event '.$event->get_name()." is occurring\n" if $verbose;

            eval {
                if (!process_event($event, $user_name, $user_email)) {
                    return;
                }
            };
            if($@) {
                print '!!! Error while sending reminder for '.$event->get_name()."\n" if $verbose;

                my $msg = 'WARNING: Due to an error, the email reminder for Event "' . $event->get_name() .
                    '" cannot be processed and all I could do was to let you know that there was a problem.';
                $msg .= "\n\n".'Since this event is OCCURRING TODAY, you should really check your reminders manually.';
                $msg .= "\n\n".'Please forward this email to the email-reminder author so that this problem can be fixed in future versions:';
                $msg .= "\n\n".'  Francois Marier <francois@fmarier.org>';
                $msg .= "\n\n".'Thanks!';
                $msg .= "\n\n--------------------------------------------------------------";
                $msg .= EmailReminder::Utils::debug_info($event, 2);
                my $subject = 'Email-reminder ERROR: ' . $event->get_name();

                if (!send_email($msg, $subject, $user_name, $user_email)) {
                    return;
                }
            }
        }
    }

    return 1;
}

# Send reminders for an event which is occurring
sub process_event
{
    my $event = shift;
    my $user_name = shift;
    my $user_email = shift;

    my $subject = $event->get_subject();

    my @recipients = @{$event->get_recipients()};
    if ($#recipients > -1) {
        foreach my $recipient (@recipients) {
            my $recipient_email = shift @{$recipient};
            my $recipient_fname = shift @{$recipient};
            my $recipient_lname = shift @{$recipient};

            my $recipient_name = $recipient_fname;
            $recipient_name .= " $recipient_lname" if defined($recipient_lname);

            my $msg = $event->get_message($recipient_fname);
            if ($msg && !send_email($msg, $subject, $recipient_name, $recipient_email)) {
                return;
            }
        }
    } else {
        my $msg = $event->get_message($user_fname);
        if ($msg && !send_email($msg, $subject, $user_name, $user_email)) {
            return;
        }
    }
}

sub main
{
    my $running_uid = $>;
    if (0 == $running_uid) {
        print STDERR "Warning: for security reasons, this script should not be not as root.\n";
    }

    my $spool_dir = $EmailReminder::Utils::SPOOL_DIRECTORY;
    if (-w $spool_dir) {
        # Iterate through all spooled files
        while (defined(my $file = glob("$spool_dir/*"))) {
            # Untaint filename
            if ($file =~ /^([A-Za-z_0-9\-\/]+)$/) {
                $file = $1;
            } else {
                print STDERR "Skipped unclean filename" if $verbose;
                next;
            }

            unless (process_file($file, 0, 1)) {
                return;
            }

            # Delete the file once we're done with it
            unless (unlink($file)) {
                print STDERR "Could not remove $file.\n" if $verbose;
            }
        }
        return 1;
    } else {
        # Normal users only get to test their own reminders
        my @pwinfo = getpwuid($>);
        my $homedir = $pwinfo[7];
        my $file = "$homedir/" . $EmailReminder::Utils::USER_CONFIG_FILE;

        if (-e $file) {
            return process_file($file, 0, 1);
        } else {
            print STDERR "Warning: could not find your .email-reminders file.\n";
            return;
        }
    }
}

if ($help || $version) {
    print "send-reminders $EmailReminder::Utils::VERSION\n";
    if ($help) {
        print "\n";
        pod2usage(1);
    }
} elsif ($preferences{"send_reminders"}) {
    unless (main()) {
        print STDERR "Could not send reminders.\n";
    }
}