Phpmailer AddBcc not working - php

I am using phpmailer to sent email, and it works the recipients receive the mail except the bcc and cc details is not showing the mail. Someone can suggest a solution to this
.
the code is
require_once("PHPMailer_v5.1/class.phpmailer.php");
require_once("PHPMailer_v5.1/language/phpmailer.lang-en.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "tls";
$mailer->Host = 'smtp.gmail.com';
$mailer->Port = 587;
$mailer->Username = "myuserid";
$mailer->Password = "mypassword";
$mailer->FromName = $fromname;
$mailer->From = "myuserid";
$mailer->AddAddress("to#gmail.com",$toname);
$mailer->Subject = $subject;
$mailer->Body =$content;
$mailer->AddCC("something#gmail.com", "bla");
$mailer->AddBCC("foo#gmail.com", "test");
if(!$mailer->Send())
{
echo "Message was not sent";
}
else
echo "mail sent";

Use as
$mailer->AddBCC("foo#gmail.com", "test");
$mailer->AddCC("something#gmail.com", "bla");

You never see BCC details. That's what they are BCC details for. Even the recipient of a BCC will not see his own name with the recipients.
PS: You noticed you wrote addBCC instead of AddBCC (capital A)?

From the phpMailer function reference:
Adds a "Bcc" address. Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
This might be causing your issue.

PHPMailer not sending CC or BCC
Old question, but I ended up here looking for an answer. Just learned elsewhere that those functions AddCC and AddBCC only work with win32 SMTP
Try using:
$mail->addCustomHeader("BCC: mybccaddress#mydomain.com");
See http://phpmailer.worxware.com/?pg=methods
Hope this helps someone, cheers!

It´s addBCC
$email->addBCC('my#email.com', 'My Name');
See PHPMailer.php (current version 6.0.5) on line 934 (https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php#L934):
/**
* Add a "BCC" address.
*
* #param string $address The email address to send to
* #param string $name
*
* #return bool true on success, false if address already used or invalid in some way
*/
public function addBCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('bcc', $address, $name);
}

the bcc will never show; only TO and CC
BCC=Blind Carbon Copy

Here is a working example from the newest release, and on Office 365, I use it to send email from shared folders...
<?
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once('./phpmailer/Exception.php');
require_once('./phpmailer/PHPMailer.php');
require_once('./phpmailer/SMTP.php');
//* Working Example As Of 09/21/2019 - Sends From Shared Mailbox With Mailbox Member
function SendO365EmailTLS($options)
{
$from = isset($options['from']) ? $options['from'] : false;
$recipients = isset($options['recipients']) ? $options['recipients'] : false;
$ccRecipeints = isset($options['ccrecipients']) ? $options['ccrecipients'] : [];
$bccRecipients = isset($options['bccrecipients']) ? $options['bccrecipients'] : [];
$attachments = isset($options['attachments']) ? $options['attachments'] : [];
$credentials = isset($options['credentials']) ? $options['credentials'] : false;
$subject = isset($options['subject']) ? $options['subject'] : '';
$body = isset($options['body']) ? $options['body'] : '';
if(!$from) throw new Exception('Cannot send email with blank \'from\' field');
if(!$recipients) throw new Exception('Cannot send email, no recipients specified!');
if(!$credentials) throw new Exception('Cannot send email, credentials not provided!');
$mail = new PHPMailer;
foreach($recipients as $recipient) $mail->addAddress( $recipient[ 'email'], $recipient['name']);
foreach($ccRecipeints as $ccRecipient) $mail->addCC( $ccRecipient[ 'email'], $ccRecipient['name']);
foreach($bccRecipients as $bccRecipient) $mail->addBCC( $bccRecipient['email'],$bccRecipient['name']);
foreach($attachments as $attachment) $mail->addAttachment($attachment[ 'path' ], $attachment['name']);
$mail->setFrom($from['email'], $from['name']);
$mail->Username = $credentials['username'];
$mail->Password = $credentials['password'];
$mail->Host = 'smtp.office365.com';
$mail->Subject = $subject;
$mail->SMTPSecure = 'tls';
$mail->Body = $body;
$mail->SMTPAuth = true;
$mail->isHTML(true);
$mail->Port = 587;
$mail->isSMTP();
$success = $mail->send();
return $success;
}
// $options = ['from'=> ['email'=>'', 'name'=>''],
// 'recipients'=> [['email'=>'', 'name'=>'']],
// 'ccrecipients'=> [['email'=>'', 'name'=>'']],
// 'bccrecipients'=>[['email'=>'', 'name'=>'']],
// 'attachments'=> [['path'=>'./attachments/file1.jpg','name'=>'1.jpg'],
// ['path'=>'./attachments/file2.jpg','name'=>'2.jpg'],
// ['path'=>'./attachments/file3.jpg','name'=>'3.jpg']],
// 'credentials'=> ['username'=>'','password'=>''],
// 'subject'=> 'Email Subject Line',
// 'body'=> '<h1>Email Body</h1><p>HTML!!!</p>'];
// $success = SendO365EmailTLS($options);
// echo $success ? 'Email Sent':'Email Not Sent';
// die();

$mail->addCC('cc#example.com');//Carbon copy
$mail->addBCC('bcc#example.com');//Blind Carbon copy
Please Read This
https://github.com/PHPMailer/PHPMailer

To operate the clausla BCC AddCC MUST precede as well nuloy hidden email will arrive to your recipient would otherwise happen nuna
Example:
   
$ mail-> AddCC ("");
$ mail-> AddBCC ("mail # domain")

Related

What's the right workaround to send DIFFERENT messages to DIFFERENT recipients in PHPMailer

I am trying to send an email to multiple different BCC recipients.
Every recipient gets an identical text body BUT, he also needs to receive his own individual email in it.
I'm looping through a JSON to add emails with the $mail->addBCC() function.
And I need that the $body that is sent to every individual user will contain his own individual address.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
//*** -> $allUsers is a JSON
function sendemails_ex($allUsers, $subject, $body)
{
$emailFrom = "noreply#slandergold.com";
$emailFromName = "slandergold.com";
if ($allUsers=="" || $subject=="" || $body=="")
{
exit();
}
$smtpUsername = "abcdKLARK";
$smtpPassword = "1t%y$R5$4";
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = "mail.slandergold.com";
$mail->Port = 26; //587; // TLS only
$mail->SMTPSecure = false; //'tls'; // ssl is depracated
$mail->SMTPAuth = false; //true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($emailFrom, $emailFromName);
$arr = json_decode($allUsers,true);
foreach($arr as $item)
{
$mail->addBCC($item['Email'], $item['Fullname']);
}
$mail->isHTML(true);
$mail->Subject = $subject;
// ***********
// is there a way to make it
// so that every individual BCC recipient
// will get a body with the individual addition of:
// $userEmail = ?
// $body."<br />This is your email: ".$userEmail;
// ***********
$mail->msgHTML($body);
$mail->AltBody = 'HTML messaging not supported';
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!";
}
}
As the comments say, you can’t send different emails to different recipients using BCC. You need to send each message individually, and the definitive way to do that is provided in the mailing list example provided with PHPMailer. There are also notes in the project wiki about how to send to lists efficiently.

