PHPMail - can I send two unique emails - php

I'm using PHPMailer to successfully send an email upon a webform submission (so just using basic post data, no mysql databases or any lookups).
What I need to do is send two seperate emails, one version for the customer and the other for a customer service agent - so that when a user completes a webform, they will receive a 'marketing' version of the email, whilst the customer service agent will receive an email just containing the details submitted by the user.
See below what im using at the moment, but not sure how to best implement to send the secoind email? It presently fails and the script exits after sending only one email.
$body = ob_get_contents();
$to = 'removed';
$email = 'removed';
$fromaddress = "removed";
$fromname = "removed";
require("phpmailer.php");
$mail = new PHPMailer();
$mail->From = $fromaddress;
$mail->FromName = $fromname ;
$mail->AddAddress("email#example.com");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "Subject";
$mail->Body = $body;
$mail->AltBody = "This is the text-only body";
if(!$mail->Send()) {
$recipient = 'email#example.com';
$subject = 'Contact form failed';
$content = $body;
mail($recipient, $subject, $content,
"From: mail#yourdomain.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
exit;
}
//Send the customer version
$mail=new PHPMailer();
$mail->SetFrom('email', 'FULLNAME');
$mail->AddAddress($mail_vars[2], 'sss');
$mail->Subject = "Customers email";
$mail->MsgHTML("email body here");
//$mail->Send();

In the customer version you are not setting the email's properties the same way you are in the first. For example you use $mail->From = $fromaddress; in the first and $mail->SetFrom('email', 'FULLNAME'); in the second.
Because you instantiated a new $mail=new PHPMailer(); you need to set the properties again.

Instead of just bailing out with a useless "something didn't work" message, why not have PHPMailer TELL you what the problem is?
if (!$mail->send()) {
$error = $mail->ErrorInfo;
echo "Mail failed with error: $error";
}

Related

Sending mail to both sender and receiver using PHPmailer

I am using phpmailer in live server for sending emails for both sender and receiver. Its working fine but I want to include additional message in sender copy as "thanks for registering with us". I am unable to do it.
Could you please help with this ?
Code I tried So far:
<?php
$msg = "";
if (isset($_POST['submit'])) {
require 'phpmailer/PHPMailerAutoload.php';
function sendemail($to, $from, $fromName, $body) {
$mail = new PHPMailer();
$mail->setFrom($from, $fromName);
$mail->addAddress($to);
$mail->Subject = 'Contact Form - Email';
$mail->Body = $body;
$mail->isHTML(false);
return $mail->send();
}
function sender_mail($to, $from, $fromName, $body) {
$mail = new PHPMailer();
$mail->setFrom($from, $fromName);
$mail->addAddress($to);
$mail->Subject = 'Copy Contact Form - Email';
$mail->Body = $body . 'Thanks for registering with us';
$mail->isHTML(false);
return $mail->send();
}
$name = $_POST['username'];
$email = $_POST['email'];
$body = $_POST['body'];
sendemail('abc#domain.com', 'xyz#domain.com', $name, $body);
sender_mail('abc#domain.com', $email, $name, $body);
}?>
I always create different mail object for sending another email. So it will always pick new message.
For sending another email you can update like below:
$mail2 = new PHPMailer();
$mail2->setFrom($from, $fromName);
$mail2->addAddress($to);
$mail2->Subject = 'Copy Contact Form - Email';
$mail2->Body = $body . 'Thanks for registering with us';
$mail2->isHTML(false);
return $mail2->send();
2nd option to use clearAddresses above your second email to clear your earlier messages like below:
$mail->clearAddresses();
$mail = new PHPMailer();
$mail->setFrom($from, $fromName);
$mail->addAddress($to);
$mail->Subject = 'Copy Contact Form - Email';
$mail->Body = $body . 'Thanks for registering with us';
$mail->isHTML(false);
return $mail->send();

mail.php script not working for subscribe and contact page [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
My web developer made this script to send notifications to people subscribing to my mailing list and the people who contact me, through the form on my website
The problem is, the recipients are not able to receive the emails, and I am not able to receive the notification on my mail id about a new subscriber or a contact
Sender id - notifications#llaveshagarwal.com
Moreover, the same script works on his server (which we used for testing) but doesn't work on my server
Is there a problem with my SMTP server settings ?
Also, I am using Google Apps for Gmail
Here is his script
What should I do ?
<?php
if($_POST['type'] == "subscribe") {
/*$to = "notifications#llaveshagarwal.com";
$subject = "New Email Subscriber";
$txt = "Name: ".$_POST['name']."\r\nFrom: ".$_POST['from'];
$headers = "From: ".$_POST['from'];
mail($to,$subject,$txt,$headers);
$to = $_POST['from'];
$subject = "Thank you for subscribing with us.";
$txt = "Hey ".$_POST['name']." ,\r\nGreetings from LLavesh Agarwal Textile Agency\r\nThank you for subscribing with us for Exclusive and Latest Catalogs and product launches.\r\nWe will update you soon.\r\n\r\nRegards,\r\nTeam LLavesh Agarwal\r\n\r\n*This is an automated Email. Please do not reply to this Email id. If you wish to talk to us, kindly Email us at hello#llaveshagarwal.com";
$headers = "From: notifications#llaveshagarwal.com";
mail($to,$subject,$txt,$headers);*/
$link = mysql_connect('localhost', 'llavesha_admin', 'Admin#1234');
$db= mysql_select_db('llavesha_contact_system', $link);
$insert='insert into subscribe (name,email) values ("'.$_POST["name"].'","'.$_POST["from"].'")';
if(mysql_query($insert)) {
echo "success";
} else {
echo "fail";
}
}
elseif($_POST['type'] == "contact") {
$to = "notifications#llaveshagarwal.com";
$subject = "New Contact";
$txt = "Name: ".$_POST['name']."\r\nContact: ".$_POST['mobile']."\r\nCategory: ".$_POST['bussiness_type']."\r\nDescription: ".$_POST['project_detail'];
$headers = "From: ".$_POST['from'];
mail($to,$subject,$txt,$headers);
$to = $_POST['from'];
$subject = "Thank you for contacting us.";
$txt = "Hey ".$_POST['name']." ,\r\nGreetings from LLavesh Agarwal Textile Agency\r\nThank you for contacting us.\r\nWe will update you soon !\r\n\r\nRegards,\r\nTeam LLavesh Agarwal\r\n\r\n*This is an automated Email. Please do not reply to this Email id. If you wish to talk to us, kindly Email us at hello#llaveshagarwal.com";
$headers = "From: notifications#llaveshagarwal.com";
mail($to,$subject,$txt,$headers);
echo "success";
}
?>
Are you working on windows (wamp)? Have you enabling php sendmail on php.ini? read: http://us3.php.net/manual/en/function.mail.php
or you can read: php mail() function on localhost
If you want to make it simpler, use phpmailer instead: https://github.com/PHPMailer/PHPMailer
How to use it by #pooria: How to configure PHP to send e-mail?
require('./PHPMailer/class.phpmailer.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';
$body = 'This is the message';
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Username = 'me.sender#gmail.com';
$mail->Password = '123!##';
$mail->SetFrom('me.sender#gmail.com', $name);
$mail->AddReplyTo('no-reply#mycomp.com','no-reply');
$mail->Subject = 'subject';
$mail->MsgHTML($body);
$mail->AddAddress('abc1#gmail.com', 'title1');
$mail->AddAddress('abc2#gmail.com', 'title2'); /* ... */
$mail->AddAttachment($fileName);
$mail->send();

PHPMailer send multiple emails fails

I'm having a problem with PHPMailer. I'm creating a page for job applications for a company. There is a form, which the applicant fills, and the form data is sent to the HR. Then there must be an automatic response from the server to the applicant which thanks the application. The first email to the HR is sent, but the second is not. The code is:
$mailer = new PHPMailer();
$mailer->From = "admin#bav.hu";
$mailer->FromName = "Báv gyakornoki jelentkezés";
$mailer->AddAddress("dudas.krisztian#nerddevelopments.com", "the subject");
$mailer->isHTML(true);
$mailer->CharSet = 'UTF-8';
$mailer->Subject = "Báv gyakornoki regisztráció";
$body = "The body with the form data to HR";
$mailer->Body = $body;
$mailer->AddAttachment($cv_path, $_FILES['cv']['name']);
$mailer->AddAttachment($motivation_letter_path, $_FILES['motivation']['name']);
$success = $mailer->send();
//this email gets sent
$autoresponse = new PHPMailer();
$autoresponse->From = "gyakornok#bav.hu";
$autoresponse->CharSet = "UTF-8";
$autoresponse->AddAddress($email);
$autoresponse->Subject = "This is an automatic message, please don't answer it";
$body = "This is the automatic response to the applicant";
$autoresponse->body = $body;
$autoresponse_sent = $autoresponse->send();
//this email won't get sent
Change
$autoresponse->body = $body;
to
$autoresponse->Body = $body;

sending emails when a form is submitted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
im trying to make it so that when a form is submitted, it would send an email. The database connecting/submitting is working so it's nothing from the database or form side hopefully.
Here is my code:
<?php
$mysql_host = "localhost";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$mysql_database2 = "";
$sub = $_POST['subject'];
$mysqli2 = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database2) or die(mysqli_error());
$head = $mysqli2->query("SELECT head FROM class WHERE subject = '$sub'")->fetch_object()->head;
$status = 1;
$mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database) or die(mysqli_error());
$prepare = $mysqli->prepare("INSERT INTO `Overrides`(`name`,`mname`,`fname`,`sid`,`email`,`phone`,`sc`,`subject`,`section`,`semester`,`professor`,`status`,`dean`,`head`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$prepare->bind_param("ssssssssssssss", $_POST['name'], $_POST['mname'], $_POST['fname'], $_POST['sid'], $_POST['email'], $_POST['phone'], $_POST['Scolarship'], $_POST['subject'], $_POST['section'], $_POST['semester'], $_POST['professor'], $status, $_POST['dean'], $head);
$prepare->execute();
$name = $_POST['name'];
$mname= $_POST['mname'];
$fname = $_POST['fname'];
$email = $_POST['email'];
$semester = $_POST['semester'];
$sid = $_POST['sid'];
$subject = $_POST['subject'];
$section = $_POST['section'];
$professor = $_POST['professor'];
if(prepare)
{
$to = '$email'; //can receive notification
$subject = 'Override Request';
$message = 'Dear $name<br /><br />
Your Following override request has been submitted.<br /><br />
Name: $name . $mname . $fname
Student ID : $sid
Semester : $semester
Subject : $subject
Section : $section
Professor : $professor<br /><br />
Please note that the request is passed to different faculty members in order to be revised. You will be notified on each update';
$headers = 'From: system#auke.edu.kw' . "\r\n" .
'Reply-To: webmaster#ourcompany.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo 'Email Sent.';
}
print 'Error : ('. $mysqli->errno .') '. $mysqli->error;
?>
It prints email sent but i get nothing on my mail.
Thanks.
$to = '$email';
Have to be
$to = "$email";
or - better:
$to = $email;
You should read this Curly braces in string in PHP
In your code "Email sent" will be allways display.
Try:
if ( mail($to, $subject, $message, $headers) )
echo "Sent";
else
echo "Error";
One of the problems is here
if(prepare)
prepare is treated as a constant rather than the intended variable $prepare.
Do if($prepare){...}
Also your variables need to be in double quotes.
$to = '$email';
variables do not get interpolated in single quotes
$to = "$email";
same for $message = '...'; that should be $message = "...";
You should also be doing and replacing $prepare->execute(); with
if(!$prepare->execute()){
trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);
}
or
if(!$prepare->execute()){
trigger_error("there was an error....".$mysqli2->error, E_USER_WARNING);
}
for your SELECT connection.
to check for possible db errors.
Also make sure your form uses a POST method and that all elements bear the proper name attributes.
Form will fail silently if the POST method is omitted.
It also defaults to GET if omitted. I don't know what the form looks like, so you'll need to look into that.
Edit: (adding PHPmailer information)
Seeing as you may not have access to using mail(), you could try using PHPmailer and a Gmail account if you have one.
Here is an example pulled from https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps
Visit also their main page: http://phpmailer.worxware.com/index.php
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$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';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "username#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto#example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}

Converting PHP Contact Form to SMTP

had alot fo problems making a functional contact form tonight. After messing for hours i finally found out that i can only use SMTP with my web hoster.
Can anyone please advice me how i can complete my form?
This is my current SMTP PHP Form
$mail = new PHPMailer();
//Your SMTP servers details
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server or localhost
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "enquiries#c(hidden)y.co.uk"; // SMTP username
$mail->Password = "******"; // SMTP password
//It should be same as that of the SMTP user
$redirect_url = "http://".$_SERVER['SERVER_NAME']; //Redirect URL after submit the form
$mail->From = $mail->Username; //Default From email same as smtp user
$mail->FromName = "Display Name";
$mail->AddAddress("enquiries#c(hidden)y.co.uk", "chapnolo"); //Email address where you wish to receive/collect those emails.
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = $_POST['subject'];
$message = "Name of the requestor :".$_POST['fullname']." \r\n <br>Email Adrress :".$_POST['email']." \r\n <br> Query :".$_POST['query'];
$mail->Body = $message;
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
header("Location: $redirect_url");
}
?>
I need my form to have the following functionality for me to retrieve the requires e-mail message body.
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
$web = $_POST['web'];
$formcontent="From: $name \n Contact: $number \n Website: $web \n Message: $message";
$recipient = "enquiries#c(hidden)y.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email ";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='contact.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
Help will be greatly appreciated
Metexora - So you're not having any issues with the code, you just haven't told it to send you the name contact number, email and message body - just change:
$message = "Name of the requestor :".$_POST['fullname']." \r\n <br>Email Adrress :".$_POST['email']." \r\n <br> Query :".$_POST['query'];
to
$message = "Name of the requestor :".$name." \r\n <br>Email Adrress :".$email." \r\n <br> Phone number :".$number."\r\n <br> Message: ".$message."\r\n <br> Website: ".$web;
(Note: Be careful, you are re-declaring $message here, that isn't really recommended practise given they refer to different things, the user message and the email message, you should only use the change the contents of a variable if it still refers to the same thing)

Categories