Sending multiple CC's and BCCs with PHP PEAR MAIL - php

I have a project that I am working on at my job and I am using Pear's mailing. I need to use smtp because we need to be able to track everything from our mailserver. And users need to be able to log in before sending a company based email. We cannot use php's mail function fo this.
My problem is that I cant find any documentation on the net for sending CC and Bcc as well as sending multiple BCCs. It is very easy to do with php' mail funciton . All you do is add it to the $header variable like so
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
This is my code for the php function where I use PEAR
function sender_mail($email,$subject,$mailmsg, $cc, $bcc){
include("Mail.php");
/* mail setup recipients, subject etc */
//DEFAULT VALUE OF FROM
$from = "noreply#addata.net";
//GET EMAIL OF USER
$result = mysql_query("SELECT email, email_pass FROM u_perinfo WHERE user_id = '$_SESSION[uid]'")
or die("There was an error when grabbing your email information");
if(mysql_num_rows($result) > 0){
$row = mysql_fetch_array($result);
if($row[0] != ''){
$from = $row[0];
}
$email_pass = $row[1];
}
$recipients = "$email";
$headers["From"] = "$from";
$headers["To"] = "$email";
$headers["Subject"] = $subject;
$headers["Cc"] = "$cc"; //Line added by Me to see if it works
$headers["Bcc"] = "$bcc"; //Line added by Me to see if it works
//$mailmsg = "Welcome to Addatareference.com! \r\n\r\nBelow is your unique login information. \r\n\r\n(Please do not share your login information.)$accountinfo";
/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "smtp.emailsrvr.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "$from";
$smtpinfo["password"] = "$email_pass";
/* Create the mail object using the Mail::factory method */
$mail_object =& Mail::factory("smtp", $smtpinfo);
/* Ok send mail */
$mail_object->send($recipients, $headers, $mailmsg);
}
I have been trying to find a solution to this with no real info coming back my way. If someone could help me out with this I would be greatly appreciated.

There is a problem with Bcc though when using the PEAR Mail function: Thunderbird displays the Bcc header, so the recipient is not hidden, which is the whole point of Bcc. It is also displayed in the To: header list (since you have to include the Bcc list in recipients).
Edit: SOLVED - I found from another site that the solution is just to include the Bcc list in the $recipients, and not in any of the headers. It works!
Thus:
$bcc = "foo#example.com";
$to = "bar#example.com";
$headers = array(..other stuff.., 'To' => $to, ..rest of header stuff); // No Bcc header!
$recipients = $to.", ".$bcc;
$mail = $smtp->send($recipients, $headers, $message);
Edit #2: Acknowledging my source - http://raamdev.com/2008/adding-cc-recipients-with-pear-mail/

Have you tried to add multiple addresses "," separated?
$headers['Cc'] = 'cc#example.com, bb#example.com, dd#ex.com';
This might work, according to line 218 in the source.

You just need to add all to, cc, bcc in $recipients variable. Header decides where to send.

Related

php pear e-mail with bcc

I'm trying to send an e-mail with a bcc. I can send it with a bcc fairly easily, but that's not quite what I want. The code that does work is
$message = new Mail_mime();
$message->setTXTBody($_text);
...
$body = $message->get();
$thisSubject = $subject;
if (isset($_POST['_cc_sender'])) {
$extraheaders = array("Bcc"=>$from_email,
"From"=>$from_email,
"Subject"=>$thisSubject);
} else {
$extraheaders = array("From"=>$from_email, "Subject"=>$thisSubject);
}
$headers = $message->headers($extraheaders);
$mail_obj = Mail::factory("mail");
$mail_obj->send($to, $headers, $body);
Where an e-mail form can set "_cc_sender" to have the submitter receive a copy. The problem is that exposes the $to address. To hide it, I figured I'd just send the e-mail to the submitter with a bcc to the intended recipient, as so:
$message = new Mail_mime();
$message->setTXTBody($_text);
...
$body = $message->get();
$thisSubject = $subject;
if (isset($_POST['_cc_sender'])) {
$extraheaders = array("Bcc"=>$to,
"From"=>$from_email,
"Subject"=>$thisSubject);
$send_to = $from_email;
} else {
$extraheaders = array("From"=>$from_email, "Subject"=>$thisSubject);
$send_to = $to;
}
$headers = $message->headers($extraheaders);
$mail_obj = Mail::factory("mail");
$mail_obj->send($send_to, $headers, $body);
However, when I do that, I end up getting two messages sent to the $from_email. One seems to be the bcc because my (Thunderbird) message filters treat them differently - moving one into a subfolder.
To be clear, if I just use a bcc, the submitter gets a blind copy while the intended recipient gets the e-mail. However, when I try to switch who gets the bcc, both e-mails go to the submitter.
If I switch the bcc to a cc, I see both headers are set correctly (it is going to the $from_email with a cc to $to). However, the e-mail still gets sent to the $from_email twice.
I've done var_dumps of everything I can think of and they just show what I'd expect. From what I understand, the "to:" field / recipients is set in $mail_obj->send - it doesn't show up in my var_dumps - so I can't figure out why the send is messing up.
One thing I have discovered is that changing the Mail::factory parameter from "mail" to "sendmaiL" has removed the second e-mail. Now I'm just getting the one to the $send_to address. This suggests the problem is with the mail program, which may be handling the headers strangely.
I'd seen another post which suggested there should be a difference between the recipients list and the headers. When using "sendmail" (but not "mail"), that seems to be true. With "sendmail", the recipients list (first parameter in $mail_obj->send) is not shown in the headers - it's all a "bcc". Adding $from_email to the $send_tolist achieves the results I was looking for:
$message = new Mail_mime();
$message->setTXTBody($_text);
...
$body = $message->get();
$thisSubject = $subject;
if (isset($_POST['_cc_sender'])) {
$send_to = $from_email . "," . $to;
} else {
$send_to = $to;
}
$extraheaders = array("From"=>$from_email,
"Subject"=>$thisSubject);
$headers = $message->headers($extraheaders);
$mail_obj = Mail::factory("sendmail");
$mail_obj->send($send_to, $headers, $body);

