📧 Ubuntu Server Mail Configuration

Professional Guide to Configuring SMTP with MSMTP and Third-Party Providers

🎯 Introduction

This comprehensive guide covers configuring your Ubuntu server to send mail from the command line and using PHP. This enables your WordPress site to send transactional emails without relying on plugins, which is crucial for maintaining server performance and security.

📌 Important Note: This guide focuses on transactional mail (contact forms, password resets, notifications) and not large mailing lists. For mailing lists exceeding 50 users, consider dedicated third-party services.

🔍 Why Mail Configuration Matters

Reliable mail delivery is critical for WordPress sites. Most emails are triggered by visitor actions such as:

Email Flow Architecture

WordPress Site / Command Line
Mail trigger point
MSMTP Client
Lightweight SMTP relay
Third-Party SMTP Server
Gmail / SendGrid / Mailgun / etc.
Recipient Inbox
Successfully delivered email

⚙️ Understanding MSMTP

MSMTP (Minimal SMTP) is a lightweight SMTP client designed for sending emails from command line or scripts. Unlike full mail servers like Postfix or Sendmail, MSMTP focuses solely on sending emails through existing SMTP servers.

🚀 Easy Configuration

Simple setup process with minimal configuration files required.

🔄 Sendmail Replacement

Can act as a drop-in replacement for sendmail command.

🔒 SSL/TLS Support

Supports encryption for secure SMTP communication.

💡 Lightweight

Minimal resource usage, perfect for low-resource servers.

📊 Third-Party SMTP Provider Comparison

Provider Free Tier Paid Starting Price Key Features
Gmail SMTP 100 emails/day Free Simple setup, no domain validation
SMTP2GO 1,000 emails/month $10 for 10,000 emails Great service, reasonable pricing
SendGrid 100 emails/day Varies by volume Popular, scalable solution
Mailgun Limited trial Pay as you go Developer-friendly API
Mailjet 200 emails/day Well-priced tiers Decent service, good value
⚠️ Domain Validation: Most third-party providers require domain ownership verification. This is necessary because WordPress sends certain emails (like password resets) from addresses like [email protected]. Without validation, these emails will not be sent.

🛠️ Installation and Configuration Steps

1Generate Google App Password

Before configuring MSMTP, you need to generate an app-specific password for Gmail:

Prerequisites:
  • Active Gmail account
  • Two-factor authentication (2FA) enabled on your Google account
Navigate to
myaccount.google.com
Go to Security
Section
Enable 2FA
(if not enabled)
Search "App
Passwords"
Create New
App Password
🔐 Security Note: The app password is displayed only once. Copy it immediately and store it securely. Remove spaces from the password before using it in configuration files.

2Install MSMTP Packages

Install MSMTP and MSMTP-MTA (Mail Transfer Agent) packages on your Ubuntu server:

# Update package list sudo apt update # Upgrade packages (optional but recommended) sudo apt upgrade # Install MSMTP and MSMTP-MTA sudo apt install msmtp msmtp-mta # When prompted, enable AppArmor support (press Enter for "No")
✅ Installation Complete: The installation adds approximately 1.5MB of additional disk space with minimal package dependencies.

3Configuration File Structure

MSMTP uses two separate configuration files:

MSMTP Configuration Files

~/.msmtprc
User's home directory

Used for sending mail from the command line

/etc/msmtprc
System-wide configuration

Used for sending mail via PHP scripts

4Create Command Line Configuration (~/.msmtprc)

# Navigate to home directory cd ~ # Create configuration file nano .msmtprc

Configuration file template:

# Defaults - Do not change these settings defaults auth on tls on tls_trust_file /etc/ssl/certs/ca-certificates.crt logfile ~/.msmtp.log # Account configuration account mail host smtp.gmail.com port 587 auth on user [email protected] password your-app-password-here from [email protected] # Set default account account default : mail
📝 Configuration Parameters:
  • account: Name for this SMTP account (e.g., "mail")
  • host: SMTP server address (smtp.gmail.com for Gmail)
  • port: SMTP port (587 for TLS, 465 for SSL)
  • user: Your Gmail email address
  • password: The app password generated earlier (no spaces)
  • from: Email address for outgoing mail
  • account default: Must match the account name

5Set Correct Permissions

# Set file permissions to 600 (owner read/write only) chmod 600 ~/.msmtprc # Verify permissions ls -la ~/.msmtprc # Should show: -rw------- (600)
🔒 Security Important: The configuration file contains sensitive credentials and must have 600 permissions (readable/writable only by owner).

6Create Command Line Log File

# Create empty log file touch ~/.msmtp.log # Set ownership (user:msmtp) sudo chown $USER:msmtp ~/.msmtp.log # Set permissions to 660 sudo chmod 660 ~/.msmtp.log # Verify settings ls -la ~/.msmtp.log

7Test Command Line Mail Sending

# Send test email msmtp [email protected] # Type your message, press Enter, then Ctrl+D to send # Example: msmtp [email protected] This is a test message # Press Enter, then Ctrl+D
✅ Testing Success: If configured correctly, the email should arrive in the recipient's inbox within seconds.

8Configure PHP Mail Support (/etc/msmtprc)

