用sendgrid和GCloud

时间:2017-12-02 17:35:27

标签: php laravel google-cloud-platform sendgrid email-integration

我的问题如下;我正在使用Laravel 5.4做一个proyect,我想从系统发送邮件,问题是我使用sendgrid来做这件事,而在本地它只是发送正常,但是当我在Google Cloud中部署邮件时,没有发送邮件,它引发的错误是"连接超时#110"

这是我的代码: .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'

我的控制员:

/**
 * 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 = 'DYNINGHALLSYSTEM@sendgrid.net';
        $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   ");
    }
    }

我使用此页面作为参考:https://sendgrid.com/docs/Integrate/Frameworks/laravel.html

正如我在当地所说的那样,但是问题来自GCloud,我已经尝试过使用2525端口而且它是相同的

2 个答案:

答案 0 :(得分:1)

同样的事发生在我身上,我就这样解决了:

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

使用端口2525时,需要指定TLS

答案 1 :(得分:0)

您无法使用GMAIL作为发送邮件功能的电子邮件服务提供商。您可以使用sendgrid,但首先需要一个sendgrid帐户,然后您必须拥有对您的域管理器的所有控制权,以便您可以更新您的DKIM和SPF设置,以便可以验证您的所有权或具有该特定访问权限的管理访问权限。

您可能还想考虑mailchimp的mandrill服务,虽然它现在是付费服务,但这更容易实现。或者Mailjet。对于测试,如果您只是测试将像生产一样的电子邮件服务,您可以检查sendblue。