Send email from email list from database using php, mysql [duplicate]

This question already has answers here:
PHP send mail to multiple email addresses
(13 answers)
Closed 3 years ago.
I am trying to send email to all the members email id's which is stored in the database. Here is the code
<?php
$sql = mysqli_query($con,"select email from email_list where email");
//$recipients = array();
while($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
$recipients[]= $row['email'];
}
$to = $recipients;
$repEmail = 'abc#gmail.com';
$subject = "$title";
$body = "$description";
$headers = 'From: xyz <'.$repEmail.'>'. "\r\n";
$headers .= 'Reply-To: abc#gmail.com' . "\r\n";
$headers .= 'BCC: ' . implode(', ', $recipients) . "\r\n";
if (mail($to, $subject, $body, $headers)){
echo "<script>alert('Email sent')</script>";
}
else {
echo "<script>alert('Email failed')</script>";
}
?>
In this above code email goes to 1 person.
When you look at the pho docs : mail() function
to
Receiver, or receivers of the mail. The formatting of this string
must comply with » RFC 2822.
Some examples are:
user#example.com
user#example.com, anotheruser#example.com
User
User , Another User
It clearly states "to" part should be in rfc2822 compliance. You are passing an array which is not acceptable and thus only first value is taken.
Also it's worth mentioning that:
Note: It is worth noting that the mail() function is not suitable for
larger volumes of email in a loop. This function opens and closes an
SMTP socket for each email, which is not very efficient. For the
sending of large amounts of email, see the » PEAR::Mail, and
» PEAR::Mail_Queue packages
.
Thus I'd suggest you to use some mailing library such as phpMailer or swiftmailer for better functionality or better use mail queue.
Your $to should be $to = "address#one.com, address#two.com, address#three.com"
So add
$recipients = array(
"youremailaddress#yourdomain.com",
// more emails here
);
$email_to = implode(',', $recipients); // your email address
add $email_to to your $to.

PHP mail() BCC - display only the end receivers address in To: header

