My website has a create account form, in which it inserts into a database and sends an email and verifies on my AWS SES server. But for some reason my code keeps freezing. If I put an echo "Testing" right above //include_phpmailer, "Testing" will not show up.
<?php
//include phpmailer
require_once('class.phpmailer.php');
require_once('ses.php');
$username = "scapXXXXXX";
$password = "baXXXXXXXX";
$hostname = "db4free.net:3306/scapterlogin";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Could Not establish connection!" . mysql_error());
$dbselect = mysql_select_db("scapterlogin", $dbhandle);
$myusername = $_POST['user'];
$mypassword = $_POST['pass'];
$myemail = $_POST['email'];
$query = "INSERT INTO userInfo (Username, Password, Email, activation_code) VALUES('$myusername', '$mypassword', '$myemail')";
$myquery = mysql_query($query);
if ($myquery) {
//verify email address using SES
$verify = new SimpleEmailService("access_key", "secret_key");
$verify->verifyEmailAddress($myemail));
//SMTP Settings
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "email-smtp.us-west-2.amazonaws.com";
$mail->Username = "AKIAXXXXXXXXX";
$mail->Password = "AoDRf8NBXXXXXXXXXXX";
//
$mail->SetFrom('webmaster#scapter.org', 'The Scapter Team'); //from (verified email address)
$mail->Subject = "New Account"; //subject
//message
$body = 'Dear " . $myusername . ", \r\n Welcome to Scapter! We hope you enjoy all of our products. We have got an account request from this email.
If you did not create an account, you can safely ignore this email.';
$body = eregi_replace("[\]",'',$body);
$mail->MsgHTML($body);
//
//recipient
$mail->AddAddress($myemail, $myusername);
//Success
if ($mail->Send()) {
//setcookie('loggedin', $myusername, Time()+3600);
//header('Location: login.php');
}
//Error
if(!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
There are couple of unusual factors in your code..
$hostname for db connection does not seem to be a valid one (db4free.net:3306/scapterlogin). If you have an IP address of the db server, you should use that instead.
Using
if ($mail->Send()) {}
and
if(!$mail->Send()) {}
effectively calls the same method twice you should replace 2nd occurrence with a simple else condition.
Using 'die' before $mail->Send() or $myquery = mysql_query($query); can help you identify whether the specific block of code is causing trouble.
You say if you echo on the first line, it will not show up, which leads me to believe that the file is not being loaded, and maybe you have error display turned off, so it's not giving you an error? Check your logs for errors - maybe you are not loading this file with the correct name or you have permissions set so that your server doesn't want to run it.
Related
I'm using PHPMailer on my website, but it returns an error:
You must provide at least one recipient email address.
I've checked out the following pages looking for answers:
https://github.com/PHPMailer/PHPMailer/issues/441
https://github.com/PHPMailer/PHPMailer/issues/429
None of those solved my problem.
This is the way it's set up:
<?php
$conn=mysqli_connect("localhost","sar","siarth2");
mysqli_select_db($conn,"test");
$Email=$_REQUEST["Email"];
$query=mysqli_query($conn,"select * from user where Email='$Email'");
$row=mysqli_fetch_array($query,MYSQLI_ASSOC);
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = TRUE;
$mail->Username = "sidban5679#gmail.com";
$mail->Password = "password";
$mail->Port =466;
$mail->From = "sidban5679#gmail.com";
$mail->FromName = "Sidharth";
$mail->AddAddress($row["Email"]);
$mail->isHTML(true);
$mail->Subject = "Password";
$mail->Body = "<i>this is your password:</i>".$row["Password"];
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
SQL Code
INSERT INTO user (Password, FirstName, LastName, Email) VALUES
('friends34', 'Kaser', 'Baddal', 'banh5#gmail.com');
Check that if your $Email and $row['Email'] is returning any valid email address or not.
you can try once with a hard coded recipient.
$mail->AddAddress('receipient#example.com');
I guess from your code, $Email and $row['Email'] are same value. so if $Email=$_REQUEST["Email"]; is getting valid email, you can use -
$mail->AddAddress($Email);
On top of the wrong port number, SQL injection vulnerability, plain-text passwords, that you're using an outdated version of PHPMailer, and have based your code on an obsolete example, you're not doing any error checking on the email address. Try this:
if (!$mail->addAddress($row['Email'])) {
exit(htmlspecialchars($row['Email']) . ' is not a valid email address.');
}
(htmlspecialchars() is there to avoid adding an XSS vulnerability for a perfect score!)
I'm using PHPMailer to send an email from a form to all the emails in a MySQL database.
I've managed to get the form to send an email to each email but I'm now trying to use their name in the email sent to them meaning each email woud begin with "Hello, [their-name],".
I'm using an array to loop through the results of my database query and adding each email and name as $mail->addAddress('email#email.com, 'name');
I've tried saving the variable $name = $row['name'}; inside the while loop but it inputs the last name from the database into all the emails.
My question is: Is it possible to access the 'name' part of the function and use it each email. Or is it better to take their name from the database itself? And if so how would I go about doing that?
Also, when the email sends to each recipient, it shows all of the recipients in the "To:" field. This would be pretty bad for privacy. Is there a way to prevent this?
I'm fairly new to PHP and MySQL still so explanatory answers would be greatly appreciated.
Please find my code below.
<?php
// Take message value from form
$message = preg_replace("/\r\n|\r/", "<br />", $_REQUEST['message']);
$message = trim($message);
// Error reporting on
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
// Require PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 587;
$mail->Username = 'my#email.com';
$mail->Password = 'mypassword';
$mail->setFrom('myemail#email.com', 'Me');
$mail->addReplyTo('myemail#email.com', 'Me');
$mail->Subject = "Newsletter";
/* ----- Add address function below ----- */
// Require Database connection
require 'dbcon.php';
// SELECT email and name values from database
$query = "SELECT email, name FROM customers";
// Result = the database query
$result = $con->query($query);
// Get array of users email addresses and names.
while($row = $result->fetch_array())
{
// Add recipients from values found in database
$mail->addAddress($row["email"], $row["name"]);
}
/* ----- Add address function above ----- */
$mail->Body ="Hello, <br> <br> $message";
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent.";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
print 'Sent!';
?>
You are currently setting up to send a single email with several recipients. For security and etiquette, you should address the email to yourself (outside the loop):
$mail->addAddress('myemail#email.com', 'Me');
...and then add all of the recipients as BCC (inside the loop):
$mail->addBCC($row["email"], $row["name"]);
As for the name field. Add a debug line inside your loop and take a look at your output. Is the name field the same each time?
print "Adding recipient: {$row['email']} {$row['name']}";
If you want to sent several emails, one to each recipient, you need to instantiate a new email inside the loop each time.
[UPDATE]
If you want to send a single message to each recipient, then instantiate a new email each time (inside your loop):
<?php
// Take message value from form
$message = preg_replace("/\r\n|\r/", "<br />", $_REQUEST['message']);
$message = trim($message);
// Error reporting on
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
// Require PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
// Require Database connection
require 'dbcon.php';
// SELECT email and name values from database
$query = "SELECT email, name FROM customers";
// Result = the database query
$result = $con->query($query);
// Get array of users email addresses and names.
while($row = $result->fetch_array())
{
// Instantiate a NEW email
$mail = new PHPMailer;
// Set the email settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 587;
$mail->Username = 'my#email.com';
$mail->Password = 'mypassword';
$mail->setFrom('myemail#email.com', 'Me');
$mail->addReplyTo('myemail#email.com', 'Me');
$mail->Subject = "Newsletter";
// Add recipient from values found in database
$mail->addAddress($row["email"], $row["name"]);
$mail->Body ="Hello, <br> <br> $message";
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent.";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
print "Sent mail to: {$row["email"]}, {$row["name"]}";
}
?>
I created a form where a user types in a code,if the code and email exists in database the code then retrieves the email and a token is generated and updated to the database and has to be sent to that email that is retrieved. I am using php mailer to send an email, can someone help me figure what is wrong with the code below, is the url query correct?
<?php
error_reporting(1);
session_start();
include 'includes/connect.php';
include 'includes/additional_function.php';
include('classes/phpmailer/phpmailer.php');
if($_POST["Submit"]=="Submit"){
$idcode=$_POST['idcode'];
$_SESSION['idcode'] = $post['idcode'];
$sql = "SELECT * FROM people WHERE idcode = :idcode";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':idcode', $idcode);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
$email = $result['email'];
//echo $email;
$token = generateToken();
//echo $token;
$sql = "UPDATE student SET token = :token WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
{
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer#bradm.inmotiontesting.com
// pass: password
$mail->Username = "send_from_PHPMailer#bradm.inmotiontesting.com"; // SMTP username
$mail->Password = "password"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("bradm#inmotiontesting.com", "Brad Markle");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You Registration Link!";
$mail->Body = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
$mail->AltBody = 'Click to Register';
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
}
}
else{
echo 'You are not Registered';
}
}
?>
Firstly, variables don't get parsed in single quotes
$mail->Body = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
wrap it in double quotes
$mail->Body = "http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id";
and will not populate themselves in the email sent.
Which for example:
$token = "abcde";
echo $var = 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id';
echo "<br>";
echo $var = "http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id";
will echo the following:
http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id
http://www.domain.com/register/registration.php?token=abcde&stud_id=stud_id
As you can see, $token doesn't get its intended value populated, but echos as $token instead of abcde.
Reference:
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single
This is assuming your conditional statement and POST arrays are kosher.
Plus this $post['idcode'] needs to read as $_POST['idcode'] as per $idcode=$_POST['idcode']; and error reporting would have helped you here. That's a superglobal http://php.net/manual/en/language.variables.superglobals.php and missed the underscore and putting POST in uppercase letters.
If you're unsure:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
or post your HTML form in your question.
Footnotes:
Unsure what you want to use stud_id for and how that is supposed to be populated. Only you know that. As per $token&stud_id=stud_id';
Now, if your query is failing, then that's a different story and you would need to find out why that is and is beyond the scope of the question.
http://php.net/manual/en/pdo.error-handling.php
The "search result" brings up a table, and at the end of each row there is an "email-button". Visitor clicks one "email-button" and the system sends an email to that registered "user".
The PHPMailer and the mailing system is working fine, but ONLY with static email!
QUESTION: what do I need to change on the code to send email to the single email what the visitor chooses. I have added a "WHERE" condition to the $query but it seems to have no impact.
MAILING FUNCTION WITH THE FOLLOWING TWO LINES IS WORKING
$mail->AddAddress("support#domain.co.uk", "John Doe");
$mail->AddAddress("admin#domain.co.uk");
WITH THE FOLLOWING LINE IS NOT WORKING
$mail->AddAddress("$email", "John Doe");
ERROR MESSAGE SAYS:
"Invalid address: Message could not be sent."
"Mailer Error: You must provide at least one recipient email address."
<?php
//mailer.php
$dbhost = 'xxx.xxx.xxx.xxx';
$dbuser = 'user_name';
$dbpass = 'password';
$dbtable = 'tablename';
$db = 'db_name';
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$db) or
die("Could not connect: " . mysql_error());
mysqli_select_db($conn,$db);
if(isset($_POST['requestedEmail'])){
$requestedEmail = $_POST['requestedEmail'];
}
//Connecting to database
$link = mysqli_connect($dbhost, $dbuser, $dbpass, $db) OR DIE ("Unable to connect to database! Please try again later.");
mysqli_select_db($conn,$db);
//Fetching from database table.
$query = "SELECT email FROM db_name WHERE email='". $requestedEmail . "'";
if ($result)
{
while ($row = mysqli_fetch_array($result)) {
send_mail($row['email']);
}
}
//$email = $row['email'];
?>
<?php
require 'PHPMailer_5.2.0/class.phpmailer.php';
$email = $row['email'];
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "domainname.co.uk;domainname.co.uk"; // specify main and back`enter code here`up server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "support#domain.co.uk"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->From = "support#domain.co.uk";
$mail->FromName ="Company Name";
$mail->AddAddress($email, "John Doe");
$mail->AddReplyTo("info#domain.co.uk", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Here is the subject 3.4";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent to: " . $email; // $email is not printed out
?>
This seems wrong
$query = "SELECT email FROM db_name WHERE email=$row[email]";
where is it getting the $row[email] from? you need to have a valid variable in there - such as from the post array (assuminig you are passing the variable from a form. Something like:
if(isset($_POST['requestedEmail'])){
$requestedEmail = $_POST['requestedEmail']}
// other code
$query = "SELECT email FROM db_name WHERE email='". $requestedEmail . "';
Then you get the email out of the returned $row (assuming you are using that variable from the returned query
$email = $Row['email'];
Then you can use $email (without quotes since it is a variable rather than a string):
$mail->AddAddress($email, "John Doe");
This line:
$mail->AddAddress("$email", "John Doe");
Should be changed to this:
$mail->AddAddress($email, "John Doe");
When passing a variable as a parameter in PHP, you don't use quotation marks around the variable like you would when passing a string. So in your code, you aren't passing the variable $email, you're passing the string "$email".
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!";
}