Sending Mail within a Perl Script

Here comes a Perl script that uses a real SMTP connection for sending mail. That’s very useful e.g. if you want to send the result of a backup process via mail to the administrator. The only thing you have to do is complete the 5 variables server, sender, recipient, subject and message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/perl
 
use Net::SMTP;
 
$server    = "localhost";
$sender    = "sender <sender\@host.tld>";
$recipient = "recipient\@host.tld";
$subject   = "Test";
$message   = "Hello World!";
 
$smtp = Net::SMTP->new($server);
$smtp->mail($sender);
$smtp->to($recipient);
$smtp->data();
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("From: $sender\n");
$smtp->datasend("To: $recipient\n");
$smtp->datasend("\n");
$smtp->datasend("$message");
$smtp->dataend();
$smtp->quit;

And here are two further hints:

  • Use the tag symbols inside the sender variable to define an additional real name for the mail address
  • Use the <STDIN> keyword to read text from the standard input to fill the subject or message variable

0 Responses to “Sending Mail within a Perl Script”


  • No Comments

Leave a Reply