0

I am trying to use Swift Mailer to send an email with an attachment. The email is not sending. I am fairly new to PHP so it may be a simple problem, but I cannot figure it out. Code:

<?php

require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465)
    ->setUsername('my gmail address')
    ->setPassword('my gmail password')
    ;

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance()
    ->setSubject('subject')
    ->setFrom(array('John@doe.com' => 'John Doe'))
    ->setTo(array('Jane@doe.com' => 'Jane Doe'))
    ->setBody('body')
    ->attach(Swift_Attachment::fromPath('image.png'))
    ;

echo('test 1'); 

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

echo('test 2');

printf("Sent %d messages\n", $numSent);

if ($mailer->send($message))
{
    echo "Sent\n";
}
else {
    echo "Failed\n";
}
?>

swift_required.php is successfully being included. My test 1 echo runs, but test 2 echo never does. This makes me think that the problem exists within the $numSent variable. Of course the problem is still very broad, but hopefully that narrows things a little bit. Also, none of the functions below $numSent work, so it does not tell me whether my email is being sent or not.

Figured it out, turns out you need to use 'tls://smtp.gmail.com'.

Will
  • 27
  • 10
  • Use the [debugging information provided in the Swiftmailer documentation](http://swiftmailer.org/docs/sending.html#finding-out-rejected-addresses) as well as the [Swiftmailer Logger plugin](http://swiftmailer.org/docs/plugins.html#logger-plugin) to help you narrow down the problem. All in all, you need to learn to debug your code effectively (from what you've written, it seems like you've done no debugging work on your own at all). – esqew Jul 23 '14 at 15:02

1 Answers1

0

If the second echo never comes, php must have exited!

Use error_reporting(E_ALL) in combination with ini_set('display_errors', 1) and add an error handler like below:

set_error_handler(function($severity, $message, $file, $line)
{
    if(!(error_reporting() & $severity))
    {
        return;
    }
    throw new ErrorException($message, $severity, $severity, $file, $line);
});

This will cause even notices to throw an exception in combination with E_ALL.

<?php ini_set('display_errors', 1); 
error_reporting(E_ALL);
//@todo: add the error handler here
try
{
    //every code in the app must be wrapped in this try statement.
    //require('file_that_mails_or_whatever.php');
}
catch(Exception $e)
{
    echo $e->getMessage() . '<br>';
    echo '<pre>' . $e->getTraceAsString() . '</pre>';
}
twicejr
  • 1,319
  • 3
  • 13
  • 21
  • 1
    Ok, I did that, but only get a blank page. Do you know what might cause this? – Will Jul 23 '14 at 15:25
  • It could be that the display_errors / error reporting is overridden somewhere else. Do you have access to your apache errorlog? – twicejr Jul 30 '14 at 15:26