PHPMailer Sending just One File - php

I am trying to send email with multiple attachments using PHPMailer class. Multiple files are uploading successfully in directory but it's sending just one file in Email. And how to format my email body using bootstrap? Your suggestions will be highly appreciated. I am using PHPMailer 6.0.5
Here is my PHP Code:
<?php
$msg = '';
use PHPMailer\PHPMailer\PHPMailer;
include_once 'PHPMailer/PHPMailer.php';
include_once 'PHPMailer/Exception.php';
// include_once 'PHPMailer/SMTP.php';
if (isset($_POST['submit'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
}
} else {
$name = '';
}
$mail = new PHPMailer;
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
$mail->addAttachment($name);
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}

I moved the class creation up to be before the file file processing loop, and moved the attachment code in to the loop
<?php
$msg = '';
use PHPMailer\PHPMailer\PHPMailer;
include_once 'PHPMailer/PHPMailer.php';
include_once 'PHPMailer/Exception.php';
// include_once 'PHPMailer/SMTP.php';
if (isset($_POST['submit'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
$mail = new PHPMailer; //moved here
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
$mail->addAttachment($name); //attache here
}
} else {
$name = '';
}
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}

Related

Redirecting html page to another page using php

I am having problems getting php to redirect after processing an email message. I've tried all of the solutions mentioned on this page, as well as some involving javascript with no luck. Here are the relevant portions of my code:
function redirect($url) {
ob_start();
header('Location: '.$url);
ob_end_flush();
exit();
}
if ( isset($_REQUEST['sendemail']) ) {
header("Content-Type: text/plain");
header("X-Node: $hostname");
$from = $_REQUEST['from'];
$name = $_REQUEST['name'];
$toemail = "djsuson#gmail.com";
$subject = "Customer question";
$message = $_REQUEST['message'];
ob_start(); //start capturing output buffer because we want to change output to html
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->IsSMTP();
if ( strpos($hostname, 'cpnl') === FALSE ) //if not cPanel
$mail->Host = 'relay-hosting.secureserver.net';
else
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->From = $from;
$mail->FromName = $name;
$mail->AddAddress($toemail);
$mail->Subject = $subject;
$mail->Body = $message;
$mailresult = $mail->Send();
$mailconversation = nl2br(htmlspecialchars(ob_get_clean()));
if ( !$mailresult ) {
echo 'FAIL: ' . $mail->ErrorInfo . '<br />' . $mailconversation;
redirect('http://otterlywoods.com/failure.html');
} else {
echo $mailconversation;
redirect('http://otterlywoods.com/success.html');
}
Any help on this would be appreciated.

SMTP connect() failed. PHPMailer [duplicate]

This question already has answers here:
SMTP connect() failed phpmailer
(1 answer)
SMTP connect() failed PHPmailer - PHP
(17 answers)
Closed 1 year ago.
I'm using 000webhost server and I got an error while sending the email using PHPMailer, knowing that it works in localhost with tls and Port 587
Here is my code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/Exception.php';
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/PHPMailer.php';
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/SMTP.php';
if(isset($_POST['hdn-insert'])) {
$data=array();
$variables = array();
$name = $_POST['name'];
$email_from = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
$location = $query['city'] . ', ' . $query['country'] . '.';
$year = date('Y');
$variables['name'] = $_POST['name'];
$variables['email'] = $_POST['email'];
$variables['message'] = $_POST['message'];
$variables['location'] = $location;
$variables['year'] = $year;
$template = file_get_contents('MailUI.html');
foreach($variables as $key => $value)
{
$template = str_replace('{{ '.$key.' }}', $value, $template);
}
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "smtp.gmail.com"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = 'tls'; // ssl is deprecated
$mail->SMTPAuth = true;
$mail->Username = 'hazemcrunchy#gmail.com'; // email
$mail->Password = '**********'; // password
$mail->setFrom($email_from, $name); // From email and name
$mail->addAddress('hazemsamiir196#gmail.com', 'Hazem El-behairy'); // to email and name
$mail->Subject = $subject;
$mail->msgHTML($template); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported'; // If html emails is not supported by the receiver, show this body
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if(!empty($name) && !empty($email_from) && !empty($subject) && !empty($message) && strlen($message) >= '8'){
if(!ctype_space($name) && !ctype_space($email_from) && !ctype_space($subject) && !ctype_space($message)){
if ($mail->send()){
$data['status'] = 1;
} else {
$data['status'] = 0;
}
echo json_encode($data);
} else {
$data['status'] = 0;
}
}
else{
$data['status'] = 0;
}
}
?>
The error message is:
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
I hope you guys get me well.

Sending multiple mails in php mail

I am trying to send the multiple mails through my mailer from the below code, But it is showing error
apache http error occurred.
<?php
require 'phpmailer/PHPMailerAutoload.php';
if(isset($_POST['send']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$to_id = $_POST['toid'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.domain.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $email;
$mail->Password = $password;
$mail->setFrom('info#domain.com', 'Name');
$mail->addReplyTo('info#domain.com', 'Name');
// read the list of emails from the file.
$email_list = file("maillist1.csv");
// count how many emails there are.
$total_emails = count($email_list);
// go through the list and trim off the newline character.
for ($counter=0; $counter<$total_emails; $counter++) {
$email_list[$counter] = trim($email_list[$counter]);
}
// implode the list in
require 'phpmailer/PHPMailerAutoload.php';
if(isset($_POST['send']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$to_id = $_POST['toid'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.domain.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $email;
$mail->Password = $password;
$mail->setFrom('info#domain.com', 'Name');
$mail->addReplyTo('info#domain.com', 'Name');
// read the list of emails from the file.
$email_list = file("maillist1.csv");
// count how many emails there are.
$total_emails = count($email_list);
// go through the list and trim off the newline character.
for ($counter=0; $counter<$total_emails; $counter++) {
$email_list[$counter] = trim($email_list[$counter]);
}
// implode the list into a single variable, put commas in, apply as $to value.
$to = implode(",",$email_list);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML($message);
if ( mail($to,$subject,$message) ) {
echo "The email has been sent!";
} else {
echo "The email has failed!";
}
}
?>to a single variable, put commas in, apply as $to value.
$to = implode(",",$email_list);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML($message);
if ( mail($to,$subject,$message) ) {
echo "The email has been sent!";
} else {
echo "The email has failed!";
}
}
?>

Attachments working intermittently

I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>

How to send multiple emails in PHP and MySQL via phpmailer

I have a problem. When i click send button, just zxc#hotmail.com receives the message.
How to change it? I'm use Gmail SMTP send out.
There are 2 records in the database:
Here is my code:
include "phpmailer/class.phpmailer.php";
$host = "localhost";
$user = "root";
$pass = "root";
$db = "mailTest";
mysql_connect($host, $user, $pass);
mysql_select_db($db);
$query = "SELECT email FROM list";
$recordset = mysql_query($query);
$row_recordset = mysql_fetch_assoc($recordset);
$tota_row_recordset = mysql_num_rows($recordset);
$msg = strip_tags($_POST['msg']);
$mail= new PHPMailer(); //建立新物件
while($row = mysql_fetch_array($recordset))
{
$to = $row['email'];
$mail->AddAddress($to, "Test Message");
}
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->CharSet = "big5";
$mail->Subject = "Test Message";
$mail->Username = "xxxxxx";
$mail->Password = "xxxxxx";
$mail->Body = "$msg";
$mail->IsHTML(true);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header('Location: index.php');
}
With this loop you overwrite the recipient with each iteration, so only the last one stays to receive the email:
while($row = mysql_fetch_array($recordset))
{
$to = $row['email'];
}
$mail = new PHPMailer();
Change your code to
$mail = new PHPMailer(); // create object FIRST
while($row = mysql_fetch_array($recordset))
{
$to = $row['email'];
$mail->AddAddress($to, "Test Message"); // add each DB entry to list of recipients
}
try this below:
while($row = mysql_fetch_array($recordset))
{
$to = $row['email'];
$mail= new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->CharSet = "big5";
$mail->Subject = "Test Message";
$mail->Username = "xxxxxx";
$mail->Password = "xxxxxx";
$mail->Body = "$msg";
$mail->IsHTML(true);
$mail->AddAddress($to, "Test Message");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
if(isset($_POST['sbmit']))
{
for($i=0;$i<count($_POST['email_address']);$i++)
{
$to = $_POST['email_address'][$i];
echo $to."<br />";
$subject = 'Thank you for Subscribing';
$message = $_POST['news'];
$headers = 'From: dhakalneil#gmail.com' . "\r\n" .
'Reply-To: xyz#hotmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
echo $_POST['email_address'][$i]."<br />";
ini_set("SMTP","smtp.ntc.net.np" );
ini_set('sendmail_from', 'dhakalneil#gmail.com');
if( mail($to,$subject,$message,$headers))
{
echo "Mail has been sent to admin<br />";
}
else
{
echo "Mail could not been sent";
}
}
}
?>

Categories