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

Mary-Kate Olsen
Release: 2024-10-28 04:18:01
Original
717 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!