Troubleshooting SwiftMailer with Gmail SMTP in PHP

I’m trying to set up a basic PHP script that uses SwiftMailer to send an email from a Gmail account to itself. I’ve adapted the code based on SwiftMailer’s documentation, but it doesn’t work as expected. The script stops executing at the send command.

Here’s an example of the setup:

require_once 'path/to/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587)
  ->setUsername('[email protected]')
  ->setPassword('mypassword');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(['[email protected]' => 'Sender Name'])
  ->setTo(['[email protected]' => 'Recipient Name'])
  ->setBody('Test Message Content');

$result = $mailer->send($message);
echo $result;

The script seems to hang or fail at the send command, and any code following it is not executed. Any insights on why this might happen or how to fix it?

hey mate, i had similar issues. try using app passwords instead of ur regular gmail password. google’s pretty strict bout security. also, make sure u’ve got the right port n encryption. sometimes 465 with SSL works better than 587 with TLS. good luck!

I’ve encountered similar issues with SwiftMailer and Gmail SMTP before. From my experience, there are a few things you might want to check:

First, make sure you’ve enabled ‘Less secure app access’ in your Gmail account settings. Google often blocks these kinds of connections by default.

Also, try setting the encryption method explicitly:

$transport = Swift_SmtpTransport::newInstance(‘smtp.gmail.com’, 587, ‘tls’)

If that doesn’t work, you might need to use port 465 with SSL instead:

$transport = Swift_SmtpTransport::newInstance(‘smtp.gmail.com’, 465, ‘ssl’)

Lastly, I’d recommend using app-specific passwords instead of your main Gmail password. It’s more secure and often resolves these connection issues.

If none of these work, try adding some error handling to see what’s going wrong:

try {
$result = $mailer->send($message);
echo $result;
} catch (Swift_TransportException $e) {
echo $e->getMessage();
}

This should give you more insight into what’s causing the script to hang.