An Excel file is uploaded from a html form the regno and email information are read from the excel file.Each user is then sent an email along with a message.The regno and email are inserted in the database.
gmail is used for sending emails $frmid is the from email address and $password is the password for it.
Here is the code.
<?php
require_once("function/PHPExcel/Classes/PHPExcel/IOFactory.php");
require_once("function/Mail/class.phpmailer.php");
require_once("function/connection.php");
if($_SERVER['REQUEST_METHOD']=='POST' && is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
$msg=$_POST['msg'];
$arr=array();
$frmid=htmlspecialchars(trim($_POST['frm_id']),ENT_QUOTES,'UTF-8');
$password=htmlspecialchars(trim($_POST['password']),ENT_QUOTES,'UTF-8');
$subject=htmlspecialchars(trim($_POST['subject']),ENT_QUOTES,'UTF-8');
$name=$_FILES['uploaded_file']['tmp_name'];
try {
$inputFileType = PHPExcel_IOFactory::identify($name);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($name);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++){
$email = $sheet->getCell('B'.$row )->getValue();
$regno = strtoupper($sheet->getCell('A'.$row )->getValue());
$arr[]=array($regno,$email);
$message=$msg;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = $frmid;
$mail->Password = $password;
$mail->SetFrom($frmid);
$mail->Subject = $subject;
$mail->MsgHTML($msg);
$mail->AddAddress($email);
if(!$mail->Send()){
die("Failed to send to Email Id ".$email."\n<br/>");
}
}
} catch(Exception $e) {
die('Server Error');
}
$db=connection();
$query="INSERT INTO table(regno,email) VALUES ";
$query=buildinsert($query,$highestRow);
$stmt=$db->prepare($query);
$result=$stmt->execute($arr);
if($stmt->rowCount()==$highestRow){
redirect("page.php?result=1");
}else{
redirect("page.php?result=0");
}
}
?>
The functions used are
<?php
function buildinsert($query,$rows){
$placeholder=array();
for($i=0;$i<$rows;$i++){
$placeholder[]="(?,?)";
}
return($query.implode(",",$placeholder));
}
function connection(){
try{
return (new PDO("mysql:host=localhost;dbname=dbms,","root","passwd"));
}catch(Exception $e){
die( "An error occured".$e->getMessage());
}
}
function redirect($link){
header("Location:".$link);
}
?>
The problem is I`m not being redirected after the operation completes.The mails are sent successfully and the content is also added but the page does not change.I get same page as before
Found the Problem.The phpmailer,phpexcel are fine the problem was with connection.php
After I added buildinsert function I left a newline,The page was not redirecting because of the newline space between
Thanks Jon!
Related
I am using PHPMailer 5.1, and while sending email through PHPMailer, I get few junk characters like =?UTF-8?Q??=, and not the expected text in subject.
Here is the my code which I used:
$recipient = 'xxx#xxx.cz';
$sender = 'xxx#xxx.cz';
header("Access-Control-Allow-Origin: *");
try
{
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
{
throw new ErrorException('Method Not Allowed (please use POST)', 405);
}
$data = unserialize(base64_decode($_POST['_data']));
$_POST = unserialize(base64_decode($_POST['_post']));
ob_start();
$cislo_objednavky = 1 + (int)
file_get_contents('cpo/cpo.txt');
require 'tabulka.php';
$body = ob_get_contents();
ob_end_clean();
require 'phpmailer/class.phpmailer.php';
$mail = new PHPMailer(TRUE);
$mail->CharSet = 'UTF-8';
$mail->Host = "xxx.xxxx.cz";
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Username = "xxx#xxx.cz";
$mail->Password = "xxxxx";
$mail->Encoding = 'base64';
$mail->AddAddress($recipient);
$mail->SetFrom($sender, 'XXXXXX');
$mail->AddReplyTo($sender);
$mail->AddCC($_POST['email']);
$mail->Subject = ('Objednávka č.'.$cislo_objednavky);
$mail->MsgHTML('html tělo mailu');
$mail->Send();
file_put_contents('xxxx.xxx', $cislo_objednavky);
}
catch (Exception $e)
{
header('HTTP/1.0 '.$e->getCode().' '.$e->getMessage());
echo '<h1>'.($e->getMessage().' (#'.$e->getCode().')').'</h1>';
exit;
}
What is the problem here?
Thank you so much.
I'm stuck on how to uses PHPMailer. I create a simple PHP form to book a meeting room. Admin needs to log in the system and key in all details including requester email's, factory and room. After admin click 'submit', it will save to database under table 'booking'.
Now, What I want is when I clicked the submit button, It also sent an email to the user about the details that already booked.
Below is my current code:
home.php
<?php
require_once 'configPDO.php';
session_start();
if(!ISSET($_SESSION['login_user'])){
header('location:index.php');
}
$Email = $_SESSION['login_user'];
$sql = $conn->prepare("SELECT * FROM staff WHERE Email='$Email'");
$sql->execute();
$fetch = $sql->fetch();
if(ISSET($_POST['submit'])){
if($_POST['Requested_by'] != "" || $_POST['Factory'] != "" || $_POST['Room'] != ""){
try{
$Requested_by = $_POST['Requested_by'];
$Factory = $_POST['Factory'];
$Room = $_POST['Room'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `booking` VALUES ('', '$Requested_by', '$Factory', '$Room')";
$conn->exec($sql);
}catch(PDOException $e){
echo $e->getMessage();
}
$conn = null;
header('location:index.php');
}else{
echo "
<script>alert('Please fill up the required field!')</script>
<script>window.location = 'registration.php'</script>
";
}
}
?>
sendmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Mailer/Exception.php';
require 'PHPMailer/Mailer/PHPMailer.php';
require 'PHPMailer/Mailer/SMTP.php';
require_once 'configPDO.php';
session_start();
$sendermail = '';
$sendername = '';
$senderpassword = '';
$receiveremail = '';
$receivername = '';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.office365.com'; //gmail SMTP server
$mail->SMTPAuth = true;
$mail->Username = $sendermail; //username
$mail->Password = $senderpassword; //password
$mail->SMTPSecure = 'TLS';
$mail->Port = 587; //smtp port
$mail->setFrom($sendermail, $sendername);
$mail->addAddress($receiveremail, $receivername);
$mail->isHTML(true);
$mail->Subject = 'E-booking';
$mail->Body = '<h3>Dear '.$receivername.',</h3>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
}
?>
Please help me. thanks
I'm trying to send multiple separate emails to multiple addresses. The below code sends it in 1 email with multiple TO addresses. This becomes an issue because everyone in the email can see each other's email addresses.
Is there a way to send separate emails?
<?php
$smtp = 'xxx.com';
$port = 25;
$secure = 'tls';
$username = 'test#xxx.com';
$pass = '';
$from = 'test#xxx.com';
$to = 'info#xxx.com';
$to1 = '';
$subject = 'Test Email';
$content = $mail_content;
require_once("include/class.phpmailer.php");
$mail=new PHPMailer(true);
$mail->IsSMTP();
try{
$mail->Host = $smtp;
$mail->SMTPAuth = true;
$mail->Port = $port;
$mail->SMTPSecure = $secure;
$mail->Username = $username;
$mail->Password = $pass;
$mail->SetFrom($from);
if (isset($email) && $email) {
$mail->AddAddress($email);
}
else {
while($row = mysqli_fetch_object($result)) {
$mail->AddAddress($row->email);
echo $row->email."<br>";
}
}
$mail->Subject = $subject;
$mail->MsgHTML($content);
$mail->Send();
if (isset($email) && $email) {
?>
<script>location.href="<?php echo '../index.php' . $_REQUEST['redirect']; ?>";</script>
<?php
}
}
catch (phpmailerException $e){
echo $e->errorMessage();
}
catch (Exception $e){
echo $e->getMessage();
}
?>
Send the email in the BCC.
Look here for an example :
PHP Email sending BCC
You have a loop that checks for all of the email addresses and then assigns the email address to $mail->AddAddress().
All you need to do in this same loop is send the email with $mail->Send(); with each iteration of the loop as well
//PHPmailer object
$mail=new PHPMailer(true);
//set up
$mail->IsSMTP();
$mail->Host = $smtp;
$mail->SMTPAuth = true;
$mail->Port = $port;
$mail->SMTPSecure = $secure;
$mail->Username = $username;
$mail->Password = $pass;
$mail->SetFrom($from);
$mail->Subject = $subject;
$mail->MsgHTML($content);
//add address
if (isset($email) && $email) {
$mail->AddAddress($email);
}
else {
//loop through the DB results
while($row = mysqli_fetch_object($result)) {
//you already have this
$mail->AddAddress($row->email);
echo $row->email."<br>";
//now send it here as well
$mail->Send();
//Do more stuff here
}
}
I have not tested this on my local system but this is one way to send the mail individually for each address as an alternative to sending one mail and using bcc.
I have a web app using PHP, MySQL, and PHPMailer to send emails. The issue I am having is PHPMailer will send some of the emails, but not always. I'm thinking maybe it is because different list of emails have data issues? Below is my code that loops through the email addresses and send some, but not all the emails. I have tried to catch errors, but I can't see any in the logs.
How can I debug what is going on, and why some don't send?
else if($current_version == 'PROD'){
date_default_timezone_set('America/New_York');
require 'PHPMailer-master/PHPMailerAutoload.php';
$pageURL = 'xxxxxx';
$subject = "xxxxx ";
$body = "xxxxxx \r\n";
$body .= "xxxxx \r\n \r\n";
$body_html = str_replace("\r\n","<br/>",$body);
try {
$mail = new PHPMailer();
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "xxx#xxxx.com";
$mail->Password = "xxxx";
$mail->setFrom('xxxxx#xxxx.com', 'xxxx');
$mail->addReplyTo('xxxx#xxxx.com', 'xxxx');
$mail->Subject = $subject;
$mail->Body = $body_html;
$mail->AltBody = $body;
$sql_email_list = "SELECT email FROM tbl_email
WHERE distro_name='xxxxs'
AND is_active='Y' ";
$result_email_list = mysql_query($sql_email_list);
$num_email_list = mysql_num_rows($result_email_list);
$lost_email_list = mysql_result($result_email_list,0,'email');
$lost_email_array = explode(";",$lost_email_list);
foreach ($lost_email_array as $key => $val){
$mail->AddAddress($val);
if($carrier_email_flag_global == 'ON'){
$mail->send();
$mail->ClearAllRecipients();
$mail->ClearAttachments();
echo '<hr>Email Sent to: '.$val;
}
}
$sql_email_one = "SELECT table2.email
FROM table1
INNER JOIN table2 ON table1.cntct = table2.cntct_id
WHERE id='$id' ";
$result_email_one = mysql_query($sql_email_one);
$num_email_one = mysql_num_rows($result_email_one);
for($iiz=0;$iiz<$num_email_one;$iiz++){
$one_email = mysql_result($result_email_one,$iiz,'email');
$mail->AddAddress($one_email);
if($carrier_email_flag_global == 'ON'){
$mail->send();
$mail->ClearAllRecipients();
$mail->ClearAttachments();
echo '<hr>Email Sent to: '.$val;
}
}
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
echo '<hr>ERROR 001';
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
echo '<hr>ERROR 002';
}
}
i am trying to send email to user and to admin at the same time using phpmailer but only one email is sent.. either to user or to admin..
i have tried every possible way with no luck. please help
below is my code.
$html.="This is my message to user";
$bcc = "xxx#gmail.com";
$to= $clientemail;
$subject = "This is my subject;
$host = $SmtpServer;
$username = $SmtpUser;
$password = $SmtpPass;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "$host"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = $username; // SMTP username
$mail->Password = $password; // SMTP password
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
try {
$mail->From = $from;
$mail->FromName = $Name;
$mail->AddAddress(''.$to.'');
$mail->AddBCC('xxx#gmail.com');
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $html;
$mail->AltBody = $html;
$mail->Send();
// echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
$message="Thank you for your request.";
$html="this is my second message to admin";
$bcc = "xxx#gmail.com";
$to= $admin;
$subject = "message to admin;
$host = $SmtpServer;
$username = $SmtpUser;
$password = $SmtpPass;
$mail2 = new PHPMailer();
$mail2->IsSMTP();
$mail2->Host = "$host"; // specify main and backup server
$mail2->SMTPAuth = true; // turn on SMTP authentication
$mail2->Username = $username; // SMTP username
$mail2->Password = $password; // SMTP password
$mail2->Port = 587;
$mail2->SMTPSecure = 'tls';
try {
$mail2->From = $from;
$mail2->FromName = $from;
$mail2->AddAddress(''.$to.'');
$mail2->AddBCC('xxx#gmail.com');
$mail2->WordWrap = 50;
$mail2->IsHTML(true);
$mail2->Subject = $subject;
$mail2->Body = $html;
$mail2->AltBody = $html;
$mail2->Send();
// echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
I'm not sure if you want to send the same email or not to differents persons, but the first improvement to do is to factorize your code.
// here an example of a function to send the SAME email to differents persons
// $emails is an array
function sendMail($emails, $subjects, $msg) {
$mail = new PHPMailer();
$mail->IsSMTP();
try {
$mail->Host = "$host"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = $username; // SMTP username
$mail->Password = $password; // SMTP password
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->From = $from;
$mail->FromName = $Name;
foreach ($emails as $to) {
$mail->AddAddress($to);
}
$mail->AddBCC('xxx#gmail.com');
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $html;
$mail->AltBody = $html;
if(!$mail->Send()) {
// log if needed
}
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
}
now you can use this function with differents messages or subjects... whatever you want!
EDIT :
to send different message to users and admins :
//settings for admin
$emails = array('admin#mail.com', 'admin2#mail.com'); // or just array('admin#mail.com');
$subjects = 'my sub';
$msg = 'my msg';
sendMail($emails, $subjects, $msg);
//settings for users
$emails = array('user#mail.com');
$subjects = 'different or not sub';
$msg = 'different or not msg';
sendMail($emails, $subjects, $msg);