【发布时间】:2026-01-20 20:10:01
【问题描述】:
我想一次向多个用户发送电子邮件,但在这种情况下,邮件会多次发送给它自己的一个用户。
尝试只向每个人发送一次电子邮件(不要向用户发送垃圾邮件) 它不适用于这种方法,任何人都可以再次帮助这件事。
public function create()
{
$users = User::where('user_type', 2)->get();
$auto_email_templates = AutoEmailTemplate::all();
foreach ($users as $user) {
foreach($auto_email_templates as $mail){
if( $user->created_at < Carbon::now()->subDays($mail->days)){
Mail::to($user->email)->send(new Automail($mail));
$mail = new EmailSave;
$mail->user_id = $user->id;
$mail->email_id =$mail->id;
$mail->save();
}
}
}
}
public function create()
{
$users = User::where('user_type', 2)->get();
$auto_email_templates=AutoEmailTemplate::all();
foreach($auto_email_templates as $mail) {
foreach ($users as $user) {
if( $user->created_at < Carbon::now()->subDays($mail->days)){
if (EmailSave::where('email_id', '=', Input::get('email_id'))->exists()) {
Mail::to($user->email)->send(new Automail($mail));
}
else {
return false;
}
$mail = new EmailSave;
$mail->user_id = $user->id;
$mail->email_id =$mail->id;
$mail->save();
}
【问题讨论】:
-
您的循环次数过多。内循环也再次循环。因此,如果
$auto_email_template中有数据,那么相同的电子邮件将被发送两次。 -
因为您使用的是嵌套的 foreach 循环,这就是您面临此问题的原因。
-
你想用foreach($auto_email_templates as $mail)做什么?
-
@Sehdev 这就是他应该向我们解释的内容
-
@Sehdev Foreach($auto_email_templates as $mail) 是发送到电子邮件的模板。基本上,我正在尝试向所有用户发送自动邮件。因此,auto_email_templates 是发送电子邮件的模板。
标签: php laravel email laravel-5 sendmail