mailx command examples

mailx command examples

mailx – send and receive Internet mail

Getting started

The mailx command has two distinct usages, according to whether one wants to send or receive mail. Sending mail is simple: to send a message to a user whose email address is, say, , use the shell command:

$ mailx bill@host.example

then type your message. Mailx will prompt you for a message subject first; after that, lines typed by you form the body of the message. When you reach the end of the message, type an EOT (control-d) at the beginning of a line, which will cause mailx to echo `EOT’ and return you to the shell.

If, while you are composing the message you decide that you do not wish to send it after all, you can abort the letter with a RUBOUT. Typing a single RUBOUT causes mailx to print `(Interrupt — one more to kill letter)’. Typing a second RUBOUT causes mailx to save your partial letter on the file `dead.letter’ in your home directory and abort the letter. Once you have sent mail to someone, there is no way to undo the act, so be careful.

If you want to send the same message to several other people, you can list their email addresses on the command line. Thus,

$ mailx sam@workstation.example bob@server.example
Subject: Fees
Tuition fees are due next Friday. Don't forget!
will send the reminder to . and .


To read your mail, simply type

$ mailx

Mailx will respond by typing its version number and date and then listing the messages you have waiting. Then it will type a prompt and await your command. The messages are assigned numbers starting with 1—you refer to the messages with these numbers. Mailx keeps track of which messages are new (have been sent since you last read your mail) and read (have been read by you).

New messages have an N next to them in the header listing and old, but unread messages have a U next to them. Mailx keeps track of new/old and read/unread messages by putting a header field called Status into your messages.

To look at a specific message, use the type command, which may be abbreviated to simply t . For example, if you had the following messages:

O 1 drfoo@myhost.example Wed Sep 1 19:52 18/631 “Fees”

O 2 sam@friends.example Thu Sep 2 00:08 30/895

you could examine the first message by giving the command:

type 1

which might cause mailx to respond with, for example:

Message 1:

From drfoo@myhost.example Wed Sep 1 19:52:25 2004

Subject: Fees

Status: R

Tuition fees are due next Wednesday. Don’t forget!

Many mailx commands that operate on messages take a message number as an argument like the type command. For these commands, there is a notion of a current message. When you enter the mailx program, the current mes‐sage is initially the first (or the first recent) one. Thus, you can often omit the message number and use, for example,


to type the current message. As a further shorthand, you can type a message by simply giving its message number. Hence,


would type the first message.

Frequently, it is useful to read the messages in your mailbox in order, one after another. You can read the next message in mailx by simply typing a newline. As a special case, you can type a newline as your first command to mailx to type the first message.

If, after typing a message, you wish to immediately send a reply, you can do so with the reply command. This command, like type, takes a message number as an argument. mailx then begins a message addressed to the user who sent you the message. You may then type in your letter in reply, followed by a at the beginning of a line, as before.

Note that mailx copies the subject header from the original message. This is useful in that correspondence about a particular matter will tend to retain the same subject heading, making it easy to recognize. If here are other header fields in the message, like `Cc:’, the information found will also be used.

Sometimes you will receive a message that has been sent to several people and wish to reply only to the person who sent it. Reply with a capital R replies to a message, but sends a copy to the sender only.

If you wish, while reading your mail, to send a message to someone, but not as a reply to one of your messages, you can send the message directly with the mail command, which takes as arguments the names of the recipients you wish to send to. For example, to send a message to , you would do:

mail frank@machine.example

To delete a message from the mail folder, you can use the delete command. In addition to not saving deleted messages, mailx will not let you type them, either. The effect is to make the message disappear altogether, along with its number.

Many features of mailx can be tailored to your liking with the set command. The set command has two forms, depending on whether you are setting a binary option or a valued option. Binary options are either on or off. For example, the askcc option informs mailx that each time you send a message, you want it to prompt you for a `Cc:’ header, to be included in the message. To set the askcc option, you would type

set askcc

Valued options are values which mailx uses to adapt to your tastes. For example, the record option tells mailx where to save messages sent by you, and is specified by

set record=Sent

for example. Note that no spaces are allowed in set record=Sent .

Mailx includes a simple facility for maintaining groups of messages together in folders. To use the folder facility, you must tell mailx where you wish to keep your folders. Each folder of messages will be a single file. For convenience, all of your folders are kept in a single directory of your choosing. To tell mailx where your folder directory is, put a line of the form

set folder=letters

in your .mailrc file. If, as in the example above, your folder directory does not begin with a `/’, mailx will assume that your folder directory is to be found starting from your home directory.

