I'm trying to send an email that has a attachment generated using dompdf to a list of recipients. Using array_shift() for taking the primary email and remove it from the array and use foreach for taking every other email as CC. When I'm adding CC, email is sent twice. If there is no CC, it will be sent only once. Even if CC is blank , it is sent twice. If I remove that line AddCC(), it will be sent only once.
Any idea or help I can seek?
require_once 'dompdf/autoload.inc.php';
require_once 'phpqrcode/qrlib.php';
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true);
$recipients = array() // array of emails to be sent
try {
ob_start();
include "pdf.php";
$htmldata = ob_get_clean();
$options = new Dompdf\Options();
$options->getChroot($_SERVER['DOCUMENT_ROOT']);
$options->setisRemoteEnabled(true);
$options->setIsHtml5ParserEnabled(true);
$options->setTempDir('temp'); // temp folder with write permission
$dompdf = new Dompdf\Dompdf($options);
$dompdf->loadHtml($htmldata);
$customPaper = array(0,0,600,600);
$dompdf->set_paper($customPaper);
QRcode::png($data, "qr.png", "L", 4, 4);
$dompdf->render();
$output = $dompdf->output();
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('', '');
$mail->addAddress(array_shift($recipients)); // Add first email as the recipient and remove the email from array
$mail->addReplyTo('');
foreach($recipients as $ccEmail)
{
$mail->AddCC($ccEmail);
}
$mail->addStringAttachment($output, 'attachment.pdf');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Subject'.rand();
$mail->Body = 'Content';
$mail->AltBody = 'content';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Related
I have a problem with my code, the intension is to send an email using smtp.mandrill.com and use the alert to know when the email is sended, otherwise send another alert when fails to send the email. And I recived the alert confirming the email, but is'nt sended. If anyone knows the problem I thanks a lot your help.
This is the code.
<?php
$name = $_POST["first_name"];
$telefono = $_POST["telephone"];
$texto = $_POST["text"];
$body =
"Name: ".$name."<br>
Telephone: ".$telephone."<br>
Message: ".$text;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPmailer/Exception.php';
require 'PHPmailer/PHPMailer.php';
require 'PHPmailer/SMTP.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; //"2" Enable verbose debug output. Change to "0" to hide all the letters n.n
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mandrill.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'example#example.com'; //SMTP username
$mail->Password = 'Any API key'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465;
//Recipients
$mail->setFrom('example#example', 'Example');
$mail->addAddress('example#example'); //Add a recipient
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Contact';
$mail->Body = 'New message from <b>Contact</b><br><br>'.$body;
$mail->CharSet = 'UTF-8';
$mail->send();
echo '<script>
alert("The data was sent successfully.");
window.history.go(-1);
</script>';
} catch (Exception $e) {
echo '<script>
alert("An error occurred while sending the data.");
window.history.go(-1);
</script>';
}
?>
Update your SMTP SECURE AND PORT TO:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
That solved my issues with using Mandrill with SMTP.
I have the following code sending email shipping confirmations to my customers:
while ($i < count($tracked) ) {
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.office365.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#mycompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('support#mycompany.com', 'mycompany');
$mail->addAddress($tracked[$i]['customers_email_address'], $tracked[$i]['customers_name']); // Add a recipient
$mail->addReplyTo('support#mycompany.com', 'mycompany');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = EMAIL_TEXT_SUBJECT;
$mail->Body = $html;
$mail->AltBody = 'Your order with mycompany.com has shipped';
$mail->send();
echo 'order confirmation sent to order#:'.$tracked[$i]['orders_id'].'<br/>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
$i++;
}
It appears to be sending to multiple emails. What I believe is happening is that in the while loop each new customers address is added to the list without clearing it. What doesnt seem to be happening though is the message does not seem to be duplicated? Wouldn't that duplicate at as well with each pass in the loop?
In any case I think the best thing to do before the try is:
$mail = new PHPMailer(true);
so that with each pass of the while loop the $mail object would be instantiated again. Is that proper? I know that the clearAllRecipients() function exists but i also want to be sure the body is cleaned as well.
it looks like your looping through an array of $tracked. Why not use a foreach loop? Then you don't need to use a counter.
foreach ($tracked as $track ) {
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.office365.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'support#mycompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('support#mycompany.com', 'mycompany');
$mail->addAddress($track['customers_email_address'], $track['customers_name']); // Add a recipient
$mail->addReplyTo('support#mycompany.com', 'mycompany');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = EMAIL_TEXT_SUBJECT;
$mail->Body = $html;
$mail->AltBody = 'Your order with mycompany.com has shipped';
$mail->send();
echo 'order confirmation sent to order#:'.$track['orders_id'].'<br/>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
It's because addAddress() does exactly what its name suggests; it adds an address that a message will be sent to. It doesn't set the addresses a message will be sent to.
Unsurprisingly there is a method that allows you to clear the list of addresses, called clearAddresses(), so just call that at the end of your sending loop after send() and your issue will be solved.
I'd also recommend that you base your code on the mailing list example provided with PHPMailer as it will be much faster than the code you have here. Also read the docs on sending to listshttps://github.com/PHPMailer/PHPMailer/wiki/Sending-to-lists) for furtehr advice.
We all know how to implement PHPMailer within a project and its use is great, but I need something more, after entering the necessary parameters in order to make everything work.
I need a form to change the email address of the recipient who will receive the email, how can I do?
code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); //Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxx#gmail.com'; // SMTP username
$mail->Password = 'xxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('xxx', 'xxx'); // Sender email and name
$mail->addAddress('xxx'); // Reciver email
// if you want to send email to multiple users, then add the email addresses you which you want to send.
//$mail->addAddress('reciver2#gmail.com');
//$mail->addAddress('reciver3#gmail.com');
//For Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // You can specify the file name
//Content
$mail->isHTML(true);// Set email format to HTML
$mail->Subject = 'Oggetto dell email'; // Subject of the email
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
My PHPmailer from Github does work on my local host but not on my Firebase hosted website. When I submit on my website it downloads the file. Now how to solve it? Do I have to put some extra code in? Someone experienced with Firebase?
<?php
// get variables from the form
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Load Composer's autoloader
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try{
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = '°°°°°°°'; // SMTP password
$mail->SMTPSecure = 'TLS'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
// Sender
$mail->setFrom($email, $name);
// Recipients
$mail->addAddress('example#gmail.com', 'Luk Ramon'); // Add a recipient
// Body content
$body = "<p>You received an email from your website <br>name:<strong>".$name." </strong><br>subject: <strong>".$subject."</strong><br>message:<br><i>".$message."</i></p> Contact back on ".$email;
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Company-name message from '.$name;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
Firebase hosting does not support PHP which is why the file is being downloaded.
You'd need to write this in Javascript to use with Firebase - https://firebase.google.com/docs/hosting/functions
I wrote a PHP mailer code to send emails to multiple recipients. But unfortunately i found a drawback in script, i am fetching emails from database, lets see if it fetches 5 emails and try to send email to all of them and no.3 email is not a valid address(any reason) then my script just "exist" the function entirely by sending mail to 1-2 and showing error invalid email 3 and "exit"(not continuing further), what i want is rather to "exit" the function it should just skip that iteration statement(email) and then go on to next one like the "continue" statement. Also in code the message and subject are being sent from another page which consists of a form.
Here is the code :
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_SESSION['userIs']))
{
$message = $_POST['message'];
$subject = $_POST['subject'];
//Load composer's autoloader
require './PHPMailer/vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'trying.test.00'; // SMTP username
$mail->Password = 'trying.test.00'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('trying.test.00#gmail.com', 'Tester');
include('./create-connection.php');
$get_list = "select name,email from signup";
$result = $conn->query($get_list) ;
if($result->num_rows>0)
{
while($row_list = $result->fetch_assoc())
{
$to = $row_list['email'];
$name = $row_list['name'];
$mail->addAddress($to,$name); // Add a recipient
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if($mail->send())
{
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-check"></i></div>';
}
} catch (Exception $e) {
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-times"></i></div>';
}
$conn->close();
}
?>
You could validate the email addresses before sending.
Or better:
You could validate the email addresses before inserting in the database so you know that the database contains only valid data.
Just needed to add a validation to check if the email is valid or not without sending email inside while loop, then if email is valid process the mail else "continue" the current iteration(email) and jump to next email.
Thus after changing code ->
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_SESSION['userIs']))
{
$message = $_POST['message'];
$subject = $_POST['subject'];
//Load composer's autoloader
require './PHPMailer/vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'trying.test.00'; // SMTP username
$mail->Password = 'trying.test.00'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('trying.test.00#gmail.com', 'Tester');
include('./create-connection.php');
$get_list = "select name,email from signup";
$result = $conn->query($get_list) ;
if($result->num_rows>0)
{
while($row_list = $result->fetch_assoc())
{
//add a validation here
if(!filter_var($row_list['email'], FILTER_VALIDATE_EMAIL))
{
echo "invalid email".$row_list['email'];
continue;
}
else
{
$to = $row_list['email'];
$name = $row_list['name'];
$mail->addAddress($to,$name); // Add a recipient
}
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if($mail->send())
{
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-check"></i></div>';
}
} catch (Exception $e) {
echo '<div class=""><b>'.$to.'</b> -> Status <i class="fa fa-times"></i></div>';
}
$conn->close();
}
?>