vue.jsaxioslaravel-9mailtrap

Failing to send Email (Mailtrap) with Laravel 9 , by getting data from Vue.js 3 component , with Axios


Hello when i get some data on my Vue app (from 2 forms, 1 select and 1 table), i want to click a button to send that data to the email put on the respective form. With my code, i am able to show the data i want to send, in a output i create on my app, as testing, however no mail is sent. My .env file is filled correctly and here are my other files

I created a mailable ComprasMail

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class ComprasMail extends Mailable
{
    use Queueable, SerializesModels;
    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $subject = 'Compra Efectuada com Sucesso';
        return $this->view('Email.comprasMail')->subject($subject);
    }
}

I created a blade file por my mail template

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="{{ str_replace('_', '-', app()->getLocale()) }}">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Material+Icons"rel="stylesheet">

        <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/img/apple-touch-icon.png">

    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <!-- Site CSS -->
    <link rel="stylesheet" href="/css/style.css">
    <!-- ALL VERSION CSS -->
    <link rel="stylesheet" href="/css/versions.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="/css/responsive.css">
    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/custom.css">

    <link rel=”stylesheet” href=”https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css”>

        <!-- Modernizer for Portfolio -->
        <script src="/js/modernizer.js"></script>


    </head>
    <body>
   
    <tr>
    <div id="hosting" class="section wb" style="background: rgb(248, 248, 248)">
    <br>
    <br>
    <table  cellpadding="0" height="100" width="100%">
    <tr>
    <td text-align="center" valign="top" class="email-container">

        <div>
        <td text-align='center' style='text-align:center'><a href="http://127.0.0.1:8000/home" target="_blank">
                 
        </div>
        <br>


        <div class="row dev-list ">
            
            <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 wow fadeIn" data-wow-duration="1s" data-wow-delay="0.3s">

                <div class="wow fadeIn" text-align="center" style="background-color: rgba(0, 0, 0, 0.10); border-radius: 15px;" data-wow-duration="1s" data-wow-delay="0.3s">
                    <br>
                    <div class="message-box">
                        <div class="widget-title">
                            <h3 style="color: #E62B36; font-family: Eczar;"><strong>Bom dia caro {{$data['nome']}}</strong></h3>
                            <h4 text-align="center">  {{$data['transportadora']}}  </h4>
                            
                            
                              
                        </div>
                        <!-- end title -->
                        
                    </div>
                    <hr>
                    <h6 text-align="center"> © {{ date('Y') }} Desafio Tecnico. Todos os Direitos Reservados</h6>
                    <br>
                    <br>
                </div>
                <!--widget -->
                <br>
            </div><!-- end col -->

        </div><!-- end row -->
</tr>
         </table>
    </div><!-- end container -->

Here is my route

Route::post('/mail-send', [ProdutoController::class, 'mailSend']);

In my controller ( when i tried the return response that is commented, i simply have a 500 error)

public function mailSend(Request $request) {
   

       return response()->json([$request->all()]);  

        $email = $request->email;
        

        $data = [
            'name' =>  $request->nome,
            'transportadora' => $request->transportadora
        ];

        Mail::to($email)->send(new ComprasMail($data));

       
   
      /*  return response()->json([
            'message' => 'Mail has sent.'
        ], Response::HTTP_OK);*/
    }

In my vue component, first the button

<button :disabled="isDisabled2" @click="sentMail"> Add </button>

my data()

data() {
  return{
    compras:[],
    nome:"",
    email:"",
    transportadora:"",
    output:"",

My sentMail function


 sentMail(e) {
                e.preventDefault();
                var obj = this;
                axios.post('/mail-send', {  
                    nome: this.nome,  
                    email: this.email,
                    transportadora: this.transportadora,
                    compras: this.compras 
                }).then(function (response) {  
                    obj.output = response.data;  
                })  
                .catch(function (error) {  
                    obj.output = error;  
                });   
      
               },

With this , as i said, all the data i want to collect is correctly saved, and appear how it is expected when i call the obj.output. However i am not able to send any email . First i am trying to send emails with only the name, to see if it works, then after that i will put more on the template.

Thank you in advance

Edit: Just did this tutorial as a way to test if i at least could send a simple email and it worked, so at least i know now my problem it is not with the config with Mailtrap and it is somewhere inside my code

https://www.youtube.com/watch?v=WU4_HzTa6PM

Edit 2: Made some changes on the code,but still won't work. After some testing i concluded that my Mailable, and config are correct, since with the small tutorial i used for testing, it worked, however i am not understanding why the mail i set up isn't being sent

I would appreciate any kind of help. Thank You

Just more update. The error that is giving me on the console is:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)


settle.js:19 Uncaught (in promise) 
AxiosError
code
: 
"ERR_BAD_RESPONSE"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Request failed with status code 500"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
: 
{data: {…}, status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
: 
"AxiosError: Request failed with status code 500\n    at settle (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1116:12)\n    at XMLHttpRequest.onloadend (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1327:7)"
[[Prototype]]
: 
Error


Solution

  • After several time looking dor a solution to my problem, i finally was able to find one. In my Script i simply needed to change error to error.response.data For some reason, with only «error» it was always giving a 500 error

     sentMail(e) {
                 e.preventDefault();
                 var obj = this;
                 axios.post('/mail-send', {  
                    nome: this.nome,  
                    mail: this.email,
                    transportadora: this.transportadora,
                    compras: this.compras 
                    }).then(function (response) {  
                        obj.output = response.data;  
                    })  
                    .catch(function (error) {  
                        obj.output = error;  
                    });   
          
                   },