gamn2090
gamn2090

Reputation: 1

Send a mail in PHP laravel with sendgrid and GCloud

my problem is the following; I'm doing a proyect with Laravel 5.4, and I want to send mails from the system, the problem is that I'm using sendgrid to do it, and in local it's just sendin fine, BUT when I deploy in Google Cloud mails are not being sent, the error it throws is "conection timeout #110"

here's my code: .env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=MY-USERNAME
MAIL_PASSWORD=MY-PASS
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="MY-NAME"
MAIL_FROM_ADDRESS=MY-USER
SENDGRID_API_KEY='MY-API-KEY'

my controller:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function factura(request $request)
{   
    $this->validate($request, [
            'Student_name' => 'required',
            'datos_facturación' => 'required',
            'cuit' => 'required',
            'facturaconceptopago' => 'required',
            'servicio' => 'required',
            'monto' => 'required|max:16',
            'details' => 'required',
        ],
        [
           'Student_name.required' => 'Debe introducir el nombre del Alumno.',
           'datos_facturación.required' => 'Debe seleccionar que datos de facturación usará.',
           'cuit.required' => 'Debe introducir el número de CUIT.',
           'facturaconceptopago.required' => 'Elija el cocepto de su pago.',
           'servicio.required' => 'Seleccione el servicio por el que hará la factura.',
           'monto.required' => 'Ingrese el monto a facturar.',
           'details.required' => 'Ingrese los detalles de la facturación.',
        ]
    );

    $post         = $request->all();
    $student      = Student::find($post['id_hidden']);
    $Represen     = Representative::find($student->representative_id);

    $cant         = Student::getRepresentativeId($student->representative_id);
    $cont         = count($cant);

    if(isset($post['hermanos']) && $post['hermanos'] == 'on'){
        $hermano = 1;
        if($cont > 1){
           $student = $cant;
           $students = $cant;
        }else{
            $students = $student;
        }
    }else{
        $hermano = 0;
        $students = $student;
        $cont = 1;
    }

    $school     = new School;
    $grade      = new Grade;
    //recuperar los precios activos
    Date::setLocale('es');
    $date        = Date::now();

    $today       = $date->format('Y-m-d');       
    $start       = Date::now()->startOfMonth()->format('Y-m-d');
    $end         = Date::now()->endOfMonth()->format('Y-m-d');

    $priceObject = Price::getPrice($today, $start);
    $price_lunch       = $priceObject->lunch_price;     

    $price_home      = $priceObject->vianda_price; 

    $invoice      = InvoiceHistoric::max('id');

    $Invoice                     = new InvoiceHistoric;
    $Invoice->student_id         = $post['id_hidden'];
    $Invoice->out_of_date        = $post['outofdate'];
    $Invoice->emision_date       = date("Y-m-d");
    $Invoice->Servicio           = $post['servicio'];
    $Invoice->invoice_type       = $post['invoice_hidden'];
    $Invoice->discount           = $post['discount'];
    $Invoice->details            = $post['details'];
    $Invoice->numero             = $invoice+1;
    $Invoice->hermano            = $hermano;
    $Invoice->concepto_pago      = $post['facturaconceptopago'];

    if($post['facturaconceptopago'] == 1)
    {
        $Invoice->monto = $post['monto'];
    }else{
        $Invoice->monto = $student['debt'] ;
    }
    $Invoice->save();

    $pdf = PDF::loadView('invoices.factura_pdf', compact('cont','post','student','invoice','students','school', 'grade'));

    $folder = storage_path('Facturas/');        

    if (!file_exists($folder)) {
        File::makeDirectory($folder);
        $path = storage_path('Facturas/')."Factura_".$Invoice->numero."_".$Invoice->invoice_type.".pdf";
        $pdf->save($path);
    }else{
        $path = storage_path('Facturas/')."Factura_".$Invoice->numero."_".$Invoice->invoice_type.".pdf";
        $pdf->save($path);
    }        

   switch ($request->boton_enviar) {
        case 'descargar':   
                if($Invoice->invoice_type == 'Resumen'){
                    return $pdf->download('Resumen.pdf');
                }else{
                    return $pdf->download('Factura.pdf');
                }
        break;
        case 'enviar_mail':                    
                    $data = ['message' => 'Servicio de Envio Automático',
                             'students' => $students, 
                             'cont' => $cont, 
                             'date' => $date, 
                             'path' => $path, 
                             'student' => $student, 
                             'representative' => $Represen];
                    $mails = explode(';' ,$Represen->emails);

                    Mail::to($mails, 'Representante de '.$student->name)->send(new TestEmail($data));

        return redirect()->route('Factura-lista');
        break;          
    }

}

TestEmail.php:

<?php

namespace App\Mail;

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

class TestEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function build()
    {
        $address = '[email protected]';
        $subject = 'Servicio de Envio automático';
        $name = 'DHSystem';

        $headerData = [
            'category' => 'category',
            'unique_args' => [
            'variable_1' => 'abc'
            ]
        ];

        $header = $this->asString($headerData);

        $this->withSwiftMessage(function ($message) use ($header) {
            $message->getHeaders()
                    ->addTextHeader('X-SMTPAPI', $header);
        });

        $message = $this->data['message'];
        $students = $this->data['students'];
        $cont = $this->data['cont'];
        $date = $this->data['date'];
        $path = $this->data['path'];
        $student = $this->data['student'];
        $representative = $this->data['representative'];

        return $this->view('emails.sendmail', compact('message',
                                                  'students',
                                                  'cont',
                                                  'date',
                                                  'path',
                                                  'student',
                                                  'representative'))
                ->from($address, $name)
                ->cc($address, $name)
                ->bcc($address, $name)
                ->replyTo($address, $name)
                ->subject($subject)
                ->attach($path)
                ->with([ 'data' => $this->data ]);
}

    private function asJSON($data)
    {
        $json = json_encode($data);
        $json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);

        return $json;
    }


    private function asString($data)
    {
        $json = $this->asJSON($data);

        return wordwrap($json, 76, "\n   ");
    }
    }

I'm using this page for references: https://sendgrid.com/docs/Integrate/Frameworks/laravel.html

As I said from my local it's being sendt but the problem comes with GCloud, and I've already tryed using the 2525 port and it's the same

Upvotes: 0

Views: 1269

Answers (2)

Christian Cruz
Christian Cruz

Reputation: 668

The same thing happened to me, I just solved it like that:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=2525
MAIL_USERNAME=USER-API-SENDGRID
MAIL_PASSWORD=API-KEY-SENDGRID
MAIL_ENCRYPTION=tls

When using port 2525 it is necessary to specify the TLS

Upvotes: 2

Kenneth Sunday
Kenneth Sunday

Reputation: 895

You can't use GMAIL as your email service provider for your send mail function. You may use sendgrid but you need first to have a sendgrid account then you must have all the control to your domain manager so u can update your DKIM and SPF settings so then can validate you the ownership or have administrative access to that certain access.

You may also want to consider mandrill service of mailchimp, this is easier to implement though it is now paid service. Or Mailjet as well. for testing you may check sendblue if you are just testing the email service that will act like a production.

Upvotes: 0

Related Questions