What are the best practices for configuring SMTP settings in PHPMailer or Swiftmailer to avoid connection timeouts or errors?

When configuring SMTP settings in PHPMailer or Swiftmailer, it is important to set appropriate timeout values to avoid connection timeouts or errors. This can be achieved by increasing the timeout value for the connection to the SMTP server. Additionally, it is recommended to use secure connections (SSL or TLS) to ensure a secure and reliable connection.

// PHPMailer example
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Timeout = 30; // set timeout value to 30 seconds

// Swiftmailer example
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
  ->setUsername('your@example.com')
  ->setPassword('yourpassword')
  ->setTimeout(30); // set timeout value to 30 seconds
$mailer = new Swift_Mailer($transport);