Anywhere a file name is expected, you can use a folder name, preceded with `+’. For example, to put a message into a folder with the save command, you can use:

save +classwork

to save the current message in the classwork folder. If the classwork folder does not yet exist, it will be created. Note that messages which are saved with the save command are automatically removed from your system mailbox.

In order to make a copy of a message in a folder without causing that message to be removed from your system mailbox, use the copy command, which is identical in all other respects to the save command.

The folder command can be used to direct mailx to the contents of a different folder. For example,

folder +classwork

directs mailx to read the contents of the classwork folder. All of the commands that you can use on your system mailbox are also applicable to folders, including type, delete, and reply. To inquire which folder you are currently editing, use simply:


To list your current set of folders, use the folders command.

Finally, the help command is available to print out a brief summary of the most important mailx commands.

While typing in a message to be sent to others, it is often useful to be able to invoke the text editor on the partial message, print the message, execute a shell command, or do some other auxiliary function. Mailx provides these capabilities through tilde escapes , which consist of a tilde (~) at the beginning of a line, followed by a single character which indicates the function to be performed. For example, to print the text of the message so far, use:


which will print a line of dashes, the recipients of your message, and the text of the message so far. A list of the most important tilde escapes is available with `~?’.

IMAP or POP3 client setup

First you need the following data from your ISP: the host name of the IMAP or POP3 server, user name and password for this server, and a notice whether the server uses SSL/TLS encryption. Assuming the host name is `server.myisp.example’ and your user name for that server is `mylogin’, you can refer to this account using the folder command or -f command line option with


(This string is not necessarily the same as your Internet mail address.) You can replace `imaps://’ with `imap://’ if the server does not support SSL/TLS. (If SSL/TLS support is built using NSS, the nss-config-dir variable must be set before a connection can be initiated, see above). Use `pop3s://’ or `pop3://’ if the server does not offer IMAP. You should use IMAP if you can, though; first because it requires fewer network operations than POP3 to get the contents of the mailbox and is thus faster; and second because message attributes are maintained by the IMAP server, so you can easily distinguish new and old messages each time you connect. Even if the server does not accept IMAPS or POP3S connections, it is possible that it supports the STARTTLS method to make a session SSL/TLS encrypted after the initial connection has been performed, but before authentication begins. The only reliable method to see if this works is to try it; enter one of

set imap-use-starttls

set pop3-use-starttls

before you initiate the connection.

As you probably want messages to be deleted from this account after saving them, prefix it with `%:’. The shortcut command can be used to avoid typing that many characters every time you want to connect:

shortcut myisp %:imaps://mylogin@server.myisp.example

You might want to put this string into a startup file. As the shortcut command is specific to this implementation of mailx and will confuse other implementations, it should not be used in ~/.mailrc, instead, put

set NAIL_EXTRA_RC=~/.nailrc

in ~/.mailrc and create a file ~/.nailrc containing the shortcut command above. You can then access your remote mailbox by invoking `mailx -f myisp’ on the command line, or by executing `fi myisp’ within mailx.

If you want to use more than one IMAP mailbox on a server, or if you want to use the IMAP server for mail storage too, the account command (which is also mailx-specific) is more appropriate than the shortcut command. You can put the following in ~/.nailrc:

account myisp {
set folder=imaps://mylogin@server.myisp.example
set record=+Sent MBOX=+mbox outfolder

and can then access incoming mail for this account by invoking `mailx -A myisp’ on the command line, or by executing `ac myisp’ within mailx. After that, a command like `copy 1 +otherfolder’ will refer to other folder on the IMAP server. In particular, `fi &’ will change to the mbox folder, and `fi +Sent’ will show your recorded sent mail, with both folders located on the IMAP server.

Mailx will ask you for a password string each time you connect to a remote account. If you can reasonably trust the security of your workstation, you can give this password in the startup file as

set password-mylogin@server.myisp.example="SECRET"

You should change the permissions of this file to 0600, see chmod(1).

Mailx supports different authentication methods for both IMAP and POP3. If Kerberos is used at your location, you can try to activate GSSAPI-based authentication by

