To send mail with a Perl script, you can use the Net::SMTP
module from the Perl standard library. This module provides a simple interface for sending email messages via an SMTP (Simple Mail Transfer Protocol) server.
Here is an example of a Perl script that uses Net::SMTP
to send a simple email message:
#!/usr/bin/perl use strict; use warnings; use Net::SMTP; # Set the from and to addresses and the subject my $from = 'sender@example.com'; my $to = 'recipient@example.com'; my $subject = 'Test email'; # Set the SMTP server and create a new Net::SMTP object my $smtp_server = 'smtp.example.com'; my $smtp = Net::SMTP->new($smtp_server); # Set the message body my $body = "This is a test email\n"; # Send the message $smtp->mail($from); $smtp->to($to); $smtp->data(); $smtp->datasend("To: $to\n"); $smtp->datasend("Subject: $subject\n"); $smtp->datasend("\n"); $smtp->datasend($body); $smtp->dataend(); # Disconnect from the SMTP server $smtp->quit();
To send an HTML message or attach files, you will need to use the MIME::Lite
module, which provides a more powerful interface for creating and sending email messages.
Here is an example of a Perl script that uses MIME::Lite
to send an HTML email message with an attachment:
#!/usr/bin/perl use strict; use warnings; use MIME::Lite; # Set the from and to addresses and the subject my $from = 'sender@example.com'; my $to = 'recipient@example.com'; my $subject = 'Test email'; # Set the SMTP server my $smtp_server = 'smtp.example.com'; # Create a new MIME::Lite message my $msg = MIME::Lite->new( From => $from, To => $to, Subject => $subject, Type => 'multipart/mixed' ); # Add the HTML body and an attachment $msg->attach(Type => 'text/html', Data => '<html><body><p>This is an HTML email</p></body></html>'); $msg->attach(Type => 'text/plain', Path => '/path/to/attachment.txt', Filename => 'attachment.txt'); # Send the message $msg->send('smtp', $smtp_server);
Keep in mind that you will need to have access to an SMTP server in order to send email from a Perl script. You may need to configure the script with the appropriate login credentials for the SMTP server, depending on the server's configuration.