Changing form php sendmail to SMTP? - php

We created this contact form a long time ago, but we have recently had issues with our sendmail, now i need to change this to use SMTP and that i haven't done before. Is it much work or just a matter of changing few lines? Any tips are welcome.
You can see our whole script here, it's very simple...
<?php
if(!$_POST) exit;
function tommus_email_validate($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email);
}
$name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $comments = $_POST['comments'];
if(trim($name) == '') {
exit('<div class="error_message">You must enter your name.</div>');
} else if(trim($name) == 'Name') {
exit('<div class="error_message">You must enter your name.</div>');
} else if(trim($email) == '') {
exit('<div class="error_message">Please enter a valid email address.</div>');
} else if(!tommus_email_validate($email)) {
exit('<div class="error_message">You have entered an invalid e-mail address.</div>');
} else if(trim($comments) == 'Tell us what you think!') {
exit('<div class="error_message">Please enter your message.</div>');
} else if(trim($comments) == '') {
exit('<div class="error_message">Please enter your message.</div>');
} else if( strpos($comments, 'href') !== false ) {
exit('<div class="error_message">Please leave links as plain text.</div>');
} else if( strpos($comments, '[url') !== false ) {
exit('<div class="error_message">Please leave links as plain text.</div>');
} if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$address = 'hello#basicagency.com';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$e_body = "You have been contacted by $name from your contact form, their additional message is as follows." . "\r\n" . "\r\n";
$e_content = "\"$comments\"" . "\r\n" . "\r\n";
$e_reply = "You can contact $name via email, $email (or by phone if supplied: $phone)";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}

You can use a package for handling e-mails, such as PHPMailer, just use the included methods to build your message, instead of the $headers variable. Once you have downloaded PHPMailer and have it somewhere accessable by your script, replace this:
$headers = "From: $email" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
if(mail($address, $e_subject, $msg, $headers)) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}
with something like this:
require '/path/to/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
// SMTP server details
$mail->Host = "mail.example.com";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "yourname#example.com";
$mail->Password = "yourpassword";
// message details
$mail->setFrom($email, $email);
$mail->addReplyTo($email, $email);
$mail->addAddress($address, $address);
$mail->Subject = $e_subject;
$mail->Body = $msg;
// send
if($mail->send()) {
echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>";
}
else{
echo 'Mailer Error: ' . $mail->ErrorInfo;
}

Related

PHP code is working, but doesn't show who is the sender. Just showing noreply#example.com

My PHP code for sending email its working good, but there is a problem that doesn't show who is the sender just show noreply#example.com. I hosted my website at ecowebhosting.
<?php
$error = "";
$successMessage = "";
if ($_POST) {
if (!$_POST["email"]) {
$error .= "An email address is required.<br>";
}
if (!$_POST["message"]) {
$error .= "The message field is required.<br>";
}
if (!$_POST["subject"]) {
$error .= "The subject is required.<br>";
}
if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "The email address is invalid.<br>";
}
if ($error != "") {
$error = '<div><p>There were error(s) in your form:</p>' . $error . '</div>';
} else {
$to = "example#gmail.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "MIME-VERSION: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From: ".$_POST['email'] . "\r\n";
$headers = "Reply-To: ".$_POST['email'] . "\r\n";
$headers = "Subject: ".$_POST['subject'] . "\r\n";
$headers = "Message : ".$_POST['message'] . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo $successMessage = '<div>Your message was sent, we\'ll get back to you ASAP!</div>';
} else {
echo $error = '<div><p><strong>Your message couldn\'t be sent - please try again later</div>';
}
}
}
?>

not able to send mail from php

I want to send a email from php mail function. This is my code
<?php
$to = "modiv2301#gmail.com";
$subject = "HTML email";
$message = "
<h1>this is msg</h1>
";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <modiv2301#gmail.com>' . "\r\n";
$success=mail($to,$subject,$message,$headers);
if (!$success) {
$errorMessage = error_get_last()['message'];
print_r($errorMessage);
}else{
echo "Success";
$errorMessage = error_get_last()['message'];
print_r($errorMessage);
}
?>
when i run this code its showing me Success but i am not Receiving any email

Sending two different mails to two different users in php

