Sending random number to email PHP - php

i am trying to send a random number to an email but unable to this is the code that i have been able to come up with so far
please help if possible
sendmail.php
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}
index.php
<form action = "register.php" method="POST">
<p>Username</p>
<input type="text" name="username" maxlength="40" value='<?php if(isset($username)) echo $username ?>'"><br>
<p>New Password</p>
<input type="password" name="password">
<p>email</p>
<input type="text" name="email" maxlength="40" value='<?php if(isset($email)) echo $email ?>'"> <br><br>
<input type="submit" value="Register"> <br><br>
</form>

In form(index.php)
<form action="sendmail.php" method="post">
<lable>email</lable>>
<input type="text" name="email" maxlength="40">
<br>
<input type="submit" value="Register">
</form>
In sendmail.php
$rand= rand(10, 20)// random number generator
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
$message = "Your Random number is";
$message .= $rand;
$message .= "Thank you-Admin";
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}

You forgot to add semicolon at the end of first line
$rand= mt_rand(100000, 999999)
It should be
$rand= mt_rand(100000, 999999);

I think the hosting service that You're using does not accept sending using mail() functions. Maybe for security reasons to prevent virus-like php scripts to send spams from Your account.
So create admin#domain.com email account and using PHPMailer send Your email:
require __DIR__.'/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.hostname.com';
$mail->SMTPAuth = true;
$mail->Username = 'no-reply#domain.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('admin#domain.com');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
download link and examples here: https://github.com/PHPMailer/PHPMailer

Related

How to send an email to multiple addresses?

