首页 > 解决方案 > 如何配置 laravel 动态邮件发件人

问题描述

我的代码已经可以发送电子邮件了。但问题在于发件人的电子邮件名称。如何根据用户输入使其动态化。

我的控制器:

class contactUsController extends Controller{
function index(Request $req){
    $this->validate($req,
    [
        'email' => 'required|email',
        'message'=>'min:10'
    ]);

    $email = $req->input('email');
    $messages = $req->input('message');

    $data = array(
        'email' => $email,
        'bodyMessage' => $messages 
    );


    Mail::send('Email.emailsendcontact', $data, function($message) use ($data){
        $message->to('noticemyartheaddivision@gmail.com');
        $message->from($data['email']);   
        $message->subject('NoticeMyArt Customer Service');
    });
    return redirect('home');
}}

我的环境

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=noticemyartheaddivision@gmail.com
MAIL_PASSWORD='my Password'
MAIL_ENCRYPTION=tls

我的邮件.php

    'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
],

标签: laravelemailenvironment-variables

解决方案


fromLaravelMailable类中方法的第二个参数是name. 看到这个

// Illuminate\Mail\Mailable

/**
 * Set the sender of the message.
 *
 * @param  object|array|string  $address
 * @param  string|null  $name
 * @return $this
 */
public function from($address, $name = null)
{
    return $this->setAddress($address, $name, 'from');
}

因此,您可以使用以下方式设置发件人姓名和发件人电子邮件:

$message->from('some.email@here.com', 'Put Your Name Here');

希望能帮助到你。


推荐阅读