I want to send a mail using php through Gmail. I've seen many websites how to do it but I don't Understand how to do them. I am still stuck at the code I've written at first. Please help me how to connect my website (hosted on GoDaddy) to gmail account, and tell correct path to do that.
I am writing a code for clearer vision. In this php code, I am trying to add data in database and if the code works, the user should get an email from the company
if (isset($_POST['name']) && isset($_POST['mobile']) && isset($_POST['email']) && isset($_POST['practice']) && isset($_POST['date']) && isset($_POST['time']))
{
include "_credentials.php";
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$practice = $_POST['practice'];
$date = $_POST['date'];
$time = $_POST['time'];
$sql = "INSERT INTO <database> (Name, Number, email, Practice, Time, Date) VALUES ('".$name."', ".$mobile.",'".$email."','".$practice."','".$date."','".$time."');";
if ($conn->query($sql) === TRUE) {
$to = $email;
$host = "ssl://smtp.gmail.com";
$subject = "Appointment Confirmation";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: abc#gmail.com' . "\r\n";
$txt = "Hello ".$name.",\n Your Appointment is booked with Doctor at Clinic on ".$date." at ".$time.".";
mail($to,$subject,$message,$headers);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
First of all you need need to check for error response on mail() function using the following snippet
$success = mail('example#example.com', 'My Subject', $message);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
After the error message , you will be able to sort it out
Related
I want to send mail (only once) using php when $cstt == 10. I want to prevent sending mail on every time I refresh the page. here is my code
if ($cstt == 10) {
echo "Great";
// SENDING EMAIL
$to = "user#example.com";
$subject = "$tracking_id_user is in transit.";
$message =' Hi user, Simple html message. Best Regards!';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Company <info#company.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
echo "mail send";
}else{
echo "email not sent";
}
}
I did the following tasks to achieve the result.
Created a Table mail_record.
added id and mail_sent columns.
after creating the table, wrote the following code.
Connectin to database
$conn = new mysqli('localhost', 'user_id', 'password', 'databasename');
Accessing the data
$sql = "SELECT * FROM mail_record";
$query = $conn->query($sql);
$row = $query->fetch_assoc();
Accessing database to get mail_sent record.
// GETTING MAIL SENT / NOT RECORD (BLANK = NOT SENT & yes10 = Sent)
$mail_status = $row(['mail_sent']);
// CREATING THE CONDITION
if($cstt == 10 and $mail_status == ''){
// SENDING EMAIL if $cstt = 10 & email is not sent (blank)
$to = "admin#example.com, user#example.com";
$subject = "email subject";
$message ='Hi user, email text';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Web admin <admin#example.com>' . "\r\n";
if(mail($to,$subject,$message,$headers)){
// ADDING The RECORD THAT EMAIL HAS BEEN SENT FOR ($CSTT == 10)
$sql = "INSERT INTO `mail_record ` (`mail_sent`) VALUES ('yes10')";
if ($conn->query($sql) === TRUE) {
echo "Email sent and record added successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
by adding a if condition / logic we can write a code to execute mail send action only once.
now if you refresh the page the first if condition will give result FALSE because $cstt == 10 TRUE but $mail_status == '' FALSE.
using this method you can be very sure that the mail will be sent only once. no matter how many times page is being refreshed.
I want to store that value in a database after computing the domain. I have done everything right as per my knowledge but data is not being sent to the table.
Note : My mysql server is in AWS and I've opened the mysql port
My code is below,
<?php
$con = mysqli_connect("localhost","user_name","passwd","db_name");
$sql = "INSERT INTO contact_form (name, mobile, email, message) VALUES ('".$_POST['name']."', '".$_POST['phone']."', '".$_POST['email']."', '".$_POST['message']."')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
$to = 'contact#xxx.com';
$subject = 'Contact Form';
$from = 'contact#xxx.com';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi!</h1>';
$message .= '<p>Name :'. $_POST['name'] .' </p>';
$message .= '<p>Contact Number :'.$_POST['phone'] .'</p>';$message .= '<p>Email :'.$_POST['email'] .'</p>';
$message .= '<p>Message :'.$_POST['message'] .'</p>';
$message .= '</body></html>';
// Sending email
mail($to, $subject, $message, $headers);
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
?>
Please help me out. I'm not good in mysql. Thanks in advance !!
Ahamed, first of all you need to check if you have set your $_POST and it is not empty. Then you need to assign this data to custom variables.
I hope it helps.
$con = mysqli_connect("localhost","user_name","passwd","db_name");
if (isset($_POST['name']) && isset($_POST['phone']) && isset($_POST['email']) && isset($_POST['message'])){
$username = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO contact_form (name, mobile, email, message) VALUES ('$username', '$phone', '$email', '$message')";
$result = $con->query($sql);
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have searched stack overflow as well as the Ubuntu forums. I am writing a website and I am hosting it myself using a LAMP server. I have a form that a user fills out and want it to send an email once the user clicks the submit button. So far I have tried sendmail, ssmtp, phpmailer, and installing mailutils and using postfix. The reason I believe that it's an issue with the mail program is because after testing I'm getting no errors from the code and I am unable to send mail from the commandline. I would prefer not to use phpmailer as I don't want to hardcode any passwords in the website in the event it gets compromised. I would appreciate any help someone could give me. I have included the mail script if you need config files let me know Thank you in advance.
<?php
session_start();
if(isset($_POST['submit'])){
$to = "jmaggsdf#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Website Email";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$type = 'plain'; // or HTML
$charset = 'utf-8';
$_SESSION['from'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['first_name'];
$_SESSION['last_name'] = $_POST['last_name'];
$_SESSION['message'] = $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n";
$headers .= 'To: ' . $to . '<' . $to . '>' . "\r\n";
$headers .= 'From: ' . $from . '<' . $from . '>' . "\r\n";
if($first_name == NULL || $last_name == NULL || $from == NULL || $message == NULL){
header("Location: mailError.php");
die();
}
else{
//$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
header("Location: thanksPage.php");
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
//echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
}
?>
It you are sending mail using local host then it will not send mail.
It requires live server.
I have a problem with this code returning nothing but a blank page... I have followed several different tutorials to try and get this working, I am not a proficient PHP coder at all - But do have a little understanding. My server however, doesn't show error messages. So pinpointing this is rather hard for me to do!
I added this top section here to prevent spam using a hidden field on the html page that posts to this email page.
<?php
$if(isset($_POST['subject'],$_POST['Customer'],$_POST['Email'],$_POST['Phone'],$_POST['Comment'],$_POST['Product'],$_POST['Amount'],$_POST['Valid'])) {
$if(isset($_POST['Name']) && !empty($_POST['Name'])) {
echo "Spam Detected!";
Die();
}
Here is the email part that is supposed to send email once the above section determines that field "name" is empty.
$subject = $_POST['subject'];
$name = $_POST['Customer'];
$from = $_POST['Email'];
$phone = $_POST['Phone'];
$message = $_POST['Comment'];
$prod = $_POST['Product'];
$cash = $_POST['Amount'];
$valid = $_POST['Valid'];
$to = "email#email.com";
$body = 'HTML EMAIL CONTENT HERE...';
$headers .= "From: $from " . "Subject";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
mail($to,$subject,$body,$headers);
}
?>
Any and all help will be greatly appreciated!
Thanks
use this i see your code you use $if try if without $
if(isset($_POST['subject'],$_POST['Customer'],$_POST['Email'],$_POST['Phone'],$_POST['Comment'],$_POST['Product'],$_POST['Amount'],$_POST['Valid'])) {
if(isset($_POST['Name']) && !empty($_POST['Name'])) {
echo "Spam Detected!";
Die();
}
}
I have a small web app where people can send a message via email to a group. Because of spam I will have to make an approval procedure.
The messages are being sent via PHP. How am I doing so I have to accept the message before its send to an email that forward it to the group?
My PHP:
<?php
$errors = '';
$myemail = 'whatever#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n FEJL: Alle felter skal udfyldes";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$email_subject = "Form request";
$times = $_POST["timeslots"];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n FEJL: Ugyldig email adresse";
}
$strTimes = implode($times);
if( empty($errors))
{
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thx.html');
}
?>
ok so this is a fair size project in itself if you want to use a data queue.
ASSUMING you want to use a database you will need to know the basics of setting one up, how to use and setup tables etc. (as long as you have access to a database anyway).
Here is some connection code:
change peter and abc123 to whatever username and password your database has associated with it.
$con = mysql_connect("localhost","peter","abc123");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db");
I will give you some sample code for inserting rows to the database, selecting rows from the database, acting on that info and deleting rows from the database.
Ok lets start with the mail submission:
This section near the bottom of your code is the data we need to manipulate
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
So assuming you have a mysql database connection with a table setup in the database this is how you would insert it: (please note this is a basic insert query)
$query = "INSERT INTO queuemails (to, subject, body, headers) VALUES ('" . $to . "', '" . $email_subject . "', '" . $email_body . "', '" . $headers . "')";
mysql_query($query);
Ok so those 2 lines would be added BELOW your set variables.
You then need to provide a method of approval page.
This can be done on the same page but you have to seperate out your mail() function from the rest of the script.
Ok so here is a select script now to be able to VIEW your queue for approval. Please note that I have added an auto increment column to the table that stored your queued mail. This is to be able to select a line in the table more easily as is generates a unique number for that line of data. This column is called mid (standing for "mail identity").
ok so here is the selection script:
$query = "SELECT * FROM queuemail"; //this is only good if you know you wont get millions else you need to limit it
//limited select:
//$query = "SELECT * FROM queuemail LIMIT 0,10"; //selects the first 10
while($m = mysql_fetch_assoc(mysql_query($query))){
echo $m['to'] . " ";
echo $m['subject'] . " ";
echo '<a href=approve.php?mid=' . $m['mid'] . '>Approve</a><br>';
}
Then finally to clean up afterwards, after you have used your mail() function you should delete the line from the database that you have sent.
Here is the code (including the $_GET variable, this is an unsafe method but is sufficient to display the code you would be using).
mail(); //data can be added either from a new select statement or from POSTING it with the form
$query = "DELETE FROM mailqueue WHERE mid='" . $_GET['mid'] . "'";
mysql_query($query);
echo 'Your mail has been sent and deleted from the queue';
Hope this helps.
You can add timestamps to another column in the database automatically so that you can verify spam posting with something like:
if($_SERVER['REQUEST_TIME'] > ($oldtimeofpost + 100)){ //time is in seconds
//do something
}
else{
//warning
}