如何使用Laravel发送电子邮件

时间:2019-05-14 08:13:04

标签: php laravel email gmail

我想在laravel中发送电子邮件,这是我正在使用的代码。 当我运行此代码时,它显示“邮件已成功发送”,但我没有在Gmail中保留任何电子邮件。代码有什么问题?

我已经测试了这个简单的代码。它运作完美。

Mail::send(['text' => 'emails.html'], ['name' => 'Jay'], function($message)
        {
            $message->to('to@gmail.com', 'To Philex')->subject('test emails');
            $message->from('from@gmail.com', 'Philex');
        });

但是我想使用快速邮件程序。 有人可以帮助我吗?

use Mail;
use Swift_SmtpTransport;
use Swift_Message;
use Swift_Mailer;


public function sendemail()
{

    $data_toview = array();
    $data_toview['bodymessage'] = "test from philex dev";

    $email_sender   = 'from@gmail.com';
    $email_pass     = 'yourpassword';
    $email_to       = 'to@gmail.com';

    // Backup your default mailer
    $backup = \Mail::getSwiftMailer();

    try{

        //https://accounts.google.com/DisplayUnlockCaptcha
        // Setup your gmail mailer
        $transport = new \Swift_SmtpTransport('smtp.gmail.com', 587, 'tls');
        $transport->setUsername($email_sender);
        $transport->setPassword($email_pass);

        // Any other mailer configuration stuff needed...
        $gmail = new \Swift_Mailer($transport);

        // Set the mailer as gmail
        \Mail::setSwiftMailer($gmail);

        $data['emailto'] = $email_sender;
        $data['sender'] = $email_to;
        //Sender dan Reply harus sama

        Mail::send('emails.html', $data_toview, function($message) use ($data)
        {

            $message->from($data['sender'], 'Laravel Mailer');
            $message->to($data['emailto'])
            ->replyTo($data['sender'], 'Laravel Mailer')
            ->subject('Test Email');

            echo 'The mail has been sent successfully';

        });

    }catch(\Swift_TransportException $e){
        $response = $e->getMessage() ;
        echo $response;
    }


    // Restore your original mailer
    Mail::setSwiftMailer($backup);

}

0 个答案:

没有答案