Home >Backend Development >PHP Tutorial >Why is my PHP email sent via Gmail's SMTP server failing, and how can I fix it using the Pear Mail library?

Why is my PHP email sent via Gmail's SMTP server failing, and how can I fix it using the Pear Mail library?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 09:51:10862browse

Why is my PHP email sent via Gmail's SMTP server failing, and how can I fix it using the Pear Mail library?

Sending Emails with GMail's SMTP Server from PHP

Issue:
When attempting to send an email using GMail's SMTP server from a PHP page, an error occurs, indicating authentication failure in SMTP.

Solution:

The provided code utilizes the Pear Mail Library, which requires adjustments for GMail's SMTP:

  1. Set Protocol to SSL: Modify the host line to include 'ssl://' before 'smtp.gmail.com'.
  2. Use Port 465 for SSL: Change the port number to '465'.
  3. Ensure Correct Username and Password: Use the full email address as the username and the associated password.

Updated Code:

require_once "Mail.php";

$from = '<[email&#160;protected]>';
$to = '<[email&#160;protected]>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => '[email&#160;protected]',
        'password' => 'passwordxxx'
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}

By incorporating these changes, the code should now successfully send emails through GMail's SMTP server from the PHP page.

The above is the detailed content of Why is my PHP email sent via Gmail's SMTP server failing, and how can I fix it using the Pear Mail library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn