How to send 2 emails with only one PHP contact form - php

I'm learning PHP and coding and am looking for a way to send 2 email confirmation with this PHP code. I tried to duplicate my mail function but didn't work. I'm not sure I have to duplicate the SMTP part too or not.
What can I try next?
<?php
use PHPMailer\PHPMailer\PHPMailer;
if ( isset ($_POST['name']) and isset ($_POST['email']) and isset ($_POST['message']) ){
$url = $_POST['url'];
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$rappel = $_POST['period'];
$message = $_POST['message'];
$address = $_POST['address'];
$ville = $_POST['city'];
$net = $_POST['net'];
$tv = $_POST['tv'];
$tel = $_POST['tel'];
$file_attach = $_FILES['file']['tmp_name'];
$file_attach_name = $_FILES['image']['name'];
$msg = '';
if (array_key_exists('email', $_POST)) {
date_default_timezone_set('Etc/UTC');
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "xxx#xxx.com";
$mail->Password = "";
$mail->setFrom('xxx#xxx.com');
$mail->addReplyTo('$email', '$name');
$cnt=count($_FILES['file']['name']);
if($cnt > 0){
for($i=0;$i<$cnt;$i++){
$mail->AddAttachment($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i],'base64',$_FILES['file']['type'][$i]);
}
}
if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
//Set the subject line
$mail->Subject = 'Message de votre site ' . $client . ' - ' . $name;
//Keep it simple - don't use HTML
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
//Build a simple message body
$mail->Body = file_get_contents('rd-mailform.tpl');
$mail->Body = str_replace(
["<!-- #{StartName} -->", "<!-- #{Name} -->"],
["Nom:", $_POST['name']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartPhone} -->", "<!-- #{Phone} -->"],
["Téléphone:", $_POST['phone']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartEmail} -->", "<!-- #{Email} -->"],
["Email:", $_POST['email']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{StartRappel} -->", "<!-- #{Rappel} -->"],
["Période de rappel:", $_POST['period']],
$mail->Body);
$mail->Body = str_replace(
["<!-- #{MessageStart} -->", "<!-- #{Message} -->"],
["Message:", $_POST['message']],
$mail->Body);
$mail->Body = $mail->Body."Adresse IP de l'expéditeur: $ssIPAddress / Localisation <a href='http://ipinfodb.com/ip_locator.php?ip=$ssIPAddress'>ici</a>, <a href='http://www.ip-tracker.org/ip-to-location.php?ip=$ssIPAddress'>ici</a> et <a href='http://whatismyipaddress.com/ip/$ssIPAddress'>ici</a></p>";
//Send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
print "<meta http-equiv=\"refresh\" content=\"0;URL=success.php\">";
}
}
?>

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.

warning in base64_encode of in phpmailer class

