9951 explained code solutions for 126 technologies


phpmailerHow do I configure PHPMailer to send emails using Gmail?


Configuring PHPMailer to send emails using Gmail

  1. Download and install PHPMailer:
composer require phpmailer/phpmailer
  1. Create a new PHPMailer instance:
$mail = new PHPMailer;
  1. Configure the SMTP settings:
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_gmail_username';
$mail->Password = 'your_gmail_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
  1. Set the sender and recipient email addresses:
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
  1. Set the email subject and body:
$mail->Subject = 'Email Subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
  1. Send the email:
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Output example

Message has been sent

For more information and detailed instructions, please refer to the PHPMailer documentation.

Edit this code on GitHub