I'm attempting to BCC to a list of subscribers from a database, using PHP mail(). Everything works, but I'm running into a problem that has troubled me all morning. I'm able to send the list with BCC, but are unable to append the receiving end email address to the deader "To:".
For example, I send the list to the following email addresses (test1#example.com, test2#example.com, and test3#example.com). Each email address receives an email and the other email addresses are hidden because of BCC.
My problem is that in the header, "To:" is displayed blank on all of the receiving ends of the list. That I understand and know that header won't display because I have only the BCC header within the outgoing message. I've attemted to for loop the process but I receive all of the emails, plus one for that address in one loop.
Here is my working code: The working code includes the loop that I attempted for solving the To: header. I'm able to send the email, though I receive all of the emails that were sent.
<?php
/*
Gathers the number of rows within the database. Used for the loop that displays the entire list in the BCC.
*/
session_start();
include_once '../dbconnect.php';
$result = mysql_query("SELECT * FROM news");
$num_rows = mysql_num_rows($result);
$rows = $num_rows;
/*
Requests the list from the database, please the list in a loop, displays the list only once, and places list in an operator.
*/
$result = mysql_query("SELECT * FROM `news`");
while($row = mysql_fetch_array( $result )) {
for ($x = 1; $x <= 1; $x++) {
$contacts.= "".$row['email'].",";
}
}
/*
ATTEMPT (It works... sort of): Sends mail to the list using BCC, displays the ONLY receivers email address in the To: header
*/
$result = mysql_query("SELECT * FROM `news`");
while($row = mysql_fetch_array( $result )) {
for ($x = 1; $x <= 1; $x++) {
$receiver= "".$row['email']."";
$to = "$receiver";
$subject = 'Test Email';
$headers = "From: example#example.com\r\n";
$headers .= "BCC: $contacts";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<h1 style="">Test Message</h1>';
$message .= '</body></html>';
mail($to,$subject, $message, $headers);
}
}
?>
My general thought was to loop, but I can't find a solution that actually solves this completely, by BBC to the list and displaying only the receiving ends email address in the To: header. Any thoughts or ideas?
Update with SMTP Server
I've been attempting to use the solution found in this thread and apply it to an SMTP server. Send the message using SendGrid was the ideal choice. I've come up with the below option, but the script only seems to send one message to one of the addresses in the database and not all the address.
<?php
require_once "Mail.php";
$sub = $_POST['subject'];
$ttl = $_POST['title'];
$img = $_POST['image'];
$bdy = $_POST['body'];
$lk = $_POST['link'];
mysql_connect("", "", "") or die(mysql_error()) ;
mysql_select_db("") or die(mysql_error()) ;
$result = mysql_query("SELECT `email` FROM news");
$num_rows = mysql_num_rows($result);
$receivers = array();
while ($row = mysql_fetch_array($result)) {
$receivers[] = $row['email'];
}
foreach ($receivers as $receiver) { }
$from = "test#example.com";
$to = $receiver;
$subject = $sub;
$mime = "1.0";
$ctype = "text/html; charset=ISO-8859-1";
$body = '
<html><body>
<p>Test Message!</p>
</body></html>
';
$host = "";
$port = "";
$username = "";
$password = "";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => $mime ,
'Content-Type:' => $ctype);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
The code includes some general improvements to your code. I have added inline comments to explain what I have done.
<?php
// General thing: If you do not need a session, do not start one ;)
session_start();
include_once '../dbconnect.php';
// Select only what you really need from the table. This saves you memory
// and it speeds up the query.
$result = mysql_query("SELECT `email` FROM news");
// You are not using these numbers in the script you showed us. I am just
// leaving them in here to show you, how you can reuse the "$result"
// variable without querying the database again.
$num_rows = mysql_num_rows($result);
// We are reusing the "$result" here without re-querying the database, which
// speeds the whole process up and takes load away from the database. We are
// storing all receivers in a dedicated variable, to reuse them later on.
$receivers = array();
while ($row = mysql_fetch_array($result)) {
$receivers[] = $row['email'];
}
// Now, instead of querying the database again, we are using our stored mail
// addresses in "$receivers" to send the emails one by one. We could have
// done this part in the "while" loop before, but I wanted to stay close to
// your code, so you would recognize it ;)
foreach ($receivers as $receiver) {
// I have removed the "for" loop here, because it runs only once. If a loop
// only runs once and you control all its input, you really do not need a
// loop at all (except some exceptions, just in case someone knows one^^).
// You can actually just put the value of $receiver in $to. PHP is pretty
// good at typecasting of scalar types (integers, strings etc.), so you do
// not need to worry about that.
$to = $receiver;
$subject = 'Test Email';
// I am putting the headers into an array and implode them later on. This
// way we can make sure that we are not forgetting the new line characters
// somewhere.
$headers = array(
"From: example#example.com",
"MIME-Version: 1.0",
"Content-Type: text/html; charset=ISO-8859-1",
// I have removed the "BCC" header here, because this loops send out an
// email to each user seperately. It is basically me sending an email to
// you. Afterwards I copy&paste all the content to another new mail and
// send it to another fella. You would never know that you both got the
// same mail ;)
);
$message = '<html><body>';
$message .= '<h1 style="">Test Message</h1>';
$message .= '</body></html>';
// Imploding the headers.
$imploded_headers = implode("\r\n", $headers);
mail($to, $subject, $message, $imploded_headers);
}
This code basically send out one email at a time. No one who receives such an email knows which email addresses the email went to.
As mentioned in the code, this snippet can be further optimized. Since email sending itself is a pretty difficult area, I would really suggest that you find some PHP library that bundles that whole thing and work with it. You can make so many mistakes with the whole email sending thing, that I would not run a script like that in production if you do not want to get marked as spam soon after.
Add \r\n to:
$headers .= "BCC: $contacts\r\n";
Each header must be on new line.

