Search code examples
phplaravelphpmailer

Contact form in laravel how to arrange mailercontroller and env file?


i have a form where visitor of my site can enter name ,email address and message, i have provided my gmail account credential in env file

//here is the ENV File Configuration

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=abc@gmail.com
MAIL_PASSWORD=bcccc124444
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=abc@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

and phpmailer code is below

public function sendmail($email,$name,$message) {


       //dd($email,$name,$message);
        require base_path("vendor/autoload.php");
        $mail = new PHPMailer(true);     // Passing `true` enables exceptions

        try {
 $mail->SMTPDebug =0;
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';             //  smtp host
        $mail->SMTPAuth = true;
        $mail->Username = 'abc@gmail.com';
        $mail->Password ='mypassword';
        $mail->SMTPSecure = 'tls';                  
        $mail->Port =587;                        
        $mail->setFrom($email,$name);
        $mail->addAddress('receivemail@gmail.com');
        $mail->isHTML(true);  
        $mail->Subject = 'WebQuery';
        $mail->Body =$message;
if( !$mail->send() ) {
               dd('not send');
                return back()->with("failed", "Email not sent.")->withErrors($mail->ErrorInfo);
            }
            
            else {
                dd('send');
                return back()->with("success", "Email has been sent.");
            }

        } catch (Exception $e) {
            dd($e);
             return back()->with('error','Message could not be sent.');
        }
    }

why i get all the time email from abc@gmail.com why not from email which visitor enter in form how to customize the email function and env in laravel 8


Solution

  • It's because you are forging the from address. Don't do that. It's not only a bad idea, but several large email providers (including gmail) prevent you from doing it, and will substitute your account name instead. Send such messages from your own address, and provide the submitter's address in a reply-to header. That way a recipient can hit reply and have a message go to the right place without having to forge anything.

    This is also what the PHPMailer examples show you how to do.

    A secondary issue is that this function will crash the second time it's called because you have an unconditional load of autoload.php, which will result in a fatal error. In a Laravel app, you should not need to load that autoloader yourself anyway; the app will take care of it for you.