Home  >  Article  >  Backend Development  >  Why is My SwiftMailer Script Failing to Send Emails via Gmail?

Why is My SwiftMailer Script Failing to Send Emails via Gmail?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 04:18:01718browse

Why is My SwiftMailer Script Failing to Send Emails via Gmail?

Using PHP's SwiftMailer to Send Emails via Gmail

This question arose when attempting to use SwiftMailer with a Gmail account to send an email to itself. Modifications were made to the script based on SwiftMailer's reference, but no results were obtained.

The issue stemmed from the line:

<code class="php">$result = $mailer->send($message);</code>

This line caused the code to fail, indicating an issue with sending the message. It is possible that the message was not being sent and the program crashed as a result.

The script code was as follows:

<code class="php">require_once '/var/www/swift/lib/swift_required.php';
echo 'Mail sent <br />';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587)
  ->setUsername('example@gmail.com')
  ->setPassword('password');

echo 'line 40 <br />';
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('example@gmail.com' => 'Evaluaciones'))
  ->setTo(array('example@gmail.com' => 'A name'))
  ->setBody('Test Message Body');

echo 'line 52 <br />';
$result = $mailer->send($message);
echo $result;
echo 'line 58 <br />';</code>

To resolve this issue, the code was modified as follows:

<code class="php">$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
  ->setUsername($this->username)
  ->setPassword($this->password);

$this->mailer = Swift_Mailer::newInstance($transporter);</code>

This resolved the issue, allowing the message to be sent successfully.

The above is the detailed content of Why is My SwiftMailer Script Failing to Send Emails via Gmail?. 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