How can I add a .png to an outgoing PHP Email with HTML?

I've been trying to add a png to my php email for quite sometime with no luck. I tried the traditional methods and I've tried to add Base64 to both html and css using this site http://www.base64-image.de
But no matter what I do I get a blank header. Can anyone please tell me, step by step what I have to do to make a png appear on the email I send, and no it can't be an attachment. Thanks in advanced.
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$mail2 = new PHPMailer();
// set mailer to use SMTP
$mail2->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail2->Host = "smtp.comcast.net"; // specify main and backup server
$mail2->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_name#comcast.net
// pass: password
$mail2->Username = "name#comcast.net"; // SMTP username
$mail2->Password = "*******"; // SMTP password
$mail2->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail2->Port = 465; // TCP port to connect to
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
//$mail2->From = 'user#gmail.com';
//Set who the message is to be sent from
$mail2->setFrom('user#gmail.com', 'user');
// below we want to set the email address we will be sending our email to.
$mail2->AddAddress("$email");
//Set an alternative reply-to address
$mail2->addReplyTo('talk#gmail.com');
// below we want to set the email address we will be sending our email to.
//$mail2->AddAddress("$email");
// set word wrap to 50 characters
$mail2->WordWrap = 50;
// set email format to HTML
$mail2->IsHTML(true);
mail($to, $subject, $message, $headers);
$mail2->Subject = "Thanks";
$headers = "From: " . strip_tags($_POST['user#gmail.com']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['talk#gmail.com']) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<div style="height:130px; text-align:center; width:100%; background:#666;"> <img src="images/logo.png"/></div>';
$message .= '<p>Welcome,</p> ';
$message .= "<p>You have been added</p>";
$message .= "</body></html>";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail2->Body = $message;
$mail2->AltBody = $message;
if(!$mail2->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail2->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
This is very confused. Why are you calling mail() as well as using PHPMailer? I've no idea why you think you need to mess about with headers manually like that - the point of using a library like PHPMailer is so you don't have to concern yourself with things like that!
PHPMailer will not do anything with your image path if you just set Body - you need to pass your body into msgHTML() where it will look up the images and convert everything to embedded images.
There are examples provided with PHPMailer that show you how to do this (if not in the examples folder, look at the unit tests).
I can also see that you've based your code on an old example and are probably using an old version of PHPMailer, so I suggest you update to at least 5.2.10.

PHP send mail to 1 to 10 recepients

I am sure I am overlooking something here, all other mail scripts are working fine except this one. I have an HTML form which collects up to 10 email addresses. all I need to do it to iterate through them and if they are filled, send email to the recipient.
$email0 = 'email#email.com';
$email1 = 'some#email1.com';
$email2 = 'some#email2.com';
$email3 = 'some#email3.com';
$email4 = 'some#email4.com';
....... up to 10.
$i=1;
while($i<=10)
{
$temp = 'email'.$i;
if(isset($$temp) && $$temp != '')
{
$subject="some subject";
$body = "email content";
$headers = "From: $email0 \r\n";
$headers .= "Reply-To: $email0 \r\n";
mail($$temp, $subject, $body, $headers);
}
$i++;
}
...OK I just tried a different way. I stuffed all the emails in one array and iterated through it. The same result, no emails received!!!! What am I missing ? :)
$recipients = array($email1,$email2,$email3,$email4,$email5,$email6,$email7,$email8,$email9,$email10);
foreach($recipients as $value)
{
if($value != '')
{
$subject2="some subject";
$body2 = "some content";
$headers2 = "From: $email0 \r\n";
$headers2 .= "Reply-To: $email0 \r\n";
mail($value, $subject2, $body2, $headers2);
}
}
At this point I am going to post the following:
It just so happened that all my previous attempts started to come
into may spam box (several hours latter!). So my suspicion seems to
be confirmed: when on GoDaddy shared hosting do not send more than
one email at the same time in short intervals (with the same content)
or it will end up labeled as spam!
SOLUTION:
As jmbertucci in the posts below suggested, the simplest solution is to use BCC: for all the recipients in one email. Since I had to personalize each email, I noticed that if I include the unique char. into the subject line for each email, it goes through with no problem as well. So my solution is adding the recipients' name into the subject line (which makes all emails unique) but any unique string should do the same (like date() etc.)
Did u try to check if your mail server is properly config or config it like this sample
// Please specify your Mail Server - Example: mail.example.com.
ini_set("SMTP","mail.example.com");
// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","25");
// Please specify the return address to use
ini_set('sendmail_from', 'example#YourDomain.com')
;
or check you php.ini file for this. heres a sample config.
[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
; For Win32 only.
;sendmail_from = me#example.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").

Categories