Mail send function not getting called from .php Customer Form - php

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>

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

Jquery Ajax, PHPMailer doesn't send emails even if there's no error but works if i use stand alone page with fix values

I have this simple bootstrap form that i run on my localhost, it accepts name email and message and a custom captcha in a form of a math question; On submit i used jquery ajax to fetch the data to emailme.php that contains the phpmailer code.. My problem is, no email was sent even if there's no error and the network status is 200 and i can also see this:
http://localhost/emailme.php?name=myname&email=myemail#gmail.com&message=test
however it works if i just use the phpmailer stand alone code with fixed values. how can i make it work?
HTML:
<form id="emailme" method="post">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="e.g. John Doe">
<span id="err_name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="e.g. example#domain.com">
<span id="err_email" class="text-danger"></span>
</div>
<div class="form-group">
<textarea name="message" id="message" cols="30" rows="10" class="form-control" placeholder="Your message"></textarea>
<span id="err_message" class="text-danger"></span>
</div>
<div class="form-group">
<label for="human">5 + 2 = ?</label>
<input type="text" id="human" name="human" class="form-control" placeholder="Your Answer">
<span id="err_human" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
JQUERY:
$("#emailme").on('submit',function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var human = $("#human").val();
var emailRegex = /(.+)#(.+)\.(com|edu|org|etc)$/g;
if(name!==''&&email!==''&&message!==''&&human!==''){
if(email.match(emailRegex)){
if(human==7){
$.ajax({
url:'emailme.php',
typ:'post',
data:{name:name,email:email,message:message},
success:function(response){
console.log(response);
$("#mail-status").html(response);
$("#emailme")[0].reset();
},
error:function(XMLHttpRequest,textStatus,errorThrown){
console.log(textStatus+errorThrown);
}
});
}
else{
$("#mail-status").html("unable to submit form, you're not human");
}
}
else{
$("#err_email").append("Invalid email format");
}
}
else if(name==''){
$("#err_name").append("Name cannot be empty");
}
else if(email==''){
$("#err_email").append("Email cannot be empty");
}
else if(message==''){
$("#err_message").append("Message cannot be empty");
}
else if(human==''){
$("#err_human").append("Please answer the security question");
}
});
PHP:
<?php
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
// Set the email address submissions will be sent to
$email_address = 'myemail#gmail.com';
// Set the subject line for email messages
$subject = 'Test email from localhost using PHPMailer';
// Check for form submission
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress($email_address, 'myname');
$mail->Subject = $subject;
$mail->Body = 'From:'.$_POST['name'].'(' . $_POST['email'] . ')'.'<p><b>Message</b><br/>' . $_POST['message'] . '</p>';
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
?>

How to send PHP email after posting data to Database

I am currently working on a quote form. After submitting the form, there was an email set to send submitted record back to client as copy. However, as I was using Mandrill for transaction emails, it's no longer free. I don't want to use any paid service and am now looking to send the same email using PHPMailer. I am finding it difficult to understand to call php to send email. Any help? I am open for options. All I want to send email after form submits.
email.js
function finalize_things(data, order_id){
//posting data to the server side page
$.post(window.location.origin+'/post/', data,function(response){
if(response == 'success'){
console.log(response);
send_email(order_id, data.email, data.firstname, data.project_details, data.file_names);
} else {
console.log(response);
alert('order not placed.');}
});
}
function send_email(order_id, email, firstname, project_details, file_names){
var html_message = "message here"
data = {
"key": "xxxxxxxxx",
"message": {
"html": html_message,
"text": "",
"subject": "Your subject",
"from_email": "test#test.com",
"from_name": "Company name",
"to": [{
"email": email,
"name": firstname
}
]},
"async": false
};
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
type: 'POST',
data: data,
success: function(resp){
console.log(resp); }
});
PHPMAILER Code:
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $smtp_server; // Specify main and backup SMTP servers
$mail->Username = $username; // SMTP username
$mail->Password = $password; // SMTP password
$mail->SMTPSecure = "tls"; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom("companyemail#xyz.com", "Company Name");
$mail->addAddress($email, $firstname); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent = "test message";
$mail->Subject = "Your Quote ID";
$mail->Body = $bodyContent;
$mail->AltBody = $bodyContent;
if(!$mail->send()) {
echo "Message could not be sent.";
$error = '<div class="alert alert-danger"><strong>Mailer Error: '. $mail->ErrorInfo.'</strong></div>';
} else {
$error = '<div class="alert alert-success"><strong>Message has been sent</strong></div>';
}
}
So, if you don't want to use external services like gmail... You need to set up your own mail server (postfix, sendmail etc.) Please note, that webservers very often has potfix onboard (httpd + php + mysql + postfix) already.
Has your hosting postfix already? Check this by using standard mail function, php script like :
<?php
$to = 'yourmail#gmail.com';
$subject = 'test subj';
$mail_body = 'test body';
mail($to, $subject, $mail_body);
?>
If it works -- write your own script based on this code or use phpmailer (it has settings for local mail daemon)
PS PHPMailer can send mail via extenal webserver, like gmail https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps (key line here: $mail->isSMTP();) or via local server, such as postfix -- see example here -- key line is $mail->isSendmail();
and your current code snippet is for using EXTERNAL service, not for LOCAL!
Changes in your js this line:
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
to:
$.ajax({url: 'http://yourserver.tld/send_phpmailer.php',
And use something like this in send_phpmailer.php:
<?php
////// Part 1. Set up variables
$key = $_POST['key']; // need for mandrill, you can omit this
$html = $_POST['message']['html'];
$text = $_POST['message']['text'];
$subject = $_POST['message']['subject'];
$from_email = $_POST['message']['from_email'];
$from_name = $_POST['message']['from_name'];
$to_email = $_POST['message']['to']['email'];
$to_name = $_POST['message']['to']['name'];
////// Part 2. Including PHPMailer
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
////// Part 3. Sending letter by PHPMailer
$mail = new PHPMailer;
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "username#gmail.com";
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom( $from_email, $from_name);
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to_email, $to_name);
//Set the subject line
$mail->Subject = $subject;
//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($html);
//Replace the plain text body with one created manually
$mail->AltBody = $text;
//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!";
}
?>
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>
i try this coding in my own way
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>

Sending random number to email 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

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

Categories