PHP sending emails to but not text

I am trying to send emails to phones that have Verizon numbers. Here is my code right now
<?php require('includes/config.php');
function Send( $ToEmail, $MessageHTML, $MessageTEXT) {
require_once ( 'classes/phpmailer/phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "box405.bluehost.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "ssl"; //Secure conection
$Mail->Port = 465; // set the SMTP port
$Mail->Username = 'techsupport#test.com'; // SMTP fake account username
$Mail->Password = 'password1'; // SMTP fake account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->FromName = 'Tech support';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$stmt = $db->prepare("select phone From members where phone not like 'no';");
$stmt->execute();
$result = $stmt->fetchAll();
$ToEmail = $result[0][0];
$ToName = 'techsupport';
$MessageHTML = "test";
$MessageTEXT = 'test';
$Send = Send( $ToEmail, $MessageHTML, $MessageTEXT);
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
this works when I try to send emails but when I use it to send texts it says sent but I do not receive anything. I know this is not because of the address because I use the same address when I text myself from gmail and it is not the sql query because I have tested it . I Think the problem is in the smtp or phpmailer for I have not used either of those a lot. Also the code runs though and prints out the SENT OK echo but nothing goes through and no errors.
[EDIT] To answer ironcito's question I am sending the email to
phonenumber#vtext.com
I know this works because I have used the same address through gmail.
I think this might be because you push the content to the mail (body) before you set the content (messagehtml/messagetext), which creates an empty email. Try changing these around, that might be the solution.

Add a CC to a mail to script

I have a form that sends an email and I want to add a cc email to the mail to line. Please show me how I would need to have the line below to acomplish this. Thanks
mail("mainemail#email.com;CCemail#email.com", $subject, $message, $header);
public function SMTPClient($subject,$content,$instance) {
try {
$mailer = new PHPMailer(true);
$mailer->IsSMTP();
$mailer->SMTPDebug = 1;
$mailer->SMTPAuth = def_SMTP_AUTHENTICATION; // enable SMTP authentication
$mailer->SMTPSecure = def_SMTP_SECURE; // sets the prefix to the servier
$mailer->Host = def_SMTP_SERVER; // sets GMAIL as the SMTP server
$mailer->Port = def_SMTP_PORT; // set the SMTP port for the GMAIL server
$mailer->Username = def_SMTP_USERNAME; // GMAIL username
$mailer->Password = def_SMTP_PASSWORD; // GMAIL password
$mailer->SetFrom(def_MAIL_FROM_ADDRESS, def_MAIL_FROM_NAME);
$to = def_MAIL_TO;
$mailer->AddAddress($to);
$mailer->Subject = $subject;
$mailer->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mailer->WordWrap = 80; // set word wrap
$mailer->AddCC('xzy#gmail.com', 'xyz');
$mailer->AddReplyTo(def_MAIL_TO, 'abc');
$mailer->MsgHTML($content);
$mailer->IsHTML(true); // send as HTML
$mailer->Send();
$this->logger("Message has been sent Successfully","INFO",$instance);
echo 'Message has been sent Successfully.';
} catch (phpmailerException $e) {
echo $e->errorMessage()`enter code here`;
}
}
Note:Use the mailer component from http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.4.zip&can=2&q=

Send attatchment using php mail()

I want to attach a image as an attachment using mail() function.
I am using xampp and want the image to be sent from my computer to an email id.
This code is sending text email easily:
<?php
if(mail('abc#gmail.com','Hello','Testing Testing','From:xyz#gmail.com'))
{
echo "Success";
} else {
echo "Fail";
}
?>
I want to add an image after it using normal mail method of php.
you need to use the pear library for composing or sending the mail.
include_once('Mail.php');
include_once('Mail_Mime/mime.php');
$message = new Mail_mime();
$message->setTXTBody($text);
$message->addAttachment($path_of_uploaded_file);
$body = $message->get();
$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
$headers = $message->headers($extraheaders);
$mail = Mail::factory("mail");
$mail->send($to, $headers, $body);
here is a way
You could use the Mail class from the Zend library, very simple and no reliance on PEAR.
Its been covered in a previous question here.
I suggest to use Swiftmailer. It is up to date, easy to install and use. You can install it via PEAR, but there are lots of other options you might find more convenient as well.
Example code to send a mail with an attachement taken from the manual:
require_once 'lib/swift_required.php';
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(array('john#doe.com' => 'John Doe'))
// Set the To addresses with an associative array
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'));
this is using php and ajax it will work 100%
<?php
include "db.php";
if(isset($_POST['tourid']))
{
$to=$_POST['email'];
$file_name = "test/sample.pdf";
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = ''; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = ''; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = ''; //Sets SMTP username
$mail->Password = ''; //Sets SMTP password
$mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = ''; //Sets the From email address for the message
$mail->FromName = ''; //Sets the From name of the message
$mail->AddAddress($to, 'Name'); //Adds a "To" address
$mail->WordWrap = 50; `` //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Customer Details'; //Sets the Subject of the message
$mail->Body = 'Please Find Tour details in attached PDF File.'; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$message = '<label class="text-success">Tour Details has been send successfully...</label>';
echo $message;
unlink($file_name);
}
}
else
{
echo "sending error";
}
?>

Sending 2 emails with PHP mailer fails

I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2

Categories