在Laravel中发送电子邮件

时间:2014-07-28 18:52:08

标签: php email laravel mailgun

我尝试使用Laravel和mailgun.com上的帐户发送基本验证电子邮件。我已按照说明here进行操作并收到错误消息。这是我的代码:

Route::post('/register', array('before'=>'reverse-auth', function(){
    $data=Input::all();

    if ($data['password'] != $data['confirm-password']){
        return Redirect::to('/register');
    }

    $user = new User;

    $user->email=$data['email'];
    $user->password=Hash::make($data['password']);
    $user->first=ucfirst($data['first']);
    $user->last=ucfirst($data['last']);
    $user->address=$data['street'].", ".$data['city'].", ".$data['state']." ".$data['zip'];
    $user->phone=$data['phone'];
    $user->confirmation=Str::random(32);
    $user->confirmed=0;

    $user->save();

    Mail::send('emails.verify', $user->toArray(), function($message){
        global $user;

        $message->to($user['email'], $user['first']." ".$user['last']);
        $message->from('noreply@localhost', 'Do Not Reply');
    });
}));

我的错误如下:

Client error response [url] https://api.mailgun.net/v2/sandboxa666975e4b514342a58e4d7d3e6c2366.mailgun.org/messages.mime [status code] 400 [reason phrase] BAD REQUEST

我不知道我做错了什么。

顺便说一下,为什么$user不是函数中的对象?不应该global关键字强制它与函数外的$user对象相同吗?

1 个答案:

答案 0 :(得分:5)

你在匿名函数中混淆了一个带有数组的对象 另外,要将变量传递给匿名函数,可以使用use构造。

Mail::send('emails.verify', $user->toArray(), function($message) use ($user){
    //  Now you can use $user anywhere in the function without using global
    //  global $user;

    //  $user is an object not an array
    //  $message->to($user['email'], $user['first']." ".$user['last']);
    $message->to($user -> email, $user -> first." ".$user -> last) ->('You also want a subject here');
    $message->from('noreply@localhost', 'Do Not Reply');
});