My form needs to have multiple email addresses. I have a form that has checkboxes. Every checkbox that is checked should be added to where the emails' recepient list. The data is getting passed correctly, I know this because if I echo it out on a new page it will correctly show each of the values. I'm using $_POST
.
The variable to append is called $email_to
.
It gets sent in: @mail($email_to, $email_subject, $email_message, $headers);
With a static $email_to
value the form functions properly and emails the data.
So far I've triedforeach($_POST['rep'] as $rep_num) { $emailto = $rep_num;}
foreach($_POST['rep'] as $rep_num[]) { $emailto = $rep_num[];}
I think the foreach is lacking something, but I can't figure out what. It can echo it out fine, but not store it in a variable. Can anyone point me in the direction of what I need to?
HTML
<div class="clearfix email_boxes">
<input type="checkbox" name="rep[]" value="02@address.com,">Lorem Ipsum 01
<input type="checkbox" name="rep[]" value="02@address.com,">Lorem Ipsum 02
<input type="checkbox" name="rep[]" value="03@address.com,">Lorem Ipsum 03
</div>
You need to use array_push
or the shorthand square brackets []
to add items to an array.
For example
$emails = array();
foreach($_POST['rep'] as $email) {
// Each $email is added as the next array entry, using []
$emails[] = $email;
}
// Convert the array to a comma separated string
$recipients = implode(',', $emails);
mail($recipients, $subject, $message);
foreach($_POST['rep'] as $rep_num) { $emailto = $rep_num;}
Here you are putting all emails in $emailto variable. So every time the loops run it erase the old one and save the new one. So at the end you are getting the last email address.
So you can use an array to save the email address. and then send email one by one. You can use a counter inside your loop to check how many times your loop run and then you can use that counter as a loop counter for sending email.
Try this:
foreach($_POST['rep'] as $key => $rep_num) {
$emailto = $rep_num;
}
Att.
With a slight modification to what you already had:
You're welcome to use it. (pre-tested)
<?php
if(isset($_POST['submit'])){
$email = "yourEmail@example.com";
$email_subject = "Subject here";
$email_message = "The message";
$headers = "From: $email" . "
" .
"Reply-To: $email" . "
" .
"X-Mailer: PHP/" . phpversion();
foreach($_POST['rep'] as $to) {
mail($to, $email_subject, $email_message, $headers);
}
} // ending brace for if(isset($_POST['submit']))
?>
<form method="post" action="">
<div class="clearfix email_boxes">
<input type="checkbox" name="rep[]" value="email_1@example.com">Lorem Ipsum 01
<input type="checkbox" name="rep[]" value="email_2@example.com">Lorem Ipsum 02
<input type="checkbox" name="rep[]" value="email_3@example.com">Lorem Ipsum 03
</div>
<input type="submit" name="submit" value="Send Email to Users">
</form>