PHP mail() form doesn't complete sending e-mail - php

<?php
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
define("TITLE", "Contact Us | MicroUrb");
include('includes/header.php');
/*
NOTE:
In the form in contact.php, the name text field has the name "name".
If the user submits the form, the $_POST['name'] variable will be automatically created and will contain the text they typed into the field. The $_POST['email'] variable will contain whatever they typed into the email field.
PHP used in this script:
pre_match()
- Perform a regular expression match
- http://ca2.php.net/preg_match
$_POST
- An associative array of variables passed to the current script via the HTTP POST method.
- http://www.php.net/manual/en/reserved.variables.post.php
trim()
- Strip whitespace (or other characters) from the beginning and end of a string
- http://www.php.net/manual/en/function.trim.php
exit
- output a message and terminate the current script
- http://www.php.net/manual/en/function.exit.php
die()
- Equivalent to exit
- http://ca1.php.net/manual/en/function.die.php
wordwrap()
- Wraps a string to a given number of characters
- http://ca1.php.net/manual/en/function.wordwrap.php
mail()
- Send mail
- http://ca1.php.net/manual/en/function.mail.php
*/
?>
<div id="contact">
<hr>
<h1 class="contact">Get in touch with us!</h1>
<?php
// Check for header injections
function has_header_injection($str) {
return preg_match("/[\r\n]/", $str);
}
if (isset($_POST['contact_submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$msg = $_POST['message'];
// Check to see if $name or $email have header injections
if (has_header_injection($name) || has_header_injection($email)) {
die(); // If true, kill the script
}
if (!$name || !$email || !$msg) {
echo '<h4 class="error">All fields required.</h4>Go back and try again';
exit;
}
// Add the recipient email to a variable
$to = "renaissance.scholar2012#gmail.com";
// Create a subject
$subject = "$name sent you a message via your contact form";
// Construct message
$message = "Name: $name\r\n";
$message .= "Email: $email\r\n";
$message .= "Message:\r\n$msg";
// If the subscribed checkbox was checked
if (isset($_POST['subscribe']) && $_POST['subscribe'] == 'Subscribe') {
// Add a new line to message variable
$message .= "\r\n\r\nPlease add $email to the mailing list.\r\n";
}
$message = wordwrap($message, 72);
// Set mail headers into a variable
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email> \r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
// Send the email
mail($to, $subject, $message, $headers);
?>
<!-- Show success message afte email has been sent -->
<h5>Thanks for contacting MicroUrb!</h5>
<p>Please allow 24 hours for a response.</p>
<p>« Go to Home Page</p>
<?php } else { ?>
<form method="post" action="" id="contact-form">
<label for="name">Your name</label>
<input type="text" id="name" name="name">
<label for="email">Your email</label>
<input type="email" id="email" name="email">
<label for="message">and your message</label>
<textarea id="message" name="message"></textarea>
<input type="checkbox" id="subscribe" name="name" value="Subscribe">
<label for="">Subscribe to newsletter</label>
<input type="submit" class="button next" name="contact_submit" value="Send Message">
</form>
<?php } ?>
<hr>
</div>
<?php include('includes/footer.php'); ?>
I've tried creating a simple mail form. The form itself is on my contact.php page. I would like to test that the code submits perfectly and sends the email.
I knew that there would be a chance that via MAMP or MAMP Pro the sending of the email would not work, but I have found documentation that says you can make it work. I followed this documentation:
https://gist.github.com/zulhfreelancer/4663d11e413c76c6393fc135f72a52ce
and it did not work for me. I have tried reaching out to the author to no avail.
This is what I have tried to do thus far:
I have made sure error reporting is enabled and set to report all errors and I have that code in my index.php file here:
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
define("TITLE", "Home | MicroUrb");
include('includes/header.php');
?>
<div id="philosophy">
<hr>
<h1>MicroUrb's Philosophy</h1>
<p>Here at MicroUrb we guarantee you organically grown produce, because we grew it ourselves and we are local. We're not pompous, we're proud. We're proud of our work, our quality, our environment and our love for fresh local produce and family.</p>
<p>Thank you, from your local urban family farm.</p>
<hr>
</div><!-- philosophy -->
<?php
include('includes/footer.php');
?>
If you look at my code in contact.php, you will see that the mail() function is being called.
I checked MAMP Pro logs and for Postfix I had nothing because Postfix appears to not be running (could this be the problem?) For the Apache logs I had this error:
unknown: warning: /etc/postfix/main.cf, line 696: overriding earlier entry: inet_protocols=all
sendmail: warning: /etc/postfix/main.cf, line 676: overriding earlier entry: inet_protocols=ipv4
sendmail: warning: /etc/postfix/main.cf, line 696: overriding earlier entry: inet_protocols=all
postdrop: warning: /etc/postfix/main.cf, line 696: overriding earlier entry: inet_protocols=all
but which was caused by following Step 2 of the link I shared above, where it directed me to add this:
myorigin = live.com
myhostname = smtp.live.com
relayhost = smtp.live.com:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
inet_protocols = ipv4
smtp_use_tls = yes
smtp_tls_security_level=encrypt
tls_random_source=dev:/dev/urandom
Line eight above was conflicting with inet_protocols = all, so I deleted line 8 above and the problem went away, but the original problem of not being able to send mail is still there.
I am not using an error suppression operator.
I may need to check to see if mail() returns true or false.
I checked spam folders of the email accounts I tried sending mail to.
I believe I have supplied all mail headers:
// Set mail headers into a variable
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email> \r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n";
I believe the recipient value is correct:
// Send the email
mail($to, $subject, $message, $headers);
I tried multiple email accounts, same issue.
I believe the form method matches the code.
Is Postfix on my MAMP Pro not working the problem?
I enabled PHP custom mail.log.
Should I just call it quits and use a different mailer or different way of developing my contact form in PHP that will be less of a headache?
So I believe my question is not a duplicate of the other posting in question is because as outline above, I have gone through the troubleshooting steps of that very SO posting and it has not solved my problem.
I can only guess my problem is either more specific to getting Postfix working on my MAMP Pro. I am not checking if mail() returns true or false correctly or I just may need to go with PHPMailer or some alternative.

Related

Heredoc not displaying html correctly

I'm still green to PHP and I have built a simple mail() form using php. I have done my best to tidy the code and use the syntaxes and methods as supplied here.
However, I'm still running into some issues, with EOD. I have coded my EOD to send a few basic lines of html, <br/> <hr/> <b/> <em/> etc.. My issue is that the HTML is not being recognised by mail clients such as mac mail, outlook, etc.
I have tried simply using $body = '<html></html>'; and declaring the headers as per the documentation on php. But I am still having the same issue. I have included my basic mail function below; It may be that it's a syntax error of somekind or im missing something else entirely. However, after a day or two of troubleshooting I can't seem to isolate the problem.
Any help would be greatly appreciated.
// mail body.
$body = <<<EOD
<h2>Booking Request / $date</h2>
<hr/><br/>
Last Name: $lnameField<br/>
First Name: $fnameField<br/>
Company: $comField<br/>
Title: $ttlField<br/>
Email: $emaField<br/>
Acitivity: $actSelect<br/>
<br/>
<h2>Contact Info</h2>
<hr><br/>
Add Line 1: $add1Field<br/>
Add Line 2: $add2Field<br/>
Country: $couField<br/>
Telephone: $telField<br/>
<br/>
Requested Booking day: $daySelect<br/>
Requested Booking Time: $selectedTime<br/>
<br/>
Interested in: $selectedProjects.<br/>
Comments: $comms<br/>
submitted: <b>$date</b> at <b>$time</b>.
EOD;
// form submission check.
if (isset($_POST['btn-sub'])) {
// subject & account.
$emailSub = 'Drupa 2016 - Booking Form Actioned';
$emailAcc = 'MGI Technology (SHCP) <testing#test.co.uk>';
// confirmation details.
$confSub = 'Confirmation of booking';
$conf_sender = 'MGI Technology (SHCP) <no-reply#test.co.uk>';
// mail headers
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/html; charset=iso-8859-1";
$headers[] = "From: $conf_sender";
$headers[] = "X-Mailer: PHP/".phpversion();
// mail info
$success = mail($emailAcc, $emailSub, $body, implode("\r\n", $headers));
$confirm = mail($_POST['ema'], $confSub, $body, implode("\r\n", $headers));
}
// redirect & exit.
header('Location: prox.php');
exit();

Issues developing companion php for natural language form

Forgive me, I am new at this and the different php I have tried hasn't really worked at all. I've found examples for Natural Language forms, but none with working PHP and I'm familiar with PHP when used with traditional forms, but I'm having problems putting the two together.
The general form layout goes like this:
My name is [your name].
Today, I am [whatchya gonna do?].
I'm doing this because [c'mon,why?].
It's important that I [what you said you'd do] because [the big picture].
Shoot me an email with my awesome new declaration at [your email]
Button 1 (sends email)
Button 2 (copies all text and input fields to clipboard -- not as important right now)
Button 1, I want to send a copy to myself with a hard coded email address and also send a copy to the user with the email address they've entered.
This is a little messy right now, as I am simply trying to get it to work... again, I have no included PHP because at this point -- I've confused myself so much that I don't know what to include.
<form method="post" action="todayiam.php">
<div class="naturallanguageform">
<div class="nlfinner">
<p class="line">
<span class="copy">My name is </span>
<span class="inputcontainer"><input class="textinput" name="name" value="" placeholder="[your name]">.</span>
<span class="copy">Today, I am </span>
<span class="inputcontainer"><input class="textinput" name="todayiam" value="" placeholder="[whatchya gonna do?]">.</span>
<span class="copy">I'm doing this because </span>
<span class="inputcontainer"><input class="textinput" name="why" value="" placeholder="[c'mon, why?]">.</span>
<span class="copy"> It's important that I </span>
<span class="inputcontainer"><input class="textinput" name="whatusaid" value="" placeholder="[what you said you'd do]"></span>
<span class="copy"> because </span>
<span class="inputcontainer"><input class="textinput" name="because" value="" placeholder="[the big picture]">.</span>
</p>
<span class="copy">Shoot me an email with my awesome new declaration at</span>
<span class="inputcontainer"><input class="textinput" name="email" value="" placeholder="[your email]"></span>
<p class="line">
<button class="button">Send to E-mail</button>
</p>
<p class="line">
<button class="button">Copy to post in comments</button>
</p>
</div>
</div>
</form>
Any assistance will be greatly appreciated.
Update:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
Another update
I have changed $headers = "From: $email\r\n"; to $headers = "From: email#gmail.com" . "\r\n" ; to set a static from address (my support email) and the email is still identifying as from CGI Mailer. I have verified that it's not a caching issue and the correct files are being used.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: email#gmail.com" . "\r\n" ;
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was successfully sent! Do something here
}
}
?>
Before you posted your answer, I was working on this script:
<?php
// from the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['todayiam']);
// set here
$subject = "Contact form submitted!";
$to = 'email#gmail.com';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: index.html');
?>
The $email = trim(strip_tags($_POST['email'])); field was pulling the user's email and using it for the sent from as noted in the $header... so it was working fine. With the new script, that you posted, I can't get it to work with my hard coded email OR the user's email as the FROM. Initially, I really wanted to understand what the differences were between the script, why one worked and the other didn't, but now... I'd really just like my email to be hard coded as the FROM. I'll worry about the differences later. As I said before, I really have tried to get this to work in many different forms... I am sure it's something simple that I am over looking as a novice to PHP. Thanks.
Right, so after a bit of discussion from comments, I decided to post an answer instead, giving a bit more detail where it's more readable.
Your PHP code is missing the combination of all fields into $message. This can easily be done, as you can put a variable inside a string in PHP. I'll show you how. I'm also going to show you how you can avoid undefined indexes.
<?php
if (isset($_POST['name'], $_POST['todayiam'], $_POST['why'], $_POST['whatusaid'], $_POST['because'], $_POST['email']) {
// We enter this statement only if all the fields has been properly defined, this to avoid getting undefined index
$name = $_POST['name'];
$todayIam = $_POST['todayiam'];
$why = $_POST['why'];
$whatYouSaid = $_POST['whatusaid'];
$because = $_POST['because'];
$email = $_POST['email'];
// We define the variables for using in mail()
$to = 'email#gmail.com';
$to .= ', '.$email; // You wanted them to recieve a copy
$subject = "Contact form submitted!";
// You can put a lot more headers, check out the mail() documentation
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Compose a $message from all the variables
$message = "My name is $name. ";
$message .= "Today, I am $todayIam.";
$message .= "I'm doing this because $why.";
$message .= "It's important that I $whatYouSaid";
$message .= "because $because.";
if (mail($to, $subject, $message, $header)) {
// Mail was sucsessfullly sent! Do something here
}
}
?>

Email code not working

I'm not sure what happen to my email code as i'm comparing with all the code i able to find online ... when i using localhost, it's work no problem.. and it having the txt file appear in mailoutput folder in xampp.
but when i request my friend to help host to web service.. it cannot work anymore for the code :(
below is my code. (modified from online source)
$subject = "Thanks for Registering." ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From : email' . "\r\n";
$message = "<html><body>
<p> Thank you to register with Lecture Public Room Book Portal </p>
<p> </p>
<p> In order to activate your account please click the link below:</p>
<p> <a href='link'>Verify Account</a> </p>
<p></p>
<p>Or you may go to the verification page using below link and paste in the verification code. Your verification code is $ver_code.</p>
<p> <a href='link'> Verify page </a> </p>
<p> </p>
<p> Please do not reply to this email has the mailbox isn't monitored.</p>
<p> </p>
<p> </p>
<p><center> - The Webmaster () - </center> </p>
</body></html>";
if(mail($email, $subject, $message, $headers))
{
$_SESSION['type'] = "User";
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Successful register. Please check your email for activate account.')
window.location.href='index.php?user=$username#verify-slide';
</SCRIPT>");
exit();
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Please try again.')
window.location.href='index.php?signup-slide';
</SCRIPT>");
exit();
}
wish someone could please help me :(
Maybe your hoster restricted access to php mail function. Email him about it. If so you can use Mandrill app.
Please check your error log if it returns some errors.
$headers .= 'From : email' . "\r\n";
Put your email in the email field ( preferably from the same domain email address )
A few bullet points (Assuming that mail() returns true and there are no errors in the error log) :
Does the sender address ("From") belong to a domain on your server? If not, make it so.
Is your server on a blacklist (e.g. check IP on spamhaus.org)? This is a remote possibility with shared hosting.
Are mails filtered by a spam filter? Open an account with a freemailer that has a spam folder and find out. Also, try sending mail to an address without a spam filter.
Do you possibly need the fifth parameter "-f" of mail() to add a sender address? (See mail() command in the PHP manual)
If you have access to log files, check those, of course, as suggested above.
Do you check the "from:" address for possible bounce mails ("Returned to sender")? You can also set up a separate "errors-to" address.
from here
In your current page email recipient is not set like this:
$subject = "Thanks for Registering." ;
$from = "admin#abc.com";
$email = "someone#gmail.com";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From :' . $from. "\r\n";

send email with php in a local host

I want to send email with php using xampp.
<html>
<head>
</head>
<body>
<?php
error_reporting(E_ALL ^ E_NOTICE);
$to = $_POST['email_add'];
//define the subject of the email
$subject = $_POST['sbjct'];
//define the message to be sent. Each line should be separated with \n
$message = $_POST['msg'];
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
$mail_sent = #mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
<form action="send_email.php" method="post">
Email Add<input type="text" name="email_add" />
Subject<input type="text" name="sbjct" /> <br>
<textarea name="msg" rows="9" cols="20"></textarea><br>
<input type="submit" value="Send"/>
</form>
</body>
</html>
It's not working. Is there something wrong with my code?
I found some tutorials on the cloud, but it mentions SMTP and I do not understand it.
PHP doesn't actually send the email... in Linux it'll forward it to sendmail or similar daemon, in Windows it'll forward it to an SMTP server. Depending on your OS you have to setup these other processes and explain to PHP how/where to contact them (in php.ini in the [mail function] section).
PHP need a SMTP server to send emails.
You can specify it in your php config file (and set it to your ISP one for example), or use "Test Mail Server Tool" ( http://www.toolheap.com/test-mail-server-tool/ ) that catches the smtp local calls and saves them in a directory of your hard disk, so that you can debug everything.
Obviously, this solution works only if you need to debug it.
If your need is to send the mail, please refer to php documentation and use your ISP SMTP server.
If you are using the mail() function on Windows from a local development environment, you may need to specify an SMTP server that can relay the mail for you. Linux has this functionality baked in, Windows may not. Your ISP may provide you with this or a webmail provider may allow you to relay mail through them.
Look inside your php.ini file and locate the [mail] section and fill in:
SMTP = smtp.yourprovider.com
SMTP_PORT = 25
From the PHP mail manpage
"The Windows implementation of mail() differs in many ways from the Unix implementation. First, it doesn't use a local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on a network socket (which can either on the localhost or a remote machine)."
I think you're looking for http://www.php.net/manual/en/function.mail.php ?
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Email Add<input type="text" name="email_add" />
Subject<input type="text" name="sbjct" /> <br>
<textarea name="msg" rows="9" cols="20"></textarea><br>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
<?php
If(isset('submit'))
{
error_reporting(E_ALL);
$to = $_POST['email_add'];
//define the subject of the email
$subject = $_POST['sbjct'];
//define the message to be sent. Each line should be separated with \n
$message = $_POST['msg'];
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
$mail_sent = mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
}
?>
Here is a script I re-use in a lot of my projects, pretty straight forward just copy in and change the obvious values.
$email_to = "myemail#gmail.com,anotheremail#gmail.com";
$email_subject = "This is the subject line";
$break = 'echo "/n"';
$form_email = "no-reply#myemail.com";
//Function to convert /n to line breaks in HTML
function nl2br2($email_message) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $email_message;
}
//Unformatted email body
$email_message = "This is the main blody of the email";
//Format string against function
nl2br2($email_message);
// create email headers
$headers = 'From: '.$form_email."\r\n".
'Reply-To: '.$form_email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);

PHP mail function not working

I have a php script that sends an email. It looks like this:
<?php
// subject
$subject = "$first_name $last_name has sent you a message on The Red-line";
// message
$message = "<html>
<head>
<title>
The Red-line
</title>
</head>
<body>
<p>
Hi $war_first,
</p> <br />
<p>
$first_name $last_name has sent you a message on the Red-line. To view your message, please login to <a href='www.thered-line.com'>the Red-line.</a>
</p> <br />
<p>
Sincerely,
</p> <br />
<p>
The Red-line Operator
</p>
</body>
</html>";
// 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";
// Additional headers
$headers .= "From: The Red-line messages#theredline.com \r\n";
$headers .= "To: $war_first $last_war <$war_mail>\r\n";
// Mail it
mail($war_mail, $subject, $message, $headers);
?>
When I was testing this out on the remote server, I used this script to send an email to my inbox at turbocapitalist1987#yahoo.com. I got the email but the "from" part doesn't work . Yahoo says that my email was sent from "the#yahoo.com"
Does anybody have a clue as to why this isn't working?
Thanks
For your From header, enclose the actual address with < >:
$headers .= "From: The Red-line <messages#theredline.com> \r\n";
This is the correct format to use when you have both a display name and an email address. I'm guessing Yahoo was interpreting the first word "The" as the entire email address, and provided a default (yahoo.com) for the domain.
The <> seems to be your problem, it should be:
$headers .= "From: The Red-line <messages#theredline.com> \r\n";
Secondly, on Unix/Linux, you must have a working MTA (i.e.: sendmail, postfix, etc.) configured on your server, either to relay mail directly, or through a Smart Host. If you're on Windows, you must have a SMTP server configured in php.ini.
I would recommend using pre-built PHP email library such as: http://swiftmailer.org/

Categories