home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeJava and XSLTSearch this book

Chapter 16. Email Connectivity

Electronic mail is arguably the most essential Internet application. In fact, for many people, it's their introduction to the Internet. Thus, the Perl modules that deal with email are among the most useful modules. There are two major groups of modules that provide email capabilities. The first group is Graham Barr's libnet collection, which contains packages for developing client-side applications over the Internet in Perl. Table 16-1 lists some of the protocols implemented by the libnet modules.

Table 16-1. Protocols implemented by the libnet modules






Post Office Protocol, for reading email



Simple Mail Transfer Protocol, for sending email



File Transfer Protocol, for transferring files between hosts



Network News Transfer Protocol, for reading Usenet news

In this chapter, we discuss Net::SMTP and Net::POP3. Chapter 17, "Usenet News" talks about Net::NNTP, Chapter 18, "FTP" discusses Net::FTP, and Chapter 19, "Lightweight Directory Access with Net::LDAP" covers Net::LDAP. Other libnet modules, such as Net::SNPP and Net::Time, are not described in this book, but you can get information about them from CPAN or with the perldoc command if libnet is installed on your system.

The second group of mail-related modules are the Mail modules, which can be found on CPAN as the MailTools collection. Other interesting mail-related modules include Mail::Folder and its subclasses, Mail::RBL, Mail::Audit, and Unix::AliasFile. This chapter describes the following subset of the Mail modules:

Built on top of Mail::Mailer, providing better control of mail headers

Interacts with external mail programs to send mail

Provides a base class and subclasses to work with mail folders

Provides functions to manipulate a mail message

Extracts and manipulates RFC 822-compliant mail addresses

Provides domain lookups to the Real-time Blackhole List (RBL)

Provides an easy interface for creating mail filters

Perl interface to /etc/aliases format files

The rest of this chapter describes the Net modules and the Mail modules.

16.1. The Net Modules

Net::SMTP and Net::POP3 are the modules for sending and receiving email via the SMTP and POP3 protocols. When you use these modules, you are working at the socket level; they directly implement the Internet protocols for sending and receiving mail as defined in the relevant RFCs: RFC 821 for SMTP and RFC 1081 for POP3.

16.1.1. Send Email with Net::SMTP

The Simple Mail Transfer Protocol, or SMTP, is responsible for clients negotiating RCPT ("to") and FROM ("from") requests with an SMTP server, sending data to the SMTP server, and then sending an end-of-data indicator. Net::SMTP is a subclass of Net::Cmd and IO::Socket::INET that implements an interface to the SMTP and ESMTP protocols. These protocols send mail by talking to an SMTP server through a socket, as described in RFC 821.

When would you want to use Net::SMTP instead of sending mail with an external program? Since socket communications don't involve spawning an external program, your programs won't suffer from the overhead associated with running an extra process. Talking to SMTP is convenient for sending a volume of mail messages. Naturally, your server must have an SMTP server running, or a remote mailhost must allow you to talk to it; otherwise, you won't be able to use this module. That's when you can turn to Mail::Mailer or Mail::Send and let them provide an interface to an external mail program for you. This is the case, for example, with home computers, which don't generally run their own SMTP server.

16.1.2. The SMTP Protocol and the SMTP Session

The SMTP protocol defines the set of commands a client sends to an SMTP server, which is generally bound to port 25 of a mailhost. Requests and responses are negotiated between client and server.

When a client negotiates an SMTP session with a server, the server tells the client that it's listening. Once you're connected, you introduce yourself to the server by issuing a HELO command. The HELO command accepts one parameter—your hostname—and defaults to your remote hostname if you don't specify one. If the command is successful, the server sends a 250 response, as follows:

250 mail.somename.com Hello some-remote-host.com [], pleased to meet 

After you've been greeted by the server, send the MAIL command to tell the server who the message is from. The MAIL command takes the string From: user@hostname as an argument, and the server responds with a 250 message to indicate success:

MAIL From: <realuser@realhost.com>
250 realuser@realhost.com ... Sender ok

Then send the RCPT command to tell the server who the recipient is:

RCPT To: <nospam@rid-spam-now.com>
250 nospam@rid-spam-now.com ... Recipient ok

Now you're ready to send the body of your message to the server. The DATA command tells the server that all data until a . on a line by itself should be treated as the body of the mail message:

354 Enter mail, end with "." on a line by itself
Subject: Hi, just thought you'd be interested ...

Hi, this is the text of my mail message that I'm going to 
send with Net::SMTP to show you how it works.
250 VAA09505 Message accepted for delivery

Once again, you get a 250 response, indicating that the message has been accepted for delivery. At that point, you can exit the SMTP session with the QUIT command, which returns 221 on success:

221 mail.somename.com closing connection
Connection closed by foreign host. Net::SMTP methods

The following methods are defined by Net:SMTP.


$smtp = Net::SMTP->new(host[, options])

Constructor. Takes the hostname of the remote mail server, host, and possibly some options, and creates a new SMTP object. Any options are passed to new as a hash, in which the option is the key. The possible options are:

Enables debug mode if set to 1. Provides information about your connection, requests, and responses.

Sends a HELO command to the SMTP server. Takes a string that represents your domain; if not specified, Hello guesses your domain.

Time (in seconds) after which the client stops trying to establish a connection with the SMTP server. Defaults to 120 seconds. If the connection cannot be established, the constructor returns undef.



Returns the banner message with which the server replied when the initial connection was made. For example:

my $banner = $smtp->banner( );
print "$banner\n";


