davy_yg's avatar
Level 27

I wonder why I didn't receive any email

My Codes are the following:

views/admin/contact.blade.php

  @extends('layout.master')

  @section('content')

  @if($message = Session::get('flash'))
      <div class="alert alert-success">
	       {{ $message }}
      </div>
  @endif

  @if($errors->any())
      @foreach($errors->all() as $error)
	     <div class="alert alert-danger">
		    <li>{{ $error }}</li>
	     </div>
      @endforeach
  @endif

  <div class="container">

      <a href="{{ url('profile') }}">BACK</a>
      <form action="{{ url('sendmail') }}" method="POST" enctype="multipart/form-data">
      @csrf
      <div class="form-group">
         <label>Nama</label>
          <input class="form-control" type="text" name="nama">
       </div>
      <div class="form-group">
          <label>Email</label>
          <input class="form-control" type="text" name="email">
      </div>
      <div class="form-group">
          <label>Pesan</label>
          <textarea class="form-control" type="text" name="pesan" rows="5"></textarea>
      </div>
       <button type="submit" class="btn btn-primary">Kirim</button>
      </form>
    </div>

   @endsection

    @push('script')

    <script>

  $(document).ready(function(){
       $(".alert").delay(5000).slideUp(300);
    });

  </script>

 @endpush

Web.php

  Route::get('contact', [ContactController::class, 'contact']);
  Route::post('sendmail', [ContactController::class, 'sendmail']);

ContactController.php

	use App\Mail\ContactMail;
	use Mail;
	use Session;

	class ContactController extends controller{

		public function contact(){
	
		return view('admin.contact');
	}

	public function sendmail(Request $request){
	
		Mail::to('d****@yahoo.com')
			->send(new ContactMail($request->all()));
		
		Session::flash('flash', 'Sukses mengirim email');
	
		return redirect()->back();
	}	
}	

