Email script using a groups file for the To: addresses

Group file

groups_file.xml

<notif_grps>
    <notifs>
        <email>joe@example.com</email>
        <email>sally@example.com</email>
        <email>mark@example.com</email>
    </notifs>
</notif_grps>

Email script

#!/usr/local/bin/perl

use strict;
use warnings;

use XML::Simple;
use Data::Dumper;
use Mail::Sendmail;
use Email::Valid;

my $xml = new XML::Simple (ForceArray=>1);
my $xml_data = $xml->XMLin("path/to/groups_file.xml");

sub trim($)
{
	my $str = shift;
	$str =~ s/^\s+//;
	$str =~ s/\s+$//;
	return $str;
}

### Usage: get_group_emails("notification_group","path/to/group/email/file");
### Returns: A comma delimited list of email addresses.
sub get_group_emails
{
	my($notif_group,$notif_group_file) = @_;

	my $xml = new XML::Simple (ForceArray=>1);
	if(-e $notif_group_file)
	{
		my $xml_data = $xml->XMLin($notif_group_file);

		my($email_string,$is_email);
		for my $email (@{ $xml_data->{$notif_group}->[0]->{email} })
		{
			$email = trim($email);
			if(Email::Valid->address($email))
			{
				$email_string .= "$email, ";
				$is_email = "yes";
			}
		}
		$email_string =~ s/, $//;

		if($is_email eq "yes")
		{
			return $email_string;
		}
		else
		{
			die("Did not receive a valid email address from $notif_group_file.");
		}
	}
	else
	{
		die("$notif_group_file does not exist.");
	}
}

### Usage: send_email("notification_group","subject line","message body","from\@address");
### Returns: True and sends an email, or it dies.
### Note: Must escape @ if using "quotes".
sub send_email
{
	my($to,$subject,$message,$from) = @_;

	if(!Email::Valid->address($to))
	{
		$to = get_group_emails($to,"/hard/coded/path/to/notification_groups.xml")
	}

	my %mail = ( To => $to, Subject => $subject, Message => $message, From => $from );

	sendmail(%mail) or die('Email could not be sent');
}

send_email("test_group","test subj","test body","hardcoded@example.com");

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.