Laravel-8技术问题:如何在控制器的邮件发送函数中用声明变量替换硬编码邮箱地址
Let's get this sorted out quickly—here's what you need to adjust to replace the hardcoded email with your $site_email variable, plus a couple of small fixes I spotted:
Step 1: Extract the Actual Email from Your Model
First off, $site_email is an instance of your InfoSite model, not a raw email string. You need to pull the email field value from it. Let's store it in a clear, readable variable:
$recipientEmail = $site_email->email;
Step 2: Pass Variables to the Closure
The closure inside Mail::send() can't automatically access variables from the outer function scope. You need to explicitly pass them using the use keyword—both $data (since you need it for the subject and sender) and the new $recipientEmail variable.
Step 3: Fix the Subject Reference
Your original code uses $data->subjects, but $data is an associative array, not an object. Swap that out for $data['subject'] to avoid an error.
Full Modified Code
Here's the updated sendemail function with all these fixes applied:
public function sendemail($contact) { $data = [ 'name' => $contact['name'], 'email' => $contact['email'], 'subject' => $contact['subject'], 'message' => $contact['message'] ]; $site_email = InfoSite::select('email')->first(); if(!$site_email) return $this->error("Site Contact Email does not exist", 404); // Pull the email address from the model instance $recipientEmail = $site_email->email; Mail::send('mail', $data, function($mail_message) use ($data, $recipientEmail) { // Use the dynamic site email instead of hardcoding $mail_message->to($recipientEmail)->subject($data['subject']); $mail_message->from($data['email']); }); // Optional: Add a success response if your controller uses a standard format return $this->success("Email sent successfully"); }
Quick Bonus Tip
For better deliverability, consider setting a consistent sender email in your Laravel .env file (like MAIL_FROM_ADDRESS) and using the user's email as a reply-to instead:
$mail_message->from(env('MAIL_FROM_ADDRESS'))->replyTo($data['email']);
This helps avoid spam flagging since most mail providers prefer senders to match verified domain addresses.
内容的提问来源于stack exchange,提问作者user11352561