Mail\ContactMail.php

	class ContactMail extends Mailable
	{
	use Queueable, SerializesModels;

	/**
 	* Create a new message instance.
 	*/

    public function __construct($data = [])
    {
        //
        $this->data['nama'] = $data['nama'];
	    $this->data['email'] = $data['email'];
	    $this->data['pesan'] = $data['pesan'];
    }

/**
 * Get the message envelope.
 */
public function envelope(): Envelope
{
    return new Envelope(
        subject: 'Contact Mail',
    );
}

/**
 * Get the message content definition.
 */
public function content(): Content
{
    return new Content(
        markdown: 'mail.contact',
        with: [
                'nama' => $this->data['nama'],
	            'email' => $this->data['email'],
	            'pesan' => $this->data['pesan'],
        ],
    );
}

views/mail/contact.blade.php

		<x-mail::message>
        # Introduction

       Nama: {{ $nama }}
       Email: {{ $email }}
       Pesan: {{ $pesan }}

      <x-mail::button :url="''">
      Button Text
      </x-mail::button>

      Thanks,<br>
      {{ config('app.name') }}
      </x-mail::message>

.env

MAIL_DRIVER=smtp 
MAIL_HOST=smtp.gmail.com 
MAIL_PORT=587 
MAIL_USERNAME=d****@gmail.com 
MAIL_PASSWORD=******* 
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME=LaravelTraining
MAIL_FROM_ADDRESS=d****@gmail.com

After filling in the form and press "Kirim" / Send I should be receiving an email but that's not what happen. I wonder why?

0 likes
5 replies
LaryAI's avatar
Level 58

Let's troubleshoot why you are not receiving the email in Laravel based on your provided setup. Here are the most common reasons and the steps to debug and fix them.


1. Check for Errors

First, make sure there are no errors being thrown in your application. After you submit the form:

  • Do you see any error messages on the page?
  • Do you see any errors in your laravel.log file (located in storage/logs/)?
  • If you have logging enabled and set to debug, you should see details of the mail sending process.

Tip: If you're in a production environment, you may not see errors directly. Check your logs.


2. Mail Configuration

From your .env:

MAIL_DRIVER=smtp 
MAIL_HOST=smtp.gmail.com 
MAIL_PORT=587 
MAIL_USERNAME=d****@gmail.com 
MAIL_PASSWORD=******* 
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME=LaravelTraining
MAIL_FROM_ADDRESS=d****@gmail.com

Common Issues:

  • Typo: The correct env variable should be MAIL_MAILER=smtp, not MAIL_DRIVER=smtp for Laravel 7 and above.
  • Make sure you have enabled Less secure app access in your Gmail account or set up an App Password if 2FA is on.
  • Google often blocks signins by default for scripts or 3rd party apps. Check your email for "security alert" or similar messages from Google.
  • Try using a different MAIL_PORT (465 for ssl; 587 for tls). You have it correct for tls.

How to fix:

  • Update your .env:
MAIL_MAILER=smtp 
MAIL_HOST=smtp.gmail.com 
MAIL_PORT=587 
MAIL_USERNAME=d****@gmail.com 
MAIL_PASSWORD=******* 
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME=LaravelTraining
MAIL_FROM_ADDRESS=d****@gmail.com
  • And in config/mail.php, make sure you have:
'mailers' => [
    'smtp' => [
        'transport' => 'smtp',
        'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
        'port' => env('MAIL_PORT', 587),
        'encryption' => env('MAIL_ENCRYPTION', 'tls'),
        'username' => env('MAIL_USERNAME'),
        'password' => env('MAIL_PASSWORD'),
        'timeout' => null,
        'auth_mode' => null,
    ],
    // ...
],

3. Cache Issues

If you change your .env, always run:

php artisan config:cache
php artisan cache:clear

4. Test the Mail System

Run this in tinker to see if mail works; it should not throw exceptions:

php artisan tinker
Mail::raw('Test email', function($msg) { $msg->to('[email protected]')->subject('Test'); });

Check your inbox.


5. Email is Being Sent, but Marked as Spam

  • Check your Spam folder!
  • Gmail and other providers can delay or block mail from automated apps.

6. Your Code Looks Good, but...

ContactController:

Mail::to('d****@yahoo.com')
    ->send(new ContactMail($request->all()));
  • Are you sure the address is correct?
  • Try sending it to another address or your own email for testing.

7. Add Validation and Error Handling

Wrap the Mail::to()->send() with a try/catch block to catch any errors:

public function sendmail(Request $request){
    try {
        Mail::to('d****@yahoo.com')->send(new ContactMail($request->all()));
        Session::flash('flash', 'Sukses mengirim email');
    } catch(\Exception $e) {
        Session::flash('flash', 'Failed to send email: ' . $e->getMessage());
    }
    return redirect()->back();
}

8. Mail Sending in Development

If this is a dev machine, use Mailtrap to test sending emails properly, as Gmail can be tricky for development environments.


Summary: Step-by-step Checklist

  1. Update .env: Use MAIL_MAILER, not MAIL_DRIVER.
  2. Clear cache: Run php artisan config:cache.
  3. Try sending a mail via Tinker.
  4. Check your laravel.log for error messages.
  5. Check your Spam/Junk folder.
  6. Ensure Gmail settings allow login from your app (app password or less secure apps).
  7. Wrap mail-sending in try/catch to get actual runtime error.
  8. If all fails, use a different SMTP server (Mailtrap, Mailgun, etc) for testing.

Example Wrap-up:

Update your .env:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=your_real_password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

Run:

php artisan config:cache
php artisan cache:clear

Test with:

// In routes/web.php for quick test
Route::get('/testmail', function () {
    Mail::raw('Hello!', function($msg) {
        $msg->to('[email protected]')->subject('Test');
    });
    return 'Sent!';
});

Visit /testmail and check your inbox and spam.


If you still do not receive email, closely check your storage/logs/laravel.log file for errors; the answer is likely there!


Let me know if you need further help or if you see any specific error messages.

davy_yg's avatar
Level 27

I get this error message, what's wrong? I am testing sending email in my local.

   D:\xampp82\htdocs\training>php artisan tinker
   Psy Shell v0.12.20 (PHP 8.2.12 — cli) by Justin Hileman
   > Mail::raw('Test email', function($msg) { $msg->to('[email protected]
   om')->subject('Test'); });

   Symfony\Component\Mailer\Exception\TransportException  Unable to connect with     STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error  messages:
   error:0A000086:SSL routines::certificate verify failed.
Glukinho's avatar

It's strange, smtp.gmail.com should provide valid certificate and you should be able to verify it. Are you sure you have this mail host? What config('mail.mailers.smtp.host') shows?

At least the problem is localized, that's good.

Try to add to config/mail.php:

'mailers' => [
        'smtp' => [
			// ...
            'verify_peer' => false,
        ],
]

And see what happens on sending test mail.

Please or to participate in this conversation.