set imap-auth=gssapi

The advantage of this method is that mailx does not need to know your password at all, nor needs to send sensitive data over the network. Otherwise, the options

set imap-auth=cram-md5
set pop3-use-apop

for IMAP and POP3, respectively, offer authentication methods that avoid to send the password in clear text over the network, which is especially important if SSL/TLS cannot be used. If the server does not offer any of these authentication methods, conventional user/password based authentication must be used. It is sometimes helpful to set the verbose option when authentication problems occur. Mailx will display all data sent to the server in clear text on the screen with this option, including passwords. You should thus take care that no unauthorized person can look at your terminal when this option is set.

If you regularly use the same workstation to access IMAP accounts, you can greatly enhance performance by enabling local caching of IMAP messages. For any message that has been fully or partially fetched from the server, a local copy is made and is used when the message is accessed again, so most data is transferred over the network once only. To enable the IMAP cache, select a local directory name and put

set imap-cache=~/localdirectory

in the startup file. All files within that directory can be overwritten or deleted by mailx at any time, so you should not use the directory to store other information.

Once the cache contains some messages, it is not strictly necessary anymore to open a connection to the IMAP server to access them. When mailx is invoked with the -D option, or when the disconnected variable is set, only cached data is used for any folder you open. Messages that have not yet been completely cached are not available then, but all other messages can be handled as usual. Changes made to IMAP mailboxes in disconnected mode are committed to the IMAP server next time it is used in online mode. Synchronizing the local status with the status on the server is thus partially within your responsibility; if you forget to initiate a connection to the server again before you leave your location, changes made on one workstation are not available on others. Also if you alter IMAP mailboxes from a workstation while uncommitted changes are still pending on another, the latter data may become invalid. The same might also happen because of internal server status changes. You should thus carefully evaluate this feature in your environment before you rely on it.

Many servers will close the connection after a short period of inactivity. Use one of

set pop3-keepalive=30
set imap-keepalive=240

to send a keepalive message each 30 seconds for POP3, or each 4 minutes for IMAP.

If you encounter problems connecting to a SSL/TLS server, try the ssl-rand-egd and ssl-rand-file variables (see the OpenSSL FAQ for more information) or specify the protocol version with ssl-method. Contact your ISP if you need a client certificate or if verification of the server certificate fails. If the failed certificate is indeed valid, fetch its CA certificate by executing the shell command

$ openssl s_client &1 | tee log

(see s_client(1)) and put it into the file specified with ssl-ca-file. The data you need is located at the end of the certificate chain within (and including) the `BEGIN CERTIFICATE’ and `END CERTIFICATE’ lines.

(Note that it is possible to fetch a forged certificate by this method. You can only completely rely on the authenticity of the CA certificate if you fetch it in a way that is trusted by other means, such as by personally receiving the certificate on storage media.)

Creating a score file or message filter

The scoring commands are best separated from other configuration for clarity, and are mostly mailx specific. It is thus recommended to put them in a separate file that is sourced from your NAIL_EXTRA_RC as follows:

source ~/.scores

The .scores file could then look as follows:

