How to send an email in perl using mail
In Perl, you can send an email using the Mail::Sender
module. Here's a simple example:
First, you need to install the Mail::Sender
module. You can do this using CPAN:
cpanm Mail::Sender
Now, you can use the following code to send an email:
use strict;
use warnings;
use Mail::Sender;
my $sender = Mail::Sender->new;
eval {
my $msg = $sender->Mail(
From => '[email protected]',
To => '[email protected]',
Subject => 'Test email',
Body => 'This is a test email sent from Perl',
);
print "Email sent successfully\n";
} or print "Error: $@\n";
In this code:
- We use the
Mail::Sender
module and create a new instance of it. - We call the
Mail
method on the$sender
object, passing in the email details as key-value pairs. - The
From
,To
,Subject
, andBody
parameters are self-explanatory. - We use an
eval
block to catch any errors that might occur during the email sending process. - If the email is sent successfully, we print a success message. If an error occurs, we print the error message.
Make sure to replace [email protected]
and [email protected]
with your actual email addresses.
You can also use other modules like Email::Simple
or Email::MIME
to send emails in Perl. However, Mail::Sender
is a popular and easy-to-use module for sending emails.
Here's an example using Email::Simple
:
use strict;
use warnings;
use Email::Simple;
my $email = Email::Simple->create(
From => '[email protected]',
To => '[email protected]',
Subject => 'Test email',
Header => [
'Content-Type' => 'text/plain; charset=utf-8',
],
Body => 'This is a test email sent from Perl',
);
eval {
$email->send;
print "Email sent successfully\n";
} or print "Error: $@\n";
And here's an example using Email::MIME
:
use strict;
use warnings;
use Email::MIME;
my $email = Email::MIME->create(
From => '[email protected]',
To => '[email protected]',
Subject => 'Test email',
Header => [
'Content-Type' => 'text/plain; charset=utf-8',
],
Body => 'This is a test email sent from Perl',
);
eval {
$email->send;
print "Email sent successfully\n";
} or print "Error: $@\n";
These examples are similar to the Mail::Sender
example, but they use different modules to create and send the email.