After successful execution of command I want to send two different mails to two different person through if else function in PHP. I am able to send a mail using below code. How to send another mail with different headers & contents.
// if new reservation has been successfully added to reservation table
// send notification to admin via email
if($result){
$to = $email;
$subject = $reservation_subject;
$message .= $reservation_message."\r\n\n";
$message .= "Customer name:" .$provinsi."\r\n";
$message .= "Special Request :" .$comment."\r\n";
$from = $admin_email;
$headers = "From:" . $from."\r\n".
mail($to,$subject,$message,$headers);
echo "OK";
}else{
echo "Failed";
}
This is all you need to do, just set the new reciever and sender and message and call mail() again
Mail is much like any PHP function, you set up its parameters and call it.
if($result){
$to = $email;
$subject = $reservation_subject;
$message .= $reservation_message."\r\n\n";
$message .= "Customer name:" .$provinsi."\r\n";
$message .= "Special Request :" .$comment."\r\n";
$from = $admin_email;
$headers = "From:" . $from."\r\n".
if ( mail($to,$subject,$message,$headers) ) {
echo "OK message 1 sent";
} else {
echo "FAILED message 1 sent";
}
$to = $email_2;
$subject = $reservation_subject_2;
$message = $reservation_message_2."\r\n\n";
$from = $admin_email_2;
$headers = "From:" . $from."\r\n".
if ( mail($to,$subject,$message,$headers) ) {
echo "OK message 2 sent";
} else {
echo "FAILED message 2 sent";
}
}else{
echo "Failed";
}
Try This code :
function send_mail($to_email,$from_email,$subject,$message){
$nameToBeDisplayed = "XYZ";
$headers = 'From: ' . $nameToBeDisplayed . '<' . $from_email . '>' . "\r\n";
$headers .= 'Reply-To: ' . $from_email . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$message = "";
mail($to_email, $subject, $message, $headers);
}
if($result){
send_mail('to1#gmail.com','from1#gmail.com','your subject','your message');
send_mail('to2#gmail.com','from2#gmail.com','your subject','your message');
}else{
echo "Failed";
}
if($result){
createEmailOne();
createEmailTwo();
}else{
echo "Failed";
}
function createEmailOne(){
$to = $email;
$subject = $reservation_subject;
$message = $reservation_message."\r\n\n";
$message .= "Customer name:" .$provinsi."\r\n";
$message .= "Special Request :" .$comment."\r\n";
$from = $admin_email;
$headers = "From:" . $from."\r\n".
mail($to,$subject,$message,$headers);
echo "OK";
}
function createEmailTwo(){
$to = "john#snow.com";
$subject = $reservation_subject;
$message = "Something went wrong in this form, here is the info: \r\n\n";
$message .= $reservation_message."\r\n\n";
$message .= "Customer name:" .$provinsi."\r\n";
$message .= "Special Request :" .$comment."\r\n";
$from = $admin_email;
$headers = "From:" . $from."\r\n".
mail($to,$subject,$message,$headers);
echo "OK";
}

Sending email only when the filled email and phone number are filled correct

I have the following code in the sendmail.php file.
<?php
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
// Form fields
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
// Email Ssubject
$subject = 'Query from My Domain';
// Compose message to send
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if (filter_var($clientEmail, FILTER_VALIDATE_EMAIL) == false) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if (!preg_match('/^(\+?)+([0-9]{10,})$/', $number)) {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName && $clientEmail && $number && $message != '') {
// Headers
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= "CC: " . 'My Boss <boss#gmail.com>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
// Send mail
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
In this from the email and phone number inputs are validated, and these validation works great. My problem is manipulating this section below so that the form send the email only when the filled email and phone number are correct. If I am not mistaken, what I need to fiddle with in the piece of code below is $clientEmail and $number, I tried many things that didn't work.
if($clientName != '' && $clientEmail && $number && $message != '') {
// Headers
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= "CC: " . 'My Boss <boss#gmail.com>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
// Send mail
mail($emailTo, $subject, $sendMessage, $headers);
}
After all your validation, and before you start to build the headers for the email, do this:
$isValid = empty($array['nameMessage']) && empty($array['emailMessage']) &&
empty($array['numberMessage']) && empty($array['messageMessage']);
$isValid will be true if the form is valid. Now check for it before you send mail:
if($isValid) {
// build headers and send mail
...
mail(...);
// maybe you should echo a success message and exit here
// if there is nothing else to do
}else{
echo json_encode($array); //echo the error messages
}

send email in php with attachment

i have use this code in php mail send with attachment. I am using the Apache http server with wamp.
<?php $to = 'santosh_091020#rediffmail.com';
// Declaring the necessary variables for mail sending :
$subject = 'Testing sendmail.exe';
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$mob = $_REQUEST['mob'] ;
$msg = $_REQUEST['msg'] ;
$message = ' santosh enquire \n\nName: '.$name.' \n Email:'. $email.' \n Mobile:'. $mob.' \n Message: '.$msg.' \n ';
// Declaration of the attributes for attachment.
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
fclose($fp);
$file = chunk_split(base64_encode($file));
$num = md5(time());
// Defining the contents of the header.
$headers = "From: ".$email. "\r\n" . "CC: santosh#creativecrows.com" ;
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
//$headers .= "Message-ID: <".gettimeofday()." TheSystem#".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
//$data = chunk_split(base64_encode($data));
// sending the mail.
if(mail($to, $subject, $message, $headers))
{
echo "Email sent";
send();
}
else
{
echo "Email sending failed";
}
//send mail in client
function send()
{
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$to= trim($email);
$subject = 'thanx';
$message = '<html><head><title>HTML email</title></head>
<body style="background-color:#000099;"><p style="color:#000099;">This email contains HTML Tags!</p><table><tr><th>Firstname</th><th>Lastname</th></tr><tr><td>John</td><td>Doe</td></tr></table></body></html>';$headers1 = 'MIME-Version: 1.0' . "\r\n";
$headers1.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers1.= "From: ".$email;
if(mail($to, $subject, $message,$headers1))
{
echo "Email sent";
}
else
{
echo "Email sending failed";
echo $to;
echo $subject;
echo $message;
}
}
?>
but i got the following error;
Delivery to the following recipient failed permanently:
1.0#localhost
Technical details of permanent failure:
DNS Error: Domain name not found.
please help me. Thnx in advance.
Check this URL,
seems your header info is not absolute
http://webcheatsheet.com/php/send_email_text_html_attachment.php
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup server
$mail->Port = '';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = '';
$mail->FromName = '';
$mail->AddAddress($row['client_email'], ''); // Add a recipient
$mail->AddReplyTo('', 'Information');
$mail->AddCC('cc#example.com');
$mail->AddBCC('bcc#example.com');
$mail->WordWrap = 50;
// Set word wrap to 50 characters
$mail->AddAttachment('kurtacompany/techreporting/upload/"'.$row['file1'].'"'); // Add attachments
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = '';
$mail->Body = '<p>type whatever you want</p>';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';

Categories