How can I send an email to multiple email addresses? Right now this index.php page is being hosted online, and it connects to a send.php page, and I'd like to add another email text field that would be used to also send an email to the address entered in it.
Currently it sends an email to one email address that is entered in the email field in the form.
Index.php
<form id="contactus" method="post" action="send.php">
<input type="name" name="name" class="form-control" placeholder="Name" required>. <br/><br/>
<input type="email" name="email" class="form-control" placeholder="Email" required>. <br/><br/>
<input type="name" name="name2" class="form-control" placeholder="Player 2's Email Address" required><br/><br/>
<textarea name="message" class="form-control" placeholder="What Is Your Question?" required></textarea><br/><br/>
<input type="hidden" name="phone2">
<button type="submit" class="btn btn-success">Send Email</button>
<br><br>
</form>
Send.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); //sanitize data
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
/*added line of code*/
if(empty($name)){
header("location: index.php?nouser");
exit();
}
if(empty($email)){
header("location: index.php?noemail");
exit();
}
if(empty($message)){
header("location: index.php?noemail");
exit();
}
/*if(empty($message)){
header("location: index.php?nomessage");
exit();
}//end validation*/
//added line; 'honeypot'
if(empty($_POST['phone2'])){
//Information that needs to be filled out to be able to send an email through phpmailer
//Will use an SMTP service. SMTP is basically like a mail server to send mail
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 1;
//$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = false;
$mail->Host = 'relay-hosting.secureserver.net';
$mail->Port = "25";
$mail->Username = "#Email_Placeholder";
$mail->Password = "Password";
$mail->SetFrom("#Email_Placeholder");
$mail->setFrom('#Email_Placeholder', 'Greeting');
// Add a recipient : used to also send to name
$mail->addAddress($email);
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('email#gmail.com');
/*$mail->addBCC('bcc#example.com');*/
//Body content
$body = "<p><strong>Hello, </strong>" . $email . " How are you?
<br>
<b> Please Notice: </b><br>
<br> <br> Your message was Delivered: " . $message . ". Hello" . $name2 .
"</p>";
$mail->isHTML(true);
//subject line of email
$mail->Subject = $name;
//for html email
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
//the email gets sent
header("Location: http://www.test-domain.com");
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>
This is pretty simple - if you follow the code, you just need to duplicate some lines.
Duplicate your form field
<input type="email" name="email" class="form-control" placeholder="Email" required>
<input type="email" name="email_2" class="form-control" placeholder="Email" required>
Duplicate your validation
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$email_2 = filter_var($_POST['email_2'], FILTER_SANITIZE_STRING);
Duplicate the 'Add Address'
$mail->addAddress($email);
$mail->addAddress($email_2);
Fore readability sake in the code use an array and implode it to a comma separated string:-
$recipients = array(
"youremailaddress#yourdomain.com",
// more emails
);
$email_to = implode(',', $recipients); // your email address
$email_subject = "Contact Form Message"; // email subject line
$thankyou = "thankyou.htm"; // thank you page

phpmailer not sending variables

I am trying to use phpmailer to send a user's input from an html form
Form is like this
<form action="senditpm.php" role="form">
<input type="text" class="form-control" id="name" name="name"><br>
<input type="email" class="form-control" id="email" name="email">>br>
<input type="text" class="form-control" id="phone" name="phone">>br>
<input type="submit" value="Submit" class="submit-button btn btn-default">
</form>
senditpm.php is like this
<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email= $_POST['email'] ;
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'xxxxxxxxx';
$mail->SMTPAuth = false;
$mail->Username = 'xxxxxxxx';
$mail->Password = 'xxxxxxxx';
$mail->Port = 25;
$mail->setFrom('xxx#xxxxs.co.uk', 'xxxxx');
$mail->addAddress('xxx#xxx', 'xxx xxxx');
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body="
Name: $name <br>
Email: $email <br>
Phone: $phone <br>";
;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
When I complete the form and click Submit, I receive an email like this
Name:
Email:
Phone:
As you can see, the php isn't sending the variables
Please could someone let me know where I am going wrong. Thanks in advance
<form> defaults to a GET method if a POST method is not implied and you are using POST arrays.
So change
<form action="senditpm.php" role="form">
to
<form action="senditpm.php" role="form" method="post">

phpmailer add more contents to body of email

I am brand new to phpmailer.. i have made some progress by creating a simple form that allows users to send emails to our inbox:
<form id="contact-form" class="contact-form" method="post" action="send-mail.php">
<input type="text" name="name" id="name" placeholder="Name" tabindex="1">
<input type="text" name="subject" id="trade" placeholder="Your Trade" tabindex="3">
<input type="text" name="email" id="email" placeholder="Your Email" tabindex="2">
<input type="text" name="number" id="number" placeholder="Contact Number" tabindex="4">
<textarea id="message" rows="8" name="message" placeholder="Message" tabindex="5"></textarea>
<div class="grid-col one-whole">
<button type="submit">Send Your Message</button>
</div>
</form>
.php:
<?php
require('PHPFiles/PHPMailerAutoload.php');
require('PHPFiles/class.smtp.php');
require('PHPFiles/class.phpmailer.php');
$mail = new PHPMailer;
//$mail->SMTPDebug = 3;
$mail->IsSMTP();
$mail->Host = '74.208.5.2';
$mail->SMTPAuth = true;
$mail->Username = 'info#mydomain.com';
$mail->Password = '*******';
$mail->SMTPSecure = 'tls';
$mail->Port = 25; connect to
$mail->From = isset($_POST["email"]) ? $_POST["email"] : "";
$mail->FromName = isset($_POST["email"]) ? $_POST["email"] : "";
$mail->addAddress('info#mydomain.com');
$mail->Subject = isset($_POST["subject"]) ? $_POST["subject"] : "";
$mail->Body = str_replace("\n",'<br>', $_POST['message']);
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->isHTML(true);
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
At the moment, the Body of the email contains the contents of the textare field. How can the body contain this, but then also a line break, then, the contents of the number field?
You might want to try this. Make a separate variable for all the data that needs to be in the body of the message.
$message = "Name :- " . $_POST['name'] . "<br>" . " Number :- " . $_POST['number'];
$mail->Body = $message;
so doing it like:
$mail->Body = str_replace('\n','<br />', $_POST['message']);
or:
$mail->Body = str_replace("\\n","<br />", $_POST["message"]);
should fix the problem of string getting the "line breaks".
btw. it`s always good to:
var_dump($data);
die();
to see what are you getting at each step of a code

phpmailer secure approach by placing credentials out of the web root in INI file

first of all thank you for your time and helping me on this.
I have a simple contact form and i'm using phpmailer.
I want to store credentials in an INI file out of webroot and then include it in my mail.php file which is the mail sending script.
How to write the INI content and how to call them on mail.php file?
This is my HTML file which is contact us form:
<h3><font style="line-height:170%" size="4"> <a id="contactus">Contact us form</a> </font></h3>
<form method="post" action="email.php" accept-charset="UTF-8">
<p>
<label>your name</label>
<input name="dname" type="text" size="30" />
<label>your email</label>
<input name="demail" type="text" size="30" />
<label>your domain name</label>
<input name="ddomain" type="text" size="30" />
<label>Message</label>
<textarea name="dmessage" id="dmessage" rows="5" cols="5"></textarea>
<br />
<input class="button" type="submit" value="submit"/>
</p>
</form>
<br />
and this is the email.php file:
<?php
header('Content-type: text/plain; charset=utf-8');
$email = $_REQUEST['demail'] ;
$message = $_REQUEST['dmessage'] ;
$ddomain = $_REQUEST['ddomain'] ;
require("PHPMailer_v5.1/class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = "info#example.com"; // SMTP username
$mail->Password = "this is the password"; // SMTP password
$mail->From = $email;
$mail->AddAddress("info#example.com");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $ddomain;
$mail->Body = $message;
$mail->AltBody = $ddomain;
if(!$mail->Send())
{
echo "Error <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "we have received your email";
?>
I want to store credentials in a safe place.
Another problem is that whenever someone open email.php file in browser ( example.com/email.php) an empty email will be sent to me, how to prevent it?
I want the email.php file to be executed only a result of a customer's contact via filling the form and not by directly opening the email.php file
Thank you all
<?php
if (empty($_REQUEST['demail']) || empty($_REQUEST['dmessage'])) {
die();
}
$constants = parse_ini_file("/outside/web/sample.ini");
header('Content-type: text/plain; charset=utf-8');
$email = $_REQUEST['demail'] ;
$message = $_REQUEST['dmessage'] ;
$ddomain = $_REQUEST['ddomain'] ;
require("PHPMailer_v5.1/class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->Host = "localhost";
$mail->SMTPAuth = true;
$mail->Username = $constants['username']; // SMTP username
$mail->Password = $constants['password']; // SMTP password
$mail->From = $email;
$mail->AddAddress("info#example.com");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $ddomain;
$mail->Body = $message;
$mail->AltBody = $ddomain;
if(!$mail->Send())
{
echo "Error <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "we have received your email";
?>
INI file (sample.ini) looks like:
username = "info#example.com"
password = "PASSW0RD"
Thank you for your helps.
I did some change on your code and it is excatly what is want.
instead of saying:
if (empty($_REQUEST['demail']) || empty($_REQUEST['dmessage'])) {
die();
}
i used this one:
if (empty($_REQUEST['demail']) || empty($_REQUEST['dmessage'])) {
echo "Please fill-in Email and Message sections completely!";
exit;
}
Thank you for your help

Mail send function not getting called from .php Customer Form

I am new to PHP coding. I have created a Customer form, followed by send e-mail function. When a Customer submits data (including E-Mail and password) he should receive a confirmation e-mail with User ID (same as entered E-Mail Id) and entered Password.
At this moment, with my current code, when a Customer submits the form, database gets updated, but no e-mail is send to the user. Can anyone point out what needs to be changed to ensure that send e-mail function works correctly.
<!DOCTYPE html>
<html>
<head>
<title>Registration Desk</title>
</head>
<body>
<div class="form">
<form id="contactform" action="reg_submit.php" method="post">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="First and last name" required="" tabindex="1" type="text">
<p class="contact"><label for="add">Address</label></p>
<textarea id="add" name="add" style="width:85%; height:60%; margin-top:1%" required=""></textarea>
<fieldset>
<label>Birthday</label>
<input type="date" name="dob" value="yyyy-mm-dd" required="">
</fieldset>
<label>I am</label> <br><br>
<input type="radio" name="sex" value="male" >Male
<input type="radio" name="sex" value="female">Female
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" class="field" placeholder="Please enter a valid emailid" required="" type="email">
<p class="contact"><label for="password">Create a password</label></p>
<input type="password" id="password" name="password" required="">
<p class="contact"><label for="repassword">Confirm your password</label></p>
<input type="password" id="repassword" name="repassword" required="">
<br><br>
<p class="contact"><label for="phone">Mobile phone</label></p>
<input id="phone" name="phone" placeholder="phone number" required="" type="text"> <br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Sign me up!" type="submit">
</form>
</div>
</div>
</body>
</html>
<?php
error_reporting( 0);
$connect=mysqli_connect("localhost","wbtecqoj_saltee","webuildtec1","wbtecqoj_salteegroup");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if( $_POST["password"]!= $_POST["repassword"])
{
?>
<script type="text/javascript">
alert("password miss matched!!!.");
history.back();
</script>
<?php
}
if($_POST["name"] && $_POST["add"] && $_POST["phone"] && $_POST["email"] && $_POST["password"] && $_POST["dob"] )
{
$insert="INSERT INTO `db`.`new_user` (`id`, `name`, `add`, `contact`, `email`, `pass`, `dob`, `gender`,`code`) VALUES (NULL, '$_POST[name]', '$_POST[add]', '$_POST[phone]', '$_POST[email]', '$_POST[password]', '$_POST[dob]', '$_POST[sex]', 'SAL1000000')";
if(!mysqli_query($connect,$insert))
{
echo die('Error: ' . mysqli_error($connect));
}
else
{
$to=$_POST['email'];
$from= "admin#wbtec.in";
$subject="Welcome to xyz Group";
$message="Welcome " . $_POST['name'] . "Dear Customer,
Your Card Number is " .$Ccode.$cookieId. " User id -" . $_POST['email'] . "Your Password -" . $_POST['password'].
"Thanking You,
Customer Care,";
$header = "From" .$from;
if(isset($_POST['btnSend']))
{
$res = mail($to,$subject,$message,$header);
if($res)
{
echo 'Message send';
}
else
{
echo 'msg not send';
}
}
}}
mysqli_close($connect);
?>
Remove the
if(isset($_POST['btnSend']))
{
}
You are checking for
if(isset($_POST['btnSend']))
But your form doesn't contain an input named btnSend, you should be able to remove that if statement altogether
I suggest you to use PHPMailer from
http://sourceforge.net/projects/phpmailer/
With the PHPMailer class you can specify the outgoing SMTP server and authenticate with it properly. Here is an example how I used it:
<?php
require("class.phpmailer.php");
class Mailer
{
function send($email, $subject, $body, $attachment1)
{
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "mail.xyz.com"; // your SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "authname"; // SMTP username
$mail->Password = "authpassword"; // SMTP password
$mail->From = "info#xyz.com";
$mail->FromName = "info#xyz.com";
$mail->AddAddress($email);
$mail->WordWrap = 50; // set word wrap
if ($attachment1 != "") {
$mail->AddAttachment($attachment1); // attachment1
}
$mail->IsHTML(false); // send as HTML
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->Send())
{
return -1;
}
else
{
return 0;
}
}
}
?>
Hope that helps!
u have to download php mailer library which have to files
PHP mailer
class.phpmailer.php and other class.smtp.php then add this file at same directory which have php code which is shown below..
<?PHP
require_once('class.phpmailer.php');
if('POST' == $_SERVER['REQUEST_METHOD']) {
// process the form here
$subject = "This is subject testing1";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->IsHTML(true); // send as HTML
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port
//$mail->Username = "gmailusername"; // GMAIL username
//$mail->Password = "password"; // GMAIL password
$mail->From = 'email id';
$mail->FromName = "FrontName";
$mail->Subject = $subject;
$mail->Body = "this is html body"; //HTML Body
$emailId='email id';
$emails = explode(",",$emailId);
foreach($emails as $email)
$mail->AddAddress($email);
if($mail->Send()){
echo "Message sent successfully";
}else{
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
<form action="" method="post">
<input type="submit" name='button1'value="sent mail" />
</form>

Categories