简体   繁体   中英

Sending e-mail via Gmail using SwiftMailer

I'm using Slim PHP framework and trying to send e-mail via Gmail. The problem is when I am sending the e-mail, it will cause "Slim Application Error."

$mailer->send($message);

Here is my function to send the e-mail

function send_email($email)
{
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls')
        ->setUsername('pandala61@gmail.com')
        ->setPassword('yourpassword');

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


    // Create a message
    $message = Swift_Message::newInstance('Test mail')
        ->setFrom(array('from_email@gmail.com' => 'SENDER'))
        ->setTo(array('To_email@gmail.com'))
        ->setBody("Hello, test send mail");

    // Send the message
    $mailer->send($message);

} 

Before you use it, you must prepare your gmail account to do it: https://support.google.com/accounts/answer/2461835?hl=en Initializing: // Create Transport. You can use it in directly in routes.php (not good practice), in your config.php file is best. $transport = Swift_SmtpTransport::newInstance() ->setHost('smtp.gmail.com') ->setPort(465) ->setEncryption('ssl') ->setUsername('emailat@gmail.com') ->setPassword('passw') ; // Create Transport. You can use it in directly in routes.php (not good practice), in your config.php file is best. $transport = Swift_SmtpTransport::newInstance() ->setHost('smtp.gmail.com') ->setPort(465) ->setEncryption('ssl') ->setUsername('emailat@gmail.com') ->setPassword('passw') ;

    // Create Mailer instance with our Transport. To be ready to call it.

$mailer = Swift_Mailer::newInstance($transport);
</code>
Using: (Where you need to use it. eg: in UserController.php , you can use it.
<code>

    $message = Swift_Message::newInstance()
                    ->setSubject('Email from contact form')
                    ->setFrom(array('email@email.com'=> 'Me'))
                    ->setTo(array('youremail@email.com' => 'You'))
                    ->setBody("I am sending you an email from contact form");

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


    // Print the results, 1 = message sent!
    print($result);
</code>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM