The /usr/sbin/sendmail -t command allows you to send emails directly from the command line on Unix-like systems. It reads the recipients from the email headers (e.g., To, Cc, Bcc) within the email content. This method is commonly used for automation in scripts or cron jobs.

Steps to Send an Email with /usr/sbin/sendmail -t

1

Create the Email Content

The email content must include the headers (e.g., To, Subject) followed by the message body.

Example file (email.txt):

2

Use the sendmail Command

Run the following command to send the email:

/usr/sbin/sendmail -t < email.txt
  • -t: Instructs sendmail to read the recipient addresses (To, Cc, Bcc) from the email headers.
  • < email.txt: Feeds the email content to the command.

Example: Combining with echo and heredoc

Using echo:

echo -e "To: recipient@example.com\nSubject: Test Email\n\nThis is the body of the email." | /usr/sbin/sendmail -t

Using a Heredoc:

/usr/sbin/sendmail -t <

Use Cases

Automation

Ideal for sending system alerts or logs in scripts.

Example:

echo -e "To: admin@example.com\nSubject: Backup Completed\n\nThe backup was successful." | /usr/sbin/sendmail -t

Cron Jobs

Send output or error notifications from scheduled tasks.

Example cron entry:

0 2 * * * /path/to/script.sh | /usr/sbin/sendmail -t

Testing Email Server Configuration

Useful for verifying if sendmail is properly configured.

Troubleshooting Common Issues

Issue Solution
Command Not Found
  • Verify if sendmail is installed: which sendmail
  • If not installed, install a compatible Mail Transfer Agent (MTA), such as Postfix:
    sudo apt install postfix
Emails Not Delivered
  • Check the mail queue for stuck messages: mailq
  • Examine the mail logs:
    • Postfix: sudo tail -f /var/log/mail.log
    • Exim: sudo tail -f /var/log/exim_mainlog
Emails Marked as Spam Ensure the sender domain has correct DNS records:
  • SPF: Authorizes the server to send emails.
  • DKIM: Digitally signs emails.
  • DMARC: Defines email handling policies.
Debugging the Sendmail Command Use verbose mode to see detailed output:
echo -e "To: recipient@example.com\nSubject: Test Email\n\nBody content" | /usr/sbin/sendmail -t -v

Enhancements and Alternatives

  1. Use a Lightweight Mail Client:

    Instead of sendmail, consider using mailx or msmtp for simpler email sending:

    echo "This is a test email" | mail -s "Subject" recipient@example.com
  2. Send Emails via SMTP:

    Use tools like Python’s smtplib or a service like SendGrid for more control and security.