Using php's swiftmailer with gmail

andandandand picture andandandand · Aug 13, 2010 · Viewed 82k times · Source

I'm writing a simple script in which a gmail account is used to send an email to itself.

I altered the script from SwiftMailer's reference, but I'm not getting any results. What's wrong?

Edit: after further debugging I've found that the statement

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

causes the code to fail (the echo below it doesn't print).

Why is this? Just cause the message isn't sent the program crashes? :/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<?php
    require_once '/var/www/swift/lib/swift_required.php';
    echo 'Mail sent <br />';  

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

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

    echo 'line 40 <br />';
    $mailer = Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance('Wonderful Subject')
      ->setFrom(array('[email protected]' => 'Evaluaciones'))
      ->setTo(array('[email protected]'=> 'A name'))
      ->setBody('Test Message Body')
    ;
    echo 'line 52 <br />';

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

?>
</body>
</html>

The test form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <title>Test Mail Script</title>
    </head>
    <body>
        <form action="scriptmail.php" method="post">
            <input type="submit"/>
            </table>
        </form>
  </body>
</html>

Answer

fullybaked picture fullybaked · Jan 14, 2011

Don't mean to resurrect an old post, but just in case others are looking for the answer, and because this post came up during my search for a solution despite the age.

When using PHP SwiftMailer to connect to Gmail or Google Apps email accounts you need to use the following

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

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

This works fine for me. In the original code, you are using port 587 not 465 and you are not specifying the protocol (ssl). Don't know if that bit matters, but for me port 587 failed and 465 worked fine.

Hope that helps.