无法在laravel 5中向电子邮件发件人发送电子邮件

无法在laravel 5中向电子邮件发件人发送电子邮件

问题描述:

My code is like this :

 public function sendMail(array $data)
    { 
        $data = explode('#', $data['id']);
        $email_from = Auth::user()->email;
        $email_to = $data[4];
        $subject = 'Send Email Test';

        $data_user = ['user_name' => $data[1], 'full_name' => $data[2].' '.$data[3] ];

        $sent = Mail::send('backend.auth.success_approved', $data_user, function ($mail) use ($email_to, $email_from, $subject)
                {
                    $mail->from($email_from)
                         ->to($email_to)
                         ->subject($subject);
                });
    }  

My configuration in mail.php :

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => 'myemail@gmail.com', 'name' => 'myname'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME', 'myemail@gmail.com'),
    'password' => env('MAIL_PASSWORD', 'mypassword'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,
];

It has successfully to send email. But it did not dynamic sender. It is the email sender of mail.php

How to keep its dynamic sender?

Thank you

This is impossible to send mail from dynamic sender if you are using Gmail server. For security purpose Gmail is converting your sender address to your default address. To prevent spamming many email server (like Gmail, Hotmail etc) don't let you do this. As an example you can send email from Barak Obama's email address.

If it is very important to send email from dynamic address for you, you can use raw php function mail()

$header = 'From: [FEEDBACK] <'.$email_from.'>'."
".'Reply-To:'.$email_from."
".'X-Mailer: PHP/' . phpversion();
$sent = mail('myemail@gmail.com',$subject,$body,$header);

This code will not work in localhost, unless you configure your xampp or wampp or mampp