Starts sending the body of the current message to the server. If specified, bodydata can be a list or a reference to a list; the contents of the list and the termination string .\r\n are sent to the server. Returns true if accepted.

If bodydata is not specified, then a true result means that the server is ready to receive data, which must be sent with the datasend and dataend methods (inherited from Net::Cmd).


$smtp->dataend(  )

Net::Cmd method issued after datasend to end the sending of data. Sends .\r\n to the server telling it that there's no more data coming and that it should send the message.

Here's an example that uses datasend and dataend:

@list_data = (1..10);
$smtp->data( );
$smtp->dataend( );


Net::Cmd method that sends the body of the message to the remote server if the body wasn't specified with the data method.


$smtp->domain(  )

Returns the domain of the remote SMTP server, or undef.



Requests the server to expand address. Returns an array containing the text from the server.



Identifies your domain to the mail server. Executes automatically when you create a Net::SMTP object, so you shouldn't have to do it manually.


$help_text = $smtp->help([subject])

Returns help text from the server, or undef on failure. If subject is specified, returns help for that topic.


$smtp->mail(address[, options])

Takes the sender's address and sends the appropriate command (MAIL, SEND, SOML, or SAML) to the server to initiate the message-sending process.

mail can take some ESMTP options, passed as key/value pairs. See the Net::SMTP documentation for the details.



This method sends the QUIT command to the remote SMTP server and closes the socket connection.


$smtp->recipient(addr[, addr[, ...]])

Tells the server to send the current message to all specified recipients. As defined in the RFC, each address is sent as a separate command to the server. If the sending of any address fails, the process aborts and returns false; you can then call reset to reset the server.


$smtp->reset(  )

Resets the server's status. Useful for canceling a message after it has been initiated but before any data has been sent.


$smtp->to(address[, address[, ...]])

Interchangeable with recipient.



Verifies that the specified mail address is valid. However, many servers ignore verify, so it frequently doesn't work.

16.1.3. Retrieving Email with Net::POP3

You can use SMTP to send mail, but not to retrieve it. For retrieving messages, use the Post Office Protocol Version 3 (POP3), described in RFC 1081. One way to do this is to use the Net::POP3 module. POP3 provides commands for interacting with the POP server, typically bound to port 110. Net::POP3 automates the transfer of email from a remote server to the local machine.

The POP server retrieves messages from a specified spooling directory on the remote system. The messages are stored in a file named for the username; anonymous logins are not permitted. Authentication is based on username and password and is done by sending the USER and PASS commands to the POP server. For example, identification of user foo with password bar looks like this:

USER foo
PASS bar

Net::POP3 has user and pass methods but may also authenticate users with login, which takes both username and password arguments. If authentication fails, the user cannot retrieve, delete, or alter any messages from the mail server. login returns the number of messages on the POP server for the user, or undef if authentication fails.

Authenticated users can retrieve information about their mailboxes and can get specific messages by message number.

A POP session to retrieve a mail message is negotiated with the server through the following steps:

  1. Connect to the POP server (the default port is 110).

  2. Send USER command.

  3. Send PASS command.

  4. If authenticated, receive number of messages.

  5. Send RETR <message number> command to retrieve a specific message.

  6. Send QUIT command to end session.

The following methods are defined by Net:POP3.


$pop = Net::POP3->new([host,] [options])

Constructor. Creates a new Net::POP3 object. host is the name of the remote host to which a POP3 connection will be made. If host is not specified, then the POP3_Host specified in Net::Config is used.

options are passed as key/value pairs, in which the option is the key. The possible options are:

Optional. If given, then the socket for the Net::POP3 object will be bound to the given local port using bind when the socket is created.

Enables debugging information

Maximum time, in seconds, to wait for a response from the POP3 server. Default is 120 seconds.


$pop->apop(user, pass)

Authenticates user with password pass with the server. The password is not sent in clear text. Requires the MD5 package; otherwise, returns undef.



Marks message msgnum for deletion from the remote mailbox. All messages marked for deletion are removed when the connection to the server is closed.



Gets message msgnum from remote mailbox. Returns a reference to an array containing lines of text read from the server.


$pop->last(  )

Returns the highest message number.



If called with an argument, returns the size of message msgnum. If called without an argument, returns a hash reference, in which the keys are the message numbers of all undeleted messages, and each corresponding value is the size of the message.


$pop->login([user[, pass]])

Sends both USER and PASS commands. If the password, pass, is not given, then Net::Netrc is used to look up the password based on the host and the username, user. If user is not specified, the current username is used. Returns the count of messages in the mailbox, or undef if the server can't authenticate the user.



Sends the PASS command with the password. Returns the number of messages in the mailbox.


$pop->popstat(  )

Returns a list with two elements: the number of undeleted elements and the size of the mailbox.


$pop->quit(  )

Quits, closing the connection to the remote POP3 server and deleting all messages marked for deletion.

Note that if a Net::POP3 object goes out of scope before quit has been called, reset is called before the connection is closed, and any messages marked for deletion are not deleted.


$pop->reset(  )

Resets status of the remote POP3 server. Clears the delete status on all messages that were marked for deletion.


$pop->top(msgnum[, numlines])

Gets the header and the first numlines lines of body for message msgnum. Returns a reference to an array containing lines of text read from the server.



Returns a unique identifier for msgnum if specified. If msgnum is not specified, returns a reference to a hash in which the keys are the message numbers, and the values are the unique identifiers.



Sends the USER command, identifying the user.

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.