Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

How can I send an email to multiple recipients using Net::SMTP??
Everything works fine for me when I send to one user.
I'm just having a problem with the formatting when it comes to more than one recipient.
#!/usr/bin/perl -w use strict; use warnings; use NET::SMTP; my $servername="testserver.com"; my $from="jon@testserver.com"; my $to="jon@testserver.com,ted@testserver.com"; my $subject="test email"; my @body=("testmail"); my $smtp = Net::SMTP->new($servername) || die "unable to connect to se +rver: $servername\n"; die "Could not open connection: $!" if (!defined $smtp); $smtp->mail($from) || die "unable to set sender: $from\n"; $smtp->to($to) || die "unable to set recipient: $to\n"; $smtp->data(); $smtp->datasend("To: $to\n") || die "unable to send data: $to\n"; $smtp->datasend("From: $from\n") || die "unable to send data: $fro +m\n"; $smtp->datasend("Subject: $subject\n")|| die "unable to send data: + $subject\n"; $smtp->datasend("\n")|| die "unable to send data: \@body\n"; foreach (@body){ $smtp->datasend("$_\n"); } $smtp->dataend(); $smtp->quit;
Thanks in advance
Jonathan.

Replies are listed 'Best First'.
Re: sending to multiple recipients with Net::SMTP
by muntfish (Chaplain) on Nov 08, 2004 at 13:29 UTC

    The to() method can take a list of addresses. So don't try to put multiple addresses into one string, just pass them in as separate strings:

    $smtp->to($address1, $address2, ... );
    or
    @addrs = ("me\@testserver.com","someone\@elsewhere.com"); $smtp->to(@addrs);

    I think you can also do $smtp->to(...) multiple times, for the same effect, but I could be remembering that wrong.

    Oh, and don't forget to escape the @ in a double-quoted string...


    s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
      You can do $smtp->to(...) multiple times. This is how we have it set up:

      @email=qw(address1@host1.com address2@host2.com address3@host3.com); $smtp->new('my.mailhost'); $smtp->mail('myaddress@myhost.com'); foreach (<@email>) { $smtp->to($_); } $smtp->datasend("Rule 42 is now in effect.\n"); $smtp->dataend; $smtp->quit;
      Perhaps not the cleanest, but it works quite nicely.

      Update: forgot the $smtp->quit;. Also removed commas from @email=qw(...) per comment below.

        Thanks for confirming that.

        Just for the sake of pedantry, you have commas in your qw() which shouldn't be there. Perl will warn you about this if you have warnings turned on.


        s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
      Hi muntfish,

      Thanks for your quick reply, you got it dead right, everything working now. ++

      Thanks a lot,
      Jonathan.