php Laravel Mail::send() 发送到多个 to 或 bcc 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26584904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:57:51  来源:igfitidea点击:

Laravel Mail::send() sending to multiple to or bcc addresses

phpemaillaravellaravel-4

提问by haakym

I can't seem to successfully send to multipleaddresses when using Laravel's Mail::send()callback, the code does however work when I only specify onerecipient.

使用 Laravel 的回调时,我似乎无法成功发送到多个地址Mail::send(),但是当我只指定一个收件人时,代码确实有效。

I've tried chaining:

我试过链接:

// for example
$emails = array("[email protected]", "[email protected]");
$input = Input::all();

Mail::send('emails.admin-company', array('body' => Input::get('email_body')), 
function($message) use ($emails, $input) {
    $message
    ->from('[email protected]', 'Administrator')
    ->subject('Admin Subject');

        foreach ($emails as $email) {
            $message->to($email);
        }
});

and passing an array:

并传递一个数组:

// for example
$emails = array("[email protected]", "[email protected]");
$input = Input::all();

Mail::send('emails.admin-company', array('body' => Input::get('email_body')), 
    function($message) use ($emails, $input) {
        $message
        ->from('[email protected]', 'Administrator')
        ->subject('Admin Subject');

        $message->to($emails);
});

but neither seem to work and I get failure messages when returning Mail::failures(), a var_dump() of Mail::failures() shows the email addresses that I tried to send to, for example:

但两者似乎都不起作用,并且在返回 Mail::failures() 时收到失败消息,Mail::failures() 的 var_dump() 显示了我尝试发送到的电子邮件地址,例如:

array(2) {
  [0]=>
  string(18) "[email protected]"
  [1]=>
  string(18) "[email protected]"
}

Clearly doing something wrong, would appreciate any help as I'm not understanding the API either: http://laravel.com/api/4.2/Illuminate/Mail/Message.html#method_to

显然做错了什么,希望得到任何帮助,因为我也不了解 API:http: //laravel.com/api/4.2/Illuminate/Mail/Message.html#method_to

I realise I could put the Mail::send()method in a for/foreach loop and Mail::send()for each email address, but this doesn't appear to me to be the optimal solution, I was hoping I would also be able to ->bcc()to all addresses once everything was working so the recipients wouldn't see who else the mail is being sent to.

我意识到我可以将该Mail::send()方法放在 for/foreach 循环和Mail::send()每个电子邮件地址中,但这在我看来并不是最佳解决方案,我希望->bcc()一旦一切正常,我也能够访问所有地址收件人不会看到邮件发送给了谁。

回答by Marcin Nabia?ek

I've tested it using the following code:

我已经使用以下代码对其进行了测试:

$emails = ['[email protected]', '[email protected]','[email protected]'];

Mail::send('emails.welcome', [], function($message) use ($emails)
{    
    $message->to($emails)->subject('This is test e-mail');    
});
var_dump( Mail:: failures());
exit;

Result - empty array for failures.

结果 - 失败的空数组。

But of course you need to configure your app/config/mail.phpproperly. So first make sure you can send e-mail just to one user and then test your code with many users.

但当然你需要app/config/mail.php正确配置你的。因此,首先确保您可以只向一个用户发送电子邮件,然后与许多用户一起测试您的代码。

Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .

此外,使用这个简单的代码,我的电子邮件都没有发送到免费邮件帐户,我只收到了我付费托管帐户上的收件箱的电子邮件,所以可能它们被某些过滤器捕获了(这可能是简单的主题/内容问题,但是我提到它以防万一你没有收到一些电子邮件)。

回答by Abhishek

If you want to send emails simultaneously to all the admins, you can do something like this:

如果您想同时向所有管理员发送电子邮件,您可以执行以下操作:

In your .env file add all the emails as comma separated values:

在您的 .env 文件中,将所有电子邮件添加为逗号分隔值:

