How to Send and Receive Email with Perl

Perl is a versatile and powerful programming language that can be used for various tasks, including sending and receiving email. In this article, we will explore some of the modules and methods that can help you accomplish this goal.

Sending Email with Perl

There are different ways to send email with Perl. One way is to use the Email::MIME module to create and parse email messages, and the Email::Sender module to send them using various transports, such as SMTP or Sendmail. Another way is to use the Mail::Send module to create mail messages and send them using your local mail agent.

Example: Sending an Email with Email::MIME and Email::Sender

Here is an example of sending an email with Perl using Email::MIME and Email::Sender:

#!/usr/bin/perl
use strict;
use warnings;

# first, create your message
use Email::MIME;
my $message = Email::MIME->create(
  header_str => [
    From    => 'sender@example.com',
    To      => 'receiver@example.com',
    Subject => 'Hello there!',
  ],
  attributes => {
    encoding => 'quoted-printable',
    charset  => 'ISO-8859-1',
  },
  body_str => "This is a simple text message.\n",
);

# then, send your message
use Email::Sender::Simple qw(sendmail);
sendmail($message);

Receiving Email with Perl

To receive emails, you can use the Mail::POP3Client module to connect to a POP3 server and retrieve messages, or the Mail::IMAPClient module to connect to an IMAP server and manipulate messages.

Example: Receiving an Email with Mail::POP3Client

Here is an example of receiving an email with Perl using Mail::POP3Client:

#!/usr/bin/perl
use strict;
use warnings;

# connect to POP3 server
use Mail::POP3Client;
my $pop = Mail::POP3Client->new(
  USER     => 'user@example.com',
  PASSWORD => 'secret',
  HOST     => 'pop.example.com',
);

# get the number of messages
my $count = $pop->Count();

# loop through each message
for (my $i = 1; $i <= $count; $i++) {
  # get the message headers
  my $headers = $pop->Head($i);
  # print the subject
  print $headers =~ /^Subject: (.*)/m, "\n";
  # get the message body
  my $body = $pop->Body($i);
  # print the first line of the body
  print substr($body, 0, index($body, "\n")), "\n";
}

# close the connection
$pop->Close();

Conclusion

In this article, we have seen some of the ways to send and receive email with Perl. There are many other modules and options that you can explore to suit your needs. Perl makes it easy and fun to work with 10 min email. Happy coding!

About Den

user-pic Old dev