How to set smtp server in php mail

To set up an SMTP server in PHP mail, you'll need to configure the mail() function or use a PHP mail library that supports SMTP. Here are the general steps:

Using the mail() function

  1. Define the SMTP server settings:
    $smtp_server = 'your_smtp_server';
    $smtp_port = 587; // or 25, 465, etc.
    $smtp_username = 'your_smtp_username';
    $smtp_password = 'your_smtp_password';
  2. Set the mail() function to use the SMTP server:
    ini_set('SMTP', $smtp_server);
    ini_set('smtp_port', $smtp_port);
    ini_set('auth_username', $smtp_username);
    ini_set('auth_password', $smtp_password);
  3. Use the mail() function to send the email:
    mail('[email protected]', 'Subject', 'Message');

    Using a PHP mail library

There are many PHP mail libraries available, such as PHPMailer, SwiftMailer, and Zend_Mail. Here's an example using PHPMailer:

  1. Install PHPMailer using Composer: composer require phpmailer/phpmailer
  2. Create a PHPMailer object:
    
    require 'PHPMailer/PHPMailer.php';
    require 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer(); $mail->isSMTP();

3. Set the SMTP server settings:
```php
$mail->Host = $smtp_server;
$mail->Port = $smtp_port;
$mail->SMTPAuth = true;
$mail->Username = $smtp_username;
$mail->Password = $smtp_password;
  1. Set the email message:
    $mail->setFrom('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]', 'Recipient Name');
    $mail->Subject = 'Subject';
    $mail->Body = 'Message';
  2. Send the email:
    $mail->send();

    Common SMTP server settings

Here are some common SMTP server settings:

Troubleshooting tips