如何发送多个Laravel邮件

时间:2019-06-05 03:21:22

标签: php laravel-5.4

我发送到1个帐户,但是在我要发送多封邮件的1个帐户中发送了2次

Laravel

public function get_sendmail(Request $request) {

        $this->validate($request, [
            'email' => 'required|email',
            'subject' => 'min:2',
            'message' => 'min:10']);

        $recipients = [ ["email" => "$request->email"], ["email" => "$request->email"] ];

        $data = array(
            'subject' => $request->subject,
            'bodyMessage' => $request->message
        );

        foreach($recipients as $recipient) {
            // here you declare variables accesable in view file
            $dataToPassToEmailView = [];
            // **key** of this table is variable **name in view**
            $dataToPassToEmailView['recipient'] = $recipient;

            Mail::send('email.contact', $dataToPassToEmailView, function($message) use ($recipient, $data) {
                $message->to($recipient['email']);
                $message->subject($data['subject']);

            });
        }

            return redirect()->back()->with('message', 'success!');

        }

谢谢

1 个答案:

答案 0 :(得分:0)

您的$recipients具有两次保存的相同地址,这是因为您要将相同的$request->email添加到了两个recipients电子邮件密钥中。

 $recipients = [ 
                   [
                      "email" => "$request->email"
                   ],
                   [
                      "email" => "$request->email"
                   ] 
              ];

要解决此问题,您可以将$request->email作为数组发送。如果请求来自表单,请尝试以下操作:

<form action="{{ route('your-sendmail-route') }} method="YOUR METHOD">
    @csrf
    <label>First email:</label>
    <input name="email[]" type="email" class="email">
    <label>Second email:</label>
    <input name="email[]" type="email" class="email">
    <label>Third email:</label>
    <input name="email[]" type="email" class="email">
    <button type="submit">Send mail</button>
</form>

提交此表单时,在您的控制器中您会收到一系列电子邮件,然后可以对其进行迭代:

foreach($request->email as $email) {
    // here you declare variables accesable in view file
     $dataToPassToEmailView = [];
    // **key** of this table is variable **name in view**
     $dataToPassToEmailView['recipient'] = $email;
     Mail::send('email.contact', $dataToPassToEmailView, function($message) use 
         ($recipient, $data) {
             $message->to($email);
                 $message->subject($data['subject']);
            });
     }

我认为这应该可以解决您的问题。