Juus site developer
Juus site developer

Reputation: 21

How to generate unsubscribe link in email?

I have a newsletter system so when I want to send a message to all of my subscribers I send it trough a php file named post-processing.php.

Here is my post-processing.php code:

$count=$dbo->prepare("select * from sw_post where post_id=:post_id");
$count->bindParam(":post_id",$post_id,PDO::PARAM_INT,4);

if($count->execute()){
   echo " Success <br>";
   $row = $count->fetch(PDO::FETCH_OBJ);
   $sub=$row->sub;
   $post=$row->post;
} else {
   echo "Database Error ..";
print_r($count->errorInfo()); 

exit;
}
/////////////////////////

$dtl="";

$dtl .=$post. "\n\n";


@$headers.="Reply-to: $from_email\n"; 
$headers .= "From: $from_email\n"; 
$headers .= "Errors-to: $from_email\n"; 
//$headers = "Content-Type: text/html; charset=iso-8859-1\n".$headers;
// Above line is required to send HTML email 
$sql="select email_id, email from sw_email where status='A'"; 
$i=0;

foreach ($dbo->query($sql) as $row) {
   $url=$base_url."unsubscribe.php?email_id=$row[email_id]&email=$row[email]&todo=delete";
   $dtl .= "Click on the URL to unsubscribe  $url ";

Let's say I have three subscribers, and when I receive the email I get this outcome:

Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=1&[email protected]&todo=delete
Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=2&[email protected]&todo=delete
Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=3&[email protected]&todo=delete

But the outcome I want is only:

Click on the URL to unsubscribe: http://#.com/unsubscribe.php?email_id=1&[email protected]&todo=delete

I don't want the recipent to recive the links to unsubscribe to all of my subscribers. How do I fix this?

Upvotes: 0

Views: 3768

Answers (2)

SparK
SparK

Reputation: 5211

What you need to do is leave your message body untouched in a variable, outside the subscribers loop. Then, one by one you read its e-mail address, append the message and the link to a new variable. Call the mail function using only that e-mail address as receiver and that new variable as body. When the loop loops it will create a new var with message body and a new link to that other subscriber.

Upvotes: 0

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

Bind your email code inside of foreach after getting user lists

  @$headers.="Reply-to: $from_email\n"; 
  $headers .= "From: $from_email\n"; 
  $headers .= "Errors-to: $from_email\n"; 
//$headers = "Content-Type: text/html; charset=iso-8859-1\n".$headers;
$sql="select email_id, email from sw_email where status='A'"; 
foreach ($dbo->query($sql) as $row) {
    $dtl =$post. "\n\n";    

    $url=$base_url."unsubscribe.php?email_id=$row[email_id]&email=$row[email]&todo=delete";
    $dtl .= "Click on the URL to unsubscribe  $url ";

    mail('to_email','subject',$dtl,$headers); //this is your mail function
}

Upvotes: 1

Related Questions