trying to send mail using swift mailer, gmail smtp

2019-01-08 09:26发布

Here is my code:

<?php
require_once 'Swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465)
  ->setUsername('me@ff.com')
  ->setPassword('pass');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('me@ff.com' => 'MY NAME'))
  ->setTo(array('you@ss.com' => 'YOU'))
  ->setBody('This is the text of the mail send by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');  
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);
?>

AFter RUNNING GOT THIS ERROR...

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Expected response code 220 but got code "", with message ""' in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php:406

Stack trace: 
#0 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(299): Swift_Transport_AbstractSmtpTransport->_assertResponseCode('', Array) 
#1 /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php(107): Swift_Transport_AbstractSmtpTransport->_readGreeting() 
#2 /home/sitenyou/public_html/Swift/lib/classes/Swift/Mailer.php(74): Swift_Transport_AbstractSmtpTransport->start() 
#3 /home/sitenyou/public_html/sgmail.php(16): Swift_Mailer->send(Object(Swift_Message)) 
#4 {main} thrown in /home/sitenyou/public_html/Swift/lib/classes/Swift/Transport/AbstractSmtpTransport.php on line 406

8条回答
劳资没心,怎么记你
2楼-- · 2019-01-08 10:10

Swift SmtpTransport - Code (send a email)

The SMTP of GMAIL is: smtp.googlemail.com

The Full Code:

<?php
$pEmailGmail = 'xxxx@gmail.com';
$pPasswordGmail = '********';
$pFromName = 'MundialSYS.com'; //display name

$pTo = 'xxxxxx@xxxx.xxx'; //destination email
$pSubjetc = "Hello MundialSYS"; //the subjetc 
$pBody = '<html><body><p>Hello MundialSYS</p></html></body>'; //body html

$transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')
            ->setUsername($pEmailGmail)
            ->setPassword($pPasswordGmail);

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

$mEmail = Swift_Message::newInstance();
$mEmail->setSubject($pSubjetc);
$mEmail->setTo($pTo);
$mEmail->setFrom(array($pEmailGmail => $pFromName));
$mEmail->setBody($pBody, 'text/html'); //body html

if($mMailer->send($mEmail) == 1){
    echo 'send ok';
}
else {
    echo 'send error';
}
?>
查看更多
迷人小祖宗
3楼-- · 2019-01-08 10:12

For google apps, in addition to setting to port 465 and ssl as recommended in the accepted answer, you may have to enable allow less secure apps setting, as per https://stackoverflow.com/a/25238515/947370

查看更多
登录 后发表回答