define list {
score (subject "important discussion") +10
score (subject "annoying discussion") -10
score (from "nicefellow@goodnet") +15
score (from "badguy@poornet") -5
move (header x-spam-flag "+++++") +junk

set folder-hook-imap://user@host/public.list=list

In this scheme, you would see any mail from `nicefellow@goodnet’, even if the surrounding discussion is annoying; but you normally would not see mail from `badguy@poornet’, unless he participates in the important discussion. Messages that are marked with five or more plus characters in their `X-Spam-Flag’ field (inserted by some server-side filtering software) are moved to the folder `junk’ in the folder directory.

Be aware that all criteria in () lead to substring matches, so you would also score messages from e.g. `not‐ sobadguy@poornetmakers’ negative here. It is possible to select addresses exactly using “address” message specifications, but these cannot be executed remotely and will thus cause all headers to be downloaded from IMAP servers while looking for matches.

When searching messages on an IMAP server, best performance is usually achieved by sending as many criteria as possible in one large () specification, because each single such specification will result in a separate network operation.

Activating the Bayesian filter The Bayesian junk mail filter works by examining the words contained in messages. You decide yourself what a good and what a bad message is. Thus the resulting filter is your very personal one; once it is correctly set up, it will filter only messages similar to those previously specified by you.

To use the Bayesian filter, a location for the junk mail database must be defined first:

set junkdb=~/.junkdb

The junk mail database does not contain actual words extracted from messages, but hashed representations of them. A foreign person who can read the database could only examine the frequency of previously known words in your mail.

If you have sufficient disk space (several 10 MB) available, it is recommended that you set the chained-junk- tokens option. The filter will then also consider two-word tokens, improving its accuracy.

A set of good messages and junk messages must now be available; it is also possible to use the incoming new messages for this purpose, although it will of course take some time until the filter becomes useful then.

Do not underestimate the amount of statistical data needed; some hundred messages are typically necessary to get satisfactory results, and many thousand messages for best operation. You have to pass the good messages to the good command, and the junk messages to the junk command. If you ever accidentally mark a good message as junk or vice-versa, call the ungood or unjunk command to correct this.

Once a reasonable amount of statistics has been collected, new messages can be classified automatically. The classify command marks all messages that the filter considers to be junk, but it does not perform any action on them by default. It is recommended that you move these messages into a separate folder just for the case that false positives occur, or to pass them to the junk command later again to further improve the junk mail database. To automatically move incoming junk messages every time the inbox is opened, put lines like the following into your .scores file (or whatever name you gave to the file in the last example):

define junkfilter {
classify (smaller 20000) :n
move :j +junk
set folder-hook-imap://user@host/INBOX=junkfilter

If you set the verbose option before running the classify command, mailx prints the words it uses for calculating the junk status along with their statistical probabilities. This can help you to find out why some messages are not classified as you would like them to be. To see the statistical probability of a given word, use the probability command.

If a junk message was not recognized as such, use the junk command to correct this. Also if you encounter a false positive (a good message that was wrongly classified as junk), pass it to the good command.

Since the classify command must examine the entire text of all new messages in the respective folder, this will also cause all of them to be downloaded from the IMAP server. You should thus restrict the size of messages for automatic filtering. If server-based filtering is also available, you might try if that works for you first.

Reading HTML mail

You need either the w3m or lynx utility or another command-line web browser that can write plain text to standard output.

set pipe-text/html="w3m -dump -T text/html"


set pipe-text/html="lynx -dump -force_html /dev/stdin"


will then cause HTML message parts to be converted into a more friendly form.

Viewing PDF attachments

Most PDF viewers do not accept input directly from a pipe. It is thus necessary to store the attachment in a temporary file, as with

set pipe-application/pdf="cat >/tmp/mailx$$.pdf; \

acroread /tmp/mailx$$.pdf; rm /tmp/mailx$$.pdf"

Note that security defects are discovered in PDF viewers from time to time. Automatical command execution like this can compromise your system security, in particular if you stay not always informed about such issues.

Signed and encrypted messages with S/MIME

S/MIME provides two central mechanisms: message signing and message encryption. A signed message contains some data in addition to the regular text. The data can be used to verify that the message was sent using a valid certificate, that the sender’s address in the message header matches that in the certificate, and that the message text has not been altered. Signing a message does not change its regular text; it can be read regardless of whether the recipient’s software is able to handle S/MIME. It is thus usually possible to sign all outgoing messages if so desired.—Encryption, in contrast, makes the message text invisible for all people except those who have access to the secret decryption key. To encrypt a message, the specific recipient’s public encryption key must be known. It is thus not possible to send encrypted mail to people unless their key has been retrieved from either previous communication or public key directories. A message should always be signed before it is encrypted. Otherwise, it is still possible that the encrypted message text is altered.

A central concept to S/MIME is that of the certification authority (CA). A CA is a trusted institution that issues certificates. For each of these certificates, it can be verified that it really originates from the CA, provided that the CA’s own certificate is previously known. A set of CA certificates is usually delivered with OpenSSL and installed on your system. If you trust the source of your OpenSSL software installation, this offers reasonable security for S/MIME on the Internet. In general, a certificate cannot be more secure than the method its CA certificate has been retrieved with, though. Thus if you download a CA certificate from the Internet, you can only trust the messages you verify using that certificate as much as you trust the download process.

The first thing you need for participating in S/MIME message exchange is your personal certificate, including a private key. The certificate contains public information, in particular your name and your email address, and the public key that is used by others to encrypt messages for you, and to verify signed messages they supposedly received from you. The certificate is included in each signed message you send. The private key must be kept secret. It is used to decrypt messages that were previously encrypted with your public key, and to sign messages.

For personal use, it is recommended that you get a S/MIME certificate from one of the major CAs on the Internet using your WWW browser. (Many CAs offer such certificates for free.) You will usually receive a combined certificate and private key in PKCS#12 format which mailx does not directly accept if S/MIME support is built using OpenSSL. To convert it to PEM format, use the following shell command:

$ openssl pkcs12 -in cert.p12 -out cert.pem -clcerts \

If you omit the -nodes parameter, you can specifiy an additional PEM pass phrase for protecting the private key. Mailx will then ask you for that pass phrase each time it signs or decrypts a message. You can then use

set smime-sign-cert-myname@myisp.example=cert.pem

to make this private key and certificate known to mailx.

If S/MIME support is built using NSS, the PKCS#12 file must be installed using Mozilla (provided that nss-config-dir is set appropriately, see above), and no further action is necessary unless multiple user certificates for the same email address are installed. In this case, the smime-sign-nickname variable has to be set appropriately.

You can now sign outgoing messages. Just use

set smime-sign

to do so.

From each signed message you send, the recipient can fetch your certificate and use it to send encrypted mail back to you. Accordingly if somebody sends you a signed message, you can do the same. First use the verify command to check the validity of the certificate. After that, retrieve the certificate and tell mailx that it should use it for encryption:

certsave filename
set smime-encrypt-user@host=filename

If S/MIME support is built using NSS, the saved certificate must be installed using Mozilla. The value of the smime-encrypt-user@host is ignored then, but if multiple certificates for the recipient are available, the smime-nickname-user@host variable must be set.

You should carefully consider if you prefer to store encrypted messages in decrypted form. If you do, anybody who has access to your mail folders can read them, but if you do not, you might be unable to read them yourself later if you happen to lose your private key. The decrypt command saves messages in decrypted form, while the save, copy, and move commands leave them encrypted.

Note that neither S/MIME signing nor encryption applies to message subjects or other header fields. Thus they may not contain sensitive information for encrypted messages, and cannot be trusted even if the message content has been verified. When sending signed messages, it is recommended to repeat any important header information in the message text.

Using CRLs with S/MIME or SSL/TLS

Certification authorities (CAs) issue certificate revocation lists (CRLs) on a regular basis. These lists contain the serial numbers of certificates that have been declared invalid after they have been issued. Such usually happens because the private key for the certificate has been compromised, because the owner of the certificate has left the organization that is mentioned in the certificate, etc. To seriously use S/MIME or SSL/TLS verification, an up-to-date CRL is required for each trusted CA. There is otherwise no method to distinguish between valid and invalidated certificates. Mailx currently offers no mechanism to fetch CRLs, or to access them on the Internet, so you have to retrieve them by some external mechanism.

If S/MIME and SSL/TLS support are built using OpenSSL, mailx accepts CRLs in PEM format only; CRLs in DER  format must be converted, e.g. with the shell command

$ openssl crl -inform DER -in crl.der -out crl.pem

To tell mailx about the CRLs, a directory that contains all CRL files (and no other files) must be created.

The smime-crl-dir or ssl-crl-dir variables, respectively, must then be set to point to that directory. After that, mailx requires a CRL to be present for each CA that is used to verify a certificate.

If S/MIME and SSL/TLS support are built using NSS, CRLs can be imported in Mozilla applications (provided that nss-config-dir is set appropriately).

Sending mail from scripts

If you want to send mail from scripts, you must be aware that mailx reads the user’s configuration files by default. So unless your script is only intended for your own personal use (as e.g. a cron job), you need to circumvent this by invoking mailx like

MAILRC=/dev/null mailx -n

You then need to create a configuration for mailx for your script. This can be done by either pointing the MAILRC variable to a custom configuration file, or by passing the configuration in environment variables.

Since many of the configuration options are not valid shell variables, the env command is useful in this situation. An invocation could thus look like

env MAILRC=/dev/null from=scriptreply@domain smtp=host \
smtp-auth-user=login smtp-auth-password=secret \
smtp-auth=login mailx -n -s "subject" \
-a attachment_file recipient@domain <content_file


Leave a Reply

Your email address will not be published. Required fields are marked *