[email protected],[email protected],[email protected]

so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):

因此,当您要发送电子邮件时,只需执行以下操作(是的!消息生成器实例的“to”方法接受一个数组):

So,

所以,

$to = explode(',', env('ADMIN_EMAILS'));

and...

和...

$message->to($to);

will now send the mail to all the admins.

现在将邮件发送给所有管理员。

回答by Toskan

the accepted answer does notwork any longer with laravel 5.3 because mailable tries to access ->emailand results in

接受的答案并没有与laravel 5.3再工作下去,因为可邮寄试图访问->email和结果

ErrorException in Mailable.php line 376: Trying to get property of non-object

Mailable.php 第 376 行中的 ErrorException:试图获取非对象的属性

a working code for laravel 5.3 is this:

laravel 5.3 的工作代码是这样的:

$users_temp = explode(',', '[email protected],[email protected]');
    $users = [];
    foreach($users_temp as $key => $ut){
      $ua = [];
      $ua['email'] = $ut;
      $ua['name'] = 'test';
      $users[$key] = (object)$ua;
    }
 Mail::to($users)->send(new OrderAdminSendInvoice($o));

回答by plus5volt

With Laravel 5.6, if you want pass multiple emails with names, you need to pass array of associative arrays. Example pushing multiple recipients into the $toarray:

在 Laravel 5.6 中,如果要传递多封带有姓名的电子邮件,则需要传递关联数组的数组。将多个收件人推入$to数组的示例:

$to[] = array('email' => $email, 'name' => $name);

Fixed two recipients:

固定两个收件人:

$to = [['email' => '[email protected]', 'name' => 'User One'], 
       ['email' => '[email protected]', 'name' => 'User Two']];

The 'name' key is not mandatory. You can set it to 'name' => NULLor do not add to the associative array, then only 'email'will be used.

'name' 键不是强制性的。您可以将其设置为'name' => NULL或不添加到关联数组中,然后才会'email'使用。

回答by Dunsin Olubobokun

In a scenario where you intend to push a single email to different recipients at one instance (i.e CC multiple email addresses), the solution below works fine with Laravel 5.4 and above.

如果您打算在一个实例中将一封电子邮件推送给不同的收件人(即抄送多个电子邮件地址),下面的解决方案适用于Laravel 5.4 及更高版本

Mail::to('[email protected]')
    ->cc(['[email protected]','[email protected]','[email protected]','[email protected]'])
    ->send(new document());

where documentis any class that further customizes your email.

其中document是进一步自定义您的电子邮件的任何类。

回答by Alexandre Ribeiro

I am using Laravel 5.6 and the Notifications Facade.

我正在使用 Laravel 5.6 和 Notifications Facade。

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

如果我用逗号分隔电子邮件设置变量并尝试发送它,我会收到错误消息:“给定的邮件地址不符合 RFC 2822, 3.6.2”

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

所以,为了解决这个问题,我从@Toskan 那里得到了解决方案的想法,编写了以下代码。

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

发送给一个或多个收件人对我有用。

回答by Radmation

This works great - i have access to the request object and the email array

这很好用 - 我可以访问请求对象和电子邮件数组

        $emails = ['[email protected]', '[email protected]'];
        Mail::send('emails.lead', ['name' => $name, 'email' => $email, 'phone' => $phone], function ($message) use ($request, $emails)
        {
            $message->from('[email protected]', 'Joe Smoe');
//            $message->to( $request->input('email') );
            $message->to( $emails);
            //Add a subject
            $message->subject("New Email From Your site");
        });

回答by Rizwan Mughal

it works for me fine, if you a have string, then simply explode it first.

它对我有用,如果你有绳子,那么先把它炸开。

$emails = array();

$emails = array();

Mail::send('emails.maintenance',$mail_params, function($message) use ($emails) {
    foreach ($emails as $email) {
        $message->to($email);
    }

    $message->subject('My Email');
});