i am using phpmailer to send mail with attachment, which is sending mail with blank attachment and it shows following warning
Warning: base64_encode() expects parameter 1 to be string, object given in D:\xampp\htdocs\contactform\class\class.phpmailer.php on line 1958
i retrieve file from database which is stored as BLOB file
<?php
require 'config.php';
require 'class/class.phpmailer.php';
$message = '';
$errors ='';
$firstName = $lastName = $emailId = $mobileNumber = $add = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
$firstName = $conn->real_escape_string($_POST['fname']);
$lastName = $conn->real_escape_string($_POST['lname']);
$emailId = $conn->real_escape_string($_POST['email']);
$mobileNumber = $conn->real_escape_string($_POST['mobile']);
$add = $conn->real_escape_string($_POST['address']);
$fileName = $conn->real_escape_string($_FILES['myfile']['name']);
$tmp_name = $_FILES['myfile']['tmp_name'];
$name = $_FILES['myfile']['name'];
$size = $_FILES['myfile']['size'];
if(isset($_POST["submit"]))
{
if((isset($_POST['fname'])&& $_POST['fname'] !='' ))
{
$sql = "INSERT INTO form (fname, lname, email,mobile,address,file,filename,created) VALUES('".$firstName."','".$lastName."','".$emailId."', '".$mobileNumber."','".$add."','".$fileName."','".$name."',now())";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Registered successfully\n ";
}
}
else
{
echo "Please fill Name and Email";
}
$query="select file from form where email='$emailId'";
$result=$conn->query($query) or die('There was an error1 running the query [' . $conn->error . ']');
$result1="resume.pdf";
$encoding='base64';
$type=" application/pdf";
$message ="hi";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = '****';
$mail->Password = '****';
$mail->SMTPSecure = 'tls';
$mail->From = $_POST["email"];
$mail->FromName = $_POST["fname"];
$mail->AddAddress('***');
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->AddStringAttachment($result,$result1,$encoding,$type).
$mail->Subject = 'Applicant Profile';
$mail->Body = $message;
if($mail->Send())
{
$message = '<div class="alert alert-success">Application Successfully Submitted</div>';
}
else
{
$message = '<div class="alert alert-danger">There is an Error</div>';
echo $mail->ErrorInfo;
}
}
print_r($message);
?>
You're getting this error because $result contains a MySQLi result set object (mysqli_result), not a string. You need to extract the field value before you use it. Also PHPMailer will figure out the encoding and content type for you from the filename you provide (in $result1), so you don't need to set them yourself, like this:
$row = $result->fetch_row();
$mail->addStringAttachment($row[0], $result1);
A separate issue is that you're using a very old version of PHPMailer which has security holes and many bugs, and you've based your code on an obsolete example, so get the latest.

send email on localhost with PHP

I want to send an email on localhost but don't really know how to do it.
I tried some different ways but it doesn't work.
I used PHPMailer https://github.com/PHPMailer/PHPMailer/tree/5.2-stable as the mailserver but I think thats maybe wrong implemented or so.
Don't know if it's important but I use MAMP.
This is what I currently have:
<?php
if (isset($_POST['submit'])) {
require("PHPMailer/PHPMailerAutoload.php");
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->SMTPSecure = "ssl";
$mail->SMTPAuth = true;
$mail->Username = "mail account";
$mail->Password = "password for account";
$mail->Port = "465";
$mail->setFrom('receiver mail', 'TEST');
$mail->addReplyTo('receiver mail', 'TEST');
$mail->addAddress('recipient mail');
$mail->Port = "465";
$mail->isHTML(true);
$mail->Subject = "test";
// get text from input fields
$email = $_POST['email'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$number = $_POST['number'];
$textarea = $_POST['textarea'];
$bodyContent =
"<p>Name: " . $name . "</p>
<p>E-Mail: " . $email . "</p>
<p>Telefonnummer: " . $number . "</p>
<p>Adresse: " . $address . $city . "</p>
<p>Anliegen: " . $textarea . "</p>";
$mail->Body = $bodyContent;
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
}
?>
Comment out the following two lines :
// ini_set("SMTP","ssl://smtp.gmail.com");
// ini_set("smtp_port","465");
And add the following under the line with $mail = new PHPMailer();
$mail->isSMTP();
And it will work, I have tried it on my laptop on XAMPP.
Okay, i finally found the solution. I updated my code to this
<?php
if (isset($_POST['sendButton'])) {
require("PHPMailer/PHPMailerAutoload.php");
require 'PHPMailer/class.phpmailer.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "secret";
$mail->Password = "secret";
$subject = utf8_decode('test');
$mail->setFrom('secret', $subject);
$mail->addReplyTo('secret', $subject);
$mail->addAddress('secret');
$mail->Subject = utf8_decode('test');
$mail->Port = "587";
$mail->isHTML(true);
$email = $_POST['email'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$number = $_POST['number'];
$sendText = $_POST['sendText'];
$bodyContent =
"<p>Name: " . $name . "</p>
<p>E-Mail: " . $email . "</p>
<p>Telefonnummer: " . $number . "</p>
<p>Adresse: " . $address . ' ' . $city . "</p>
<p>Anliegen: " . $sendText . "</p>";
$mail->Body = $bodyContent;
}
?>
Besides I had to go to myaccount.google.com -> "Sign-in & security" -> "Apps with account access", and turn "Allow less secure apps" to "ON"
Now everything is fine.
Thank you for your help guys

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!";
}
}
?>

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