How to send mail to list of user of database table in PHP?

 


Let's start this article to send emails to a list of users dynamically.

Steps

1. First create a database 

2. Create a table where you will store the Email-ID of different users.

3. Insert data into the table.

4. Write code to fetch data using Mysql Query.

5. Pass the table data into the PHP Email function to send emails to multiple users.

Here is a example

<?php 

$conn=mysqli_connect('localhost','root','','phpcode' or die("connection failed");

$sql="select * from email";

$result=mysqli_query($conn,$sql);

if(mysqli_num_rows($result))

{

    while($row=mysqli_fetch_array($result))

    {

       $addresses[] = $row['email'];

       $name[]=$row['name'];

    }

}

$to = implode(", ", $addresses);

$subject = 'PHP Email projects';

$from = 'example@gmail.com';

// To send HTML mail, the Content-type header must be set

$headers  = 'MIME-Version: 1.0' . "\r\n";

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

 

// Create email headers

$headers .= 'From: '.$from."\r\n".

    'Reply-To: '.$from."\r\n" .

    'X-Mailer: PHP/' . phpversion();

 

// Compose a simple HTML email message

$message = '<html><body>';

$message .= '<h1 style="color:#f40;">Hi Guys!</h1>';

$message .= '<p style="color:#080;font-size:18px;">PHP Email Projects</p>';

$message .= '</body></html>';

 

// Sending email

if(mail($to, $subject, $message, $headers)){

    echo 'Your mail has been sent successfully.';

} else{

    echo 'Unable to send email. Please try again.';

}

?>

I hope this article would help you. Kindly share with others. Thank you!

Comments