Send email with CCO in PHP

Asked

Viewed 7,767 times

8

I wanted to know how to send email with CCO ("with hidden copy")?

Formular code:

require('config.php');
$sqlstt = "SELECT * FROM tb_site WHERE id='1'";
$resultstt = mysql_query($sqlstt);        
$rowtt = mysql_fetch_array($resultstt);

$sitename = $rowtt['sitename'];
$supmails = $rowtt['sitepp']; // E-mail Suporte.
$supmail  = ""; // Envio do email.
$bcc      = null;
$nome_remetente = "Email Marketing $sitename";   
$assunto = strtoupper($user).", E-Mail Marketing";
$email_remetente = $supmails;

// Inicio do envio de menságem para o usuário //    

$email_destinatario = $emaills;

// Conteudo do e-mail (voce poderá usar HTML) //
$mensagem = $description;

// Cabeçalho do e-mail. Nao é necessário alterar geralmente...
$cabecalho  = "MIME-Version: 1.0\n";
$cabecalho .= "Content-Type: text/html; charset=iso-8859-1\n";
$cabecalho .= "From: \"{$nome_remetente}\" <{$email_remetente}>\n";

// Dispara e-mail e retorna status para variável
$status_envio = @mail ($email_destinatario, $assunto, $mensagem, $cabecalho);

if ($status_envio) { // Se mensagem foi enviada pelo servidor...
    echo "Uma menságem foi enviada para o e-mail do usuário!<br />";
} else { // Se mensagem nao foi enviada pelo servidor...
    echo "Nao conseguimos enviar a sua menságem ao usuário!<br />";
}
  • Did any of the answers help you? Or are there problems with them? Comment informing the author who doubts to try to use the proposed solution. If any of the answers solved your problem, mark it as correct by clicking on

3 answers

13

Correct form

To send an email With Hidden Copy (CCO) or Blind Carbon Copy (BCC), simply add to the email header the following instruction

$emailoculto = '[email protected]';
$cabecalho .= "Bcc: {$emailoculto}\r\n";

Heed: According to the job documentation mail() in PHP, multiple headers should be separated with CRLF that is to say \r\n:

Multiple extra headers should be separated with a CRLF ( r n)

Not so correct shape

You can also do with POG. This alternative consists of sending the email twice, the first to its recipients and a second time to the hidden copy:

$emailoculto = '[email protected]';
$status_envio = @mail ($email_destinatario, $assunto, $mensagem, $cabecalho);
if ($status_envio) { // Se mensagem foi enviada pelo servidor...
    echo "Uma menságem foi enviada para o e-mail do usuário!";
    // Envia para o destinatário oculto
    if (!mail($emailoculto, $assunto, $mensagem, $cabecalho))
        echo "!";

    echo "<br />";

} else // Se mensagem não foi enviada pelo servidor...
    echo "Não conseguimos enviar a sua mensagem ao usuário!<br />";

Better Form

You can also (or should) use the class Phpmailer to send your emails.

This is the best alternative to sending emails with PHP, as you have several features in a very simple way like: add attachments, multiple recipients, copies or hidden copies.

In addition to the possibility to easily configure the sending by SMTP, because some servers do not support function mail().

Example of use:

email php.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;

send php.

require_once 'email.php'
global $mail;

$mail->From = '[email protected]'; // DE
$mail->FromName = 'Mailer'; // DE Nome

$mail->addAddress('[email protected]', 'Joe User');     // Destinatário
$mail->addAddress('[email protected]');               // Nome OPCIONAL

$mail->addReplyTo('[email protected]', 'Information'); // Responder Para

$mail->addCC('[email protected]'); // CÓPIA

$mail->addBCC('[email protected]'); // CÓPIA OCULTA

$mail->addAttachment('/var/tmp/file.tar.gz');         // Adicionar Anexo
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Nome OPCIONAL
$mail->isHTML(true);                                  // E-mail no formato HTML

$mail->Subject = 'Here is the subject'; // TÍTULO
$mail->Body    = 'This is the HTML message body <b>in bold!</b>'; // Corpo HTML
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; // Corpo TEXTO

if($mail->send()) {
    echo 'Mensagem enviada com sucesso.';
} else {
    echo 'Erro ao tentar enviar mensagem.<br>';
    echo 'Erro: ' . $mail->ErrorInfo;
}

8

Using the function mail() it is necessary to pass this information in the header which is the last argument,

just add that line:

$cabecalho .=   "From: \"{$nome_remetente}\" <{$email_remetente}>\n";
$cabecalho .=   "Bcc: $email_oculto\n";

Bcc: is the hidden copy(blind Carbon copy)

Cc: Email with copy (Carbon copy)

  • 2

    That’s right. However, I recommend using a library like Swift Mailer instead of the simple use of mail()

  • 1

    did not work, I exchanged $hidden email for $email_destinatario .

  • 1

    @user7329, what happened? hidden email appeared? gave error?

  • 1

    the hidden email appeared

  • @rray I’m having the same problem in a customer, I’m using the BCC in the Header and yet the email that should be hidden appears

  • @Erlonchaérles, is linux or windows hosting?

  • the problem may be the line separator \n, should be \r\n, in accordance with pointed out by Bruno

  • @rray is linux, was windows, had this problem and went to linux, and still did not stop the problem

  • 2

    I discovered the error, at the beginning of the project there would be no hidden copies, so there would be nothing in the header, but with a change it became necessary to send a hidden copy in a specific case. The mistake itself was that the BCC and the first parameter in the mail function were using the same email.

Show 4 more comments

4

According to the documentation multiple "additional headers" must be separated by CRLF ( r n). Only in some cases, and as a last resort, you should do as in your example and separate the headers only with LF ( n). This is because it would not be in accordance with RFC 2822.

So, according to the function manual, your example would be.:

$cabecalho =    "MIME-Version: 1.0\r\n";
$cabecalho .=   "Content-Type: text/html; charset=iso-8859-1\r\n";
$cabecalho .=   "From: \"{$nome_remetente}\" <{$email_remetente}>\r\n";
$cabecalho .=   "Bcc: $email_oculto\r\n";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.