Using php's swiftmailer with gmail
Asked Answered
P

6

41

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>
Pizarro answered 13/8, 2010 at 16:33 Comment(3)
This may be useful: https://mcmap.net/q/86322/-send-email-using-the-gmail-smtp-server-from-a-php-pageWorkhouse
helpful to me: Symfony - How to Use Gmail to Send EmailsOrten
this may be useful : https://mcmap.net/q/392271/-swiftmailer-gmail-cannot-send-emailTymon
T
90

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.

Toowoomba answered 14/1, 2011 at 12:44 Comment(4)
For those who have two-step verification enabled at Goole, you must use your generated password.Maldon
well, i declared a transporter but not the mailer. too many abstractions for my small head :-) +1 anywaySparing
Thanks, this works great. I was going nuts sending/testing rom localhost and trying to get out of spam box.Confluent
port 465 is deprecated, you should use port 587 instead.Cristionna
T
40

I found this question doing a google search and used the code in the answer provided by fullybaked. It got me to the point where I could see in the Exceptions thrown that the Google smtp server was responding with an error code indicating password and username not accepted. Upon further investigation I found the following steps. Now it works great and I can continue to flesh out the code for production.

Not sure when Google made the change but in addition to the configuring your code with your Google username, password and port (465/ssl or 587/tls) you need to do the following steps to be able to use the Google smtp server.

To use the the gmail smtp server with your gmail account you need to:

1) In Google "Account settings" enable "Access for less secured apps" by setting it to "Allow".

2) In gmail settings under the "Forwarding and POP/IMAP" tab, check the IMAP status, it needs to be enabled. (This will allow the emails sent to be saved in the sent folder.)

3) If after steps 1 and 2 you still throw the Exception Google's smtp server is not accepting the user name and password you need to open a browser, go to gmail and log in, then open another tab in the same browser andgo to this address:
https://accounts.google.com/DisplayUnlockCaptcha

According to Google you may have to enter a captcha.

4) Immediately send an email from your code as this will allow it to be authorized to use your gmail account.

Hope this helps.

Turney answered 19/4, 2015 at 9:3 Comment(3)
@Turney Dear I have try all this. All worked on my local host but not on live server. I'm facing this error and no success till after 4 hours search and try of everything. "Failed to authenticate on SMTP server with username "[email protected]" using 2 possible authenticators"Clower
I didn't give much attention to step 3, but it actually solved the problemHerbartian
step 3 is what I was missingPerinephrium
B
5

I found that what evad said was true, but I had to change his work a little bit for the current version of Swift Mailer. Now it is:

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

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

Should work fine.

Bryophyte answered 15/2, 2012 at 11:22 Comment(3)
Hos is it different from fullybaked solution?Wesson
this is the same as the aboveAndradite
If anyone has an email with a google apps account using your own registered domain such as [email protected] : #17970596Mallis
S
4

The GMail SMTP system has it's issues given the SSL and ports. I find it hard to get it to work with PHP nicely.

The best thing I have found, that does work is phpGMailer. You may be able to sift through that code to see how they got it to work, but that has always worked flawlessly for me.

I know this does not address the SwiftMail issue, just figured I would point that out :)

Shevlo answered 13/8, 2010 at 16:47 Comment(1)
Thanks, I'll look it up. Still, I wanna fix this.Pizarro
M
3

465 is the port for ssl, 587 is used for tls encryption (look at http://swiftmailer.org/docs/sending.html#encrypted-smtp)

Musquash answered 23/9, 2012 at 12:7 Comment(0)
O
1

I also came here after hours of research. I finally found the true answer. I wanted to send email FROM google mail servers and not from my host with smtp authentication.

You can trace an email with its full headers inside of gmail, follow this guide.

https://support.google.com/mail/answer/29436?hl=en

@fullybaked had the right answer for authenticating your email via smtp but you would still be sending via your host.

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

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

@ducin was correct with the different ports and encryption types.

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')

OR more modern and more secure, use;

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')

If you want to send directly from a gmail server you need to set the authorization mode. Plain is default.

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

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

@gene is also correct, you do have to authenticate your app, so follow his instruction.

Further to prevent your email from landing in the spam folder, you will also have to add dns text records with DKIM (domain keys)

https://support.google.com/a/answer/174124?hl=en

SPF records

https://support.google.com/a/answer/33786?hl=en

and DMARC

https://support.google.com/a/answer/2466580?hl=en

Outrageous answered 8/12, 2017 at 0:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.