用户使用Laravel提交联系表单时接收电子邮件

时间:2019-07-05 19:05:31

标签: php laravel smtp laravel-blade

我目前有一个带有联系表的Laravel应用程序。提交表单后,用户名,电子邮件,电话号码和消息均正确存储在我的数据库中,该用户收到确认电子邮件,并且我没有收到任何错误。我的问题是,作为拥有表单的人,我如何使用Laravel接收用户名和我的gmail帐户消息?我正在使用gmail smtp发送电子邮件给提交表单的用户。我希望将用户联系表单信息(仅是姓名和消息)发送到我的Gmail电子邮件中。

MessagesController.php

    <?php
namespace App\Http\Controllers;
use App\Mail\MessageCreated;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Message;
use Illuminate\Support\Facades\Mail;

class MessagesController extends Controller
{
    public function submit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:2',
            'email' => 'required|max:255',
            'phonenumber' => 'required|min:11',
            'message' => 'required|min:5',
        ]);


        if ($validator->fails()) {
            return redirect(url()->previous() . '#contact')
                ->withErrors($validator)
                ->withInput();
        }

        $message = Message::create($request->all());

        Mail::to($message->email)->queue(
            new MessageCreated($message)
        );


        return redirect('/')->with('success', 'Your message has been 
            successfully sent. We will reach out to you soon');
    }
}

型号:Message.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    protected $guarded = [];

    public function email(){
        return $this->belongsTo(Message::class);
    }
}

可邮寄:MessageCreated.php

<?php

namespace App\Mail;

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

class MessageCreated extends Mailable
{
    use Queueable, SerializesModels;

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

    public function build()
    {
        return $this->markdown('mail.message-created');
    }
}

用户收到的消息:message-created.blade.php

    @component('mail::message')

We appreciate you taking the time to contact us. We will be reaching out to you soon.

@component('mail::button', ['url' => 'mysamplesite.io'])
Back to homepage
@endcomponent

Thank you,<br>

@endcomponent

2 个答案:

答案 0 :(得分:5)

Laravel使它变得超级简单。

Mail::to() ...之后的控制器中,只需添加以下脚本片段:

Mail::raw("name: $message->name \n message: $message->message", function($message) {
      $message->to('your-gmail-address')
      ->subject('New contact form is submitted.');
 });

答案 1 :(得分:1)

您将电子邮件放入队列中,因此应ru php artisan queue:work发送或使用send功能而不是queue