# Copy user configuration to system directory sudo cp ~/.msmtprc /etc/msmtprc # Change to /etc directory cd /etc # Set ownership to web server user sudo chown www-data:www-data /etc/msmtprc # Set permissions to 660 sudo chmod 660 /etc/msmtprc

9Update PHP Configuration Log Path

# Edit system configuration file sudo nano /etc/msmtprc # Change the logfile line to: logfile /var/log/msmtp.log

10Create and Configure PHP Log File

# Navigate to log directory cd /var/log # Create log file sudo touch msmtp.log # Set ownership (www-data:adm) sudo chown www-data:adm msmtp.log # Set permissions to 640 sudo chmod 640 msmtp.log # Verify ls -la msmtp.log

11Create PHP Test Script

# Return to home directory cd ~ # Create test script nano php_mail_test.php

PHP test script content:

<?php // Email configuration $to = "[email protected]"; $subject = "PHP Mail Test"; $message = "Testing PHP mail functionality from Ubuntu server."; $headers = "From: [email protected]\r\n"; $headers .= "Reply-To: [email protected]\r\n"; $headers .= "X-Mailer: PHP/" . phpversion(); // Send email if(mail($to, $subject, $message, $headers)) { echo "Test email sent successfully!\n"; } else { echo "Failed to send email.\n"; } ?>

12Adjust Directory Permissions for Testing

# Temporarily set directory permissions to 755 cd .. sudo chmod 755 /home/your-username # Note: This is temporary for testing only

13Test PHP Mail Functionality

# Run PHP script as www-data user sudo -u www-data php ~/php_mail_test.php # Expected output: Test email sent successfully!
✅ Configuration Complete: Your server can now send emails from both command line and PHP scripts!

🐛 Troubleshooting

Check Command Line Logs

# View command line mail log cat ~/.msmtp.log

Check PHP Mail Logs

# View PHP mail log sudo cat /var/log/msmtp.log
💡 Common Issues:
  • Authentication failed: Verify app password is correct and 2FA is enabled
  • Permission denied: Check file/directory permissions (600 for config, 660 for logs)
  • Connection timeout: Verify firewall allows outbound connections on port 587
  • TLS errors: Ensure ca-certificates package is installed

📧 Email Hosting Solutions for Domain Email

While MSMTP handles transactional emails from your server, you'll need a proper email hosting solution for receiving emails and managing mailboxes at your domain.

Paid Solutions

🏆 Google Workspace (Recommended Paid Option)

Starting at $6/user/month

  • Familiar Gmail interface
  • Legendary Google uptime and reliability
  • Professional email addresses ([email protected])
  • Generous storage space
  • Excellent mobile and desktop apps
  • Integrated with Google Drive, Calendar, Meet

Free Solutions

🌟 Zoho Mail (Top Free Choice)

  • Free tier available
  • Professional features
  • Excellent mobile app
  • Easy setup process
  • Ad-free interface

💼 Namecheap Email

  • Affordable pricing
  • Basic email features
  • Good for small businesses
  • Domain bundling available
  • Webmail interface
⚠️ Important Considerations:
  • Setting up a full mail server (Postfix/Sendmail) is complex and requires expertise
  • Mail server configuration involves DKIM, SPF, DMARC, and reverse DNS
  • Third-party solutions provide better deliverability and reliability
  • Always test services with free/trial plans before committing

🔄 Switching to Third-Party Providers

If you decide to switch from Gmail to another SMTP provider:

# Update ~/.msmtprc for command line nano ~/.msmtprc # Update /etc/msmtprc for PHP sudo nano /etc/msmtprc # Modify these fields: host smtp.your-provider.com port 587 # or provider-specific port user your-username password your-api-key-or-password from [email protected]

📚 Best Practices Summary

🔒 Security

  • Always use app passwords, never main account passwords
  • Set proper file permissions (600 for config files)
  • Enable two-factor authentication
  • Regularly review access logs

⚡ Performance

  • Use MSMTP instead of full mail servers
  • Minimize WordPress plugin usage
  • Monitor log file sizes
  • Test mail delivery regularly

🛡️ Reliability

  • Choose reputable SMTP providers
  • Configure proper error logging
  • Validate domain ownership with providers
  • Monitor email deliverability rates

📊 Monitoring

  • Check log files regularly
  • Monitor sending limits
  • Track bounce rates
  • Set up alerts for failures

🎓 Conclusion

Configuring MSMTP on your Ubuntu server provides a lightweight, efficient solution for sending transactional emails without the complexity of managing a full mail server. By using third-party SMTP providers like Gmail, SendGrid, or Mailgun, you ensure reliable email delivery while maintaining a simple configuration.

✅ Key Takeaways:
  • MSMTP is ideal for transactional emails from WordPress sites
  • Two configuration files handle command line and PHP mail separately
  • Proper permissions and logging are essential for security and troubleshooting
  • Third-party SMTP providers offer better deliverability than self-hosted mail servers
  • Always minimize plugin usage in WordPress for better performance

🚀 Next Steps

In the next section, we'll explore nginx configuration files in detail, understanding the layout, directives, and contexts that appear in nginx configuration files.