#!/usr/bin/perl -Tw

# Copyright 2000 Jason Costomiris <jcostom@jasons.org>
#
# To use this program, you'll need the following perl modules, all
# at your friendly neighborhood CPAN:
#
# Net::LDAPapi
# Net::SMTP (part of the libnet package)
# MailTools
#
# And of course, it should go without saying that you need to have a 
# working LDAP server and SMTP server.

use strict;

my $ldapserver = "dir-server";
my $mailserver = "mail-server";
my $ou = "ou=My Org Unit";
my $basedn = "o=My Org, c=US";
my $url = "ldap://$ldapserver/$ou,$basedn?mail?sub?(objectclass=inetOrgPerson)";

my @msg = <>;

my ($to, $from, $subject, $val);

use Mail::Header;
my $bar = new Mail::Header \@msg;
chomp($from = $bar->get('From') || "Anonymous");
chomp($to = $bar->get('To'));
chomp($subject = $bar->get('Subject') || "No Subject");

use Mail::Internet;
my $foo = new Mail::Internet \@msg;
# @{$foo->body} is the text of the message


use Net::LDAPapi;
my $ld = new Net::LDAPapi($ldapserver);
if ($ld->bind_s != LDAP_SUCCESS){
	$ld->perror("bind_s");
	$ld->unbind;
	die;
}

if($ld->url_search_s($url, 0) != LDAP_SUCCESS){
	$ld->perror("url_search_s");
	$ld->unbind;
	die;
}

my $entries = $ld->get_all_entries;
$ld->unbind;

use Net::SMTP;
my $smtp = new Net::SMTP($mailserver);

foreach $val (sort keys %$entries){
	$smtp->mail("broadcast");
	$smtp->to($$entries{$val}{'mail'}[0]);
	$smtp->data();
	$smtp->datasend("From: $from\n");
	$smtp->datasend("To: $to\n");
	$smtp->datasend("Subject: $subject\n\n");
	foreach (@{$foo->body}){
		$smtp->datasend($_);
	}
	$smtp->dataend();
}
$smtp->quit;
