ThisCalculator

Everyday

Send Email From PHP Through Office 365 on LAMP

Updated · Standard formula, shown below

Send Email From PHP Through Office 365 on LAMP

This guide shows you how to configure a LAMP (Linux, Apache, MySQL, PHP) server to send email through Office 365 using PHP’s built-in mail functions or a library like PHPMailer. You’ll learn the exact settings for SMTP authentication, TLS encryption, and the correct port, so your emails land in inboxes instead of spam folders.

What You’ll Need

  • A LAMP server with PHP 7.4 or newer (PHP 8.x recommended).
  • An Office 365 account with an email address (e.g., user@yourdomain.com) and its password or an app password if multi-factor authentication (MFA) is enabled.
  • Access to your server’s command line (SSH) to install packages and edit PHP configuration files.
  • Composer (optional but recommended) to install PHPMailer easily.
  • A domain that is verified in your Office 365 tenant (if you’re sending from a custom domain).

Step-by-Step

  1. Check PHP mail() availability: Run php -m | grep mail on your server. If you see ‘mail’ in the output, the mail() function is available. However, for reliable sending through Office 365, we’ll use SMTP with PHPMailer, which is more robust.
  2. Install PHPMailer: Navigate to your project directory and run composer require phpmailer/phpmailer. If Composer isn’t installed, download PHPMailer manually from GitHub and include the autoloader.
  3. Configure Office 365 SMTP settings: You’ll need the following details:
    • SMTP server: smtp.office365.com
    • Port: 587 (STARTTLS) or 465 (SSL/TLS). We’ll use 587 with STARTTLS.
    • Authentication: Yes, using your full Office 365 email address and password.
    • Encryption: STARTTLS (often called ‘tls’ in PHPMailer).
  4. Create a test PHP script: In your web root (e.g., /var/www/html), create a file named send_test.php with the following content:
    <?php
    require 'vendor/autoload.php'; // If using Composer
    
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    $mail = new PHPMailer(true);
    
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.office365.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your-email@yourdomain.com'; // Your full email
        $mail->Password = 'your-password'; // Use an app password if MFA is on
        $mail->SMTPSecure = 'tls'; // STARTTLS
        $mail->Port = 587;
    
        // Recipients
        $mail->setFrom('your-email@yourdomain.com', 'Your Name');
        $mail->addAddress('recipient@example.com', 'Recipient Name');
    
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Test email from LAMP server';
        $mail->Body    = 'This is a test email sent via Office 365 SMTP.';
    
        $mail->send();
        echo 'Message has been sent';
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
    ?>
  5. Update the credentials: Replace the placeholder email and password with your actual Office 365 credentials. If you have MFA enabled, create an app password in your Office 365 security settings and use that.
  6. Run the script: Open your browser and navigate to http://your-server-ip/send_test.php. If you see ‘Message has been sent’, everything works. If not, check the error message.
  7. Secure your script: After testing, move the script to a private location or delete it, as it contains credentials. For production, store credentials in environment variables or a config file outside the web root.
  8. Integrate into your application: Use the same SMTP configuration in your application’s email sending code. If you’re using a framework like Laravel, update the mail configuration file with these SMTP settings.

Common Mistakes

  • Using the wrong port: Port 25 is often blocked by ISPs and hosting providers. Always use 587 (STARTTLS) or 465 (SSL).
  • Forgetting to enable SMTP authentication: Office 365 requires authentication. Ensure SMTPAuth is set to true in PHPMailer.
  • Using a personal Microsoft account: If you’re using a free Outlook.com account, the SMTP server is different (smtp-mail.outlook.com). Office 365 uses smtp.office365.com for business accounts.
  • Hardcoding credentials in the script: This is a security risk. Use environment variables or a secure config file.
  • Not using an app password with MFA: If MFA is enabled, your regular password won’t work. Generate an app password from your Office 365 account settings.

Tips

  • Use PHPMailer’s debug mode: Set $mail->SMTPDebug = 2; to see detailed SMTP conversation in the browser. This helps diagnose connection issues.
  • Set a proper From address: Use an email address that exists in your Office 365 tenant. Some email clients mark emails as spam if the From address doesn’t match the authenticated user.
  • Add DKIM/SPF records: Ensure your domain has SPF and DKIM records set up in Office 365 to improve deliverability.
  • Use a dedicated sending account: Consider creating a service account for sending emails, rather than using a user’s personal mailbox.
  • Test with a real recipient: Always test with a real inbox (e.g., Gmail) to verify the email arrives and isn’t filtered.

Troubleshooting

If the email doesn’t send, check the following:

  • Connection refused or timeout: Your server may be blocking outbound port 587. Try using port 465 with SMTPSecure = 'ssl'. If that fails, contact your hosting provider to open the port.
  • Authentication failed: Double-check your email and password. If MFA is on, use an app password. Also ensure the account is active and not locked.
  • SMTP server not found: Verify the hostname smtp.office365.com is correct. Try pinging it from the server: ping smtp.office365.com.
  • Email goes to spam: Check your SPF and DKIM records. Also, avoid using a generic ‘From’ address like ‘noreply@yourdomain.com’ unless it’s a valid mailbox.
  • Error: ‘Mailbox unavailable’ or ‘Relay denied’: This often means the authenticated user is not allowed to send from the specified From address. Use the same address for both.
  • PHP error: ‘Class PHPMailer not found’: Make sure the autoloader is included correctly. If using Composer, verify the vendor directory exists.

Frequently Asked Questions

Can I use PHP’s mail() function with Office 365?

Yes, but it’s not recommended. The mail() function uses the local sendmail binary, which may not support SMTP authentication. You’d need to configure sendmail to use SMTP with Office 365, which is complex. PHPMailer is simpler and more reliable.

What is an app password and how do I create one?

An app password is a generated password for applications that don’t support MFA. To create one, go to Office 365 account security settings, enable MFA, then under ‘App passwords’, generate a new one. Use that in your PHP script.

Is port 587 or 465 better?

Both work, but 587 with STARTTLS is the standard for email submission and is less likely to be blocked. Port 465 uses implicit SSL and is also supported. Try 587 first.

Can I send to any email address (Gmail, Yahoo, etc.)?

Yes, Office 365 SMTP allows sending to any external email address, provided your account is authorized to send externally. There may be limits on the number of recipients per message.

Do I need to set up SPF and DKIM records?

It’s highly recommended. SPF and DKIM help authenticate your domain and prevent your emails from being marked as spam. Office 365 provides setup instructions for these records.

What if my server has no internet access?

SMTP requires outbound internet access on port 587 or 465. If your server is behind a firewall, you’ll need to allow outbound traffic on those ports. Without internet, you cannot send email via Office 365.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.