#!/usr/bin/perl -w

# Send mail with attachment 
# Use only standard perl modules (Linux, AIX, Solaris ?, ..)
# Bruno Bonfils, <asyd@debian-fr.org>
# January 2005

use strict;
use MIME::Base64;
use Getopt::Long;
use Pod::Usage;

# configure
my $boundary = '=-=-=';
my $sendmail = '/usr/lib/sendmail';

my $from = 'noreply@domain.com';
my $to;
my $file;
my $subject;

my $result = GetOptions("to=s" => \$to,
                        "file=s" => \$file,
                        "from=s" => \$from,
                        "subject=s" => \$subject);

if (not defined $to or not defined $file or not defined $subject) {
   pod2usage(1);
}

# sub functions
sub print_boundary {
	my ($start,$end) = @_;
	return "$start--$boundary" . $end . "\n";
}

# Internal variables

# Mail Headers
my %mailh = ( From    => $from,
              To      => $to,
              Subject => $subject,
              'Content-Type' => 'multipart/mixed; boundary="'. $boundary .'"');

my $base64 = '';

# extract the filename
my $filename = [split ('/', $file)]->[-1];
# extract the extension
my $ext = [split (m#\.#, $filename)]->[-1];

# Content-Type: Plain text by default
my $content = 'text/plain';

if ($ext eq 'pdf') {
	$content = 'application/pdf';
}

my $buffer;

# Note : (from perldoc MIME::Base64)
# This ensures that the base64 lines line up and that you do not end up with
# padding in the middle. 57 bytes of data fills one complete base64 line (76 ==
# 57*4/3)
open (FH, "< $file")
	or die "Can't open $file for reading, $!";
while(read(FH,$buffer, 60*57)) {
	$base64 .= encode_base64($buffer);
}
close (FH);

# Open the sendmail pipe 

open (SENDMAIL, "| $sendmail " . $mailh{'To'})
	or die "Can't open sendmail, $!";

# Print Mail Headers
foreach my $header (keys %mailh) {
	print SENDMAIL "$header: " . $mailh{$header} . "\n";
}

# Print Mail Content
print SENDMAIL print_boundary("\n");
print SENDMAIL "\n";
while (<>) {
	print SENDMAIL $_;
}
print SENDMAIL "\n" . print_boundary("\n");

# Attach the file
print SENDMAIL "Content-Type: $content\n";
print SENDMAIL "Content-Disposition: attachment; filename=$filename\n";
print SENDMAIL "Content-Transfer-Encoding: base64\n\n";
print SENDMAIL $base64;
print SENDMAIL print_boundary(undef,"--");

# end of message
print SENDMAIL "\n\n";

close (SENDMAIL);

__END__

=head1 NAME

sendmail.pl

 Send a single to a single recipient (Using sendmail command line)

=head1 SYNOPSIS

sendmail.pl [options]

 Options:
  --from     From
  --to       To (required)
  --subject  Subject (required)
  --file     File to attach (required)

=head1 Example

./sendmail.pl --to asyd@debian-fr.org --file asyd.pdf --subject "asyd's cv"
