I have built a form builder plugin. The last step is to get the emails to send to the site admin, however, I can't seem to figure out how to make this work. Here is my php mail handler:
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
parse_str($_REQUEST['formData'], $formFields);
$html='<html><body>';
foreach ($formFields as $key => $value) {
$html .= '<p><label>' . $key . ' :</label> ' . $value . '</p>';
}
$html .='</body></html>';
$to = get_option('admin_email');
$subject = "Form Submission";
$txt = $html;
$headers = "From: <sam.skirrow#gmail.com>". "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
mail($to,$subject,$txt,$headers);
// if there are no errors process our form, then return a message
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
You can see in my $to variable I have added get_option('admin_email'); however, doing this breaks my form (as opposed to just writing an email address in.
You need to load WordPress to be able to use their get_option function.
Add this to the top of your PHP script:
require_once('../../../wp-load.php');
Related
I am trying to parse some HTML from files into a PHP variable to send across HTML email, but I am struggling. It doesn't output anything at all when loaded. Only the submit button is echoed. What am I doing wrong? I know it's probably a lot, but can someone please advise me on how to get this to work?
I will end up using AJAX for the submit button so the page isn't reloaded, but the content (at the moment) isn't even displaying. It's a lot of code, so I decided to break it up into files to make it easier to read and easier to inject.
<?php
// Setting mail options
$to = $_POST["clientemail"];
$subject = $_POST["subject"];
// Are we debugging?
$debug = true;
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: CodexWorld<"postmaster#intel-web.co.uk">' . "\r\n";
$headers .= 'Cc: b.ravetta#gmail.com' . "\r\n";
$headers .= 'Bcc: admin#intel-web.co.uk' . "\r\n";
// Place all HTML content into one big fucking message.
$head = file_get_contents("head.html");
$body = file_get_contents("body.html");
$footnotes = file_get_contents("footer.html");
if($_POST["packageid"] == 1)
{
$content = file_get_contents("fb.html");
}
if($_POST["packageid"] == 2)
{
$content = file_get_contents("aw.html");
}
if($_POST["packageid"] == 3)
{
$content = file_get_contents("mobi.html");
};
$messagecontent =
echo $head;
echo $body;
echo $content;
echo $footnotes;
;
// Where the message content ends.
echo "<form method='POST' action=''>
<input type='submit' name='sendmail' value='Send Email'>
</form>";
if (isset($_POST['sendmail']))
if(mail($to,$subject,$messagecontent,$headers)):
$successMsg = 'Email has sent successfully.';
else:
$errorMsg = 'Email sending fail.';
endif;
// Debug Shit
if ($debug)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting("E_STRICT")
?>
I'm surprised that you even get a submit button at all. Because
$messagecontent =
echo $head;
echo $body;
echo $content;
echo $footnotes;
;
should actually raise a syntax error for an unexpected T_ECHO.
If you want to concatenate a string, that's how you do it:
$messagecontent = $head . $body . $content . $footnotes;
If you fix that, you will still only get the submit button after submitting the form, because while you will send the mail, you do nothing with your success / error message. You might want to do something like
if (isset($_POST['sendmail'])) {
if(mail($to,$subject,$messagecontent,$headers)) {
$successMsg = 'Email has sent successfully.';
echo $successMsg;
} else {
$errorMsg = 'Email sending fail.';
echo $errorMsg;
}
}
(Note: I also changed the syntax of your if statements to an accepted standard. see http://www.php-fig.org/psr/)
Also, you might want to change the error reporting settings in the php.ini and not in the file. Because if you do have a parse error, you won't see it (because the file can't be parsed and so display_errors won't get set to 1.
So I have created a PHP form for my wordpress site as Contact form 7 is too heavy and slows it down drastically.
But I have the same contact form on multiple 'items' on one page, so the contact form is used more than once on one page. So when the sender clicks submit depending on how many items are on the page the form will send the same amount of emails...
Now contact form 7 doesn't do this when you submit it only sends me one email. So there is a way to do it, I just don't know as I am new to PHP.
Any help would be great. Here is my sending form code but let me know if you need anything else. cheers guys:
// Sending form to admin
if ($error == false) {
// Hook to support plugin Contact Form DB
//do_action( 'name_before_send_mail', $form_data );
$to = $name_atts['email_to'];
if ($name_atts['hide_subject'] != "true") {
$subject = "(".get_bloginfo('name').") " . $form_data['form_subject'];
} else {
$subject = get_bloginfo('name');
}
$message = $form_data['form_name'] . "\r\n\r\n" . $form_data['form_email'] . "\r\n\r\n" . $form_data['form_message'] . "\r\n\r\n" . sprintf( esc_attr__( 'IP: %s' ), name_get_the_ip() );
$headers = "Content-Type: text/plain; charset=UTF-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: 8bit" . "\r\n";
$headers .= "From: ".$form_data['form_name']." <".$form_data['form_email'].">" . "\r\n";
$headers .= "Reply-To: <".$form_data['form_email'].">" . "\r\n";
if(wp_mail($to, $subject, $message, $headers) == true) {
$result = $name_atts['message_success'];
$sent = true;
} else {
$result = $name_atts['message_error'];
$fail = true;
}
}
There's the hook wpcf7_before_send_mail that you can use to check for posted datas and then send need mails.
I am creating a form builder plugin for wordpress. Within the plugin settings, the user can set the recipient email address - the code for this is in file class-form-builder.php.
I have a file called class-send-form.php that is a php mail handler. I am trying to add the email address that is entered by the user to this file but returning an error.
In class-form-builder.php I have the following code:
class Layers_Form_Builder_Widget extends Layers_Widget {
...
function send_to_email() {
return 'sam#skizzar.com';
}
...
}
At the minute I am using a hardcoded email address to try and get that working before I grab the value inputted by the user.
Then in class-send-form.php I have the following code:
require_once('../../../../wp-load.php');
$layers_email_address = Layers_Form_Builder_Widget::send_email_to();
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
parse_str($_REQUEST['formData'], $formFields);
$html='<html><body>';
foreach ($formFields as $key => $value) {
$html .= '<p><label>' . $key . ' :</label> ' . $value . '</p>';
}
$html .='</body></html>';
$to = $layers_email_address;
$subject = "Form Submission";
$txt = $html;
$headers = "From: <".$to.">". "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
mail($to,$subject,$txt,$headers);
// if there are no errors process our form, then return a message
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
However, when I click send, I just get an error ("there was an error when submitting your form").
How can I get the value of the email address from class-form-builder.php and use it in class-send-form.php?
The function name used in class-send-form.php is send_email_to() and the function name defined in class-form-builder.php is send_to_email().
I think once you fix that, it will work.
I have a PHP form for my event page. Right now it works perfectly to email to myself, and I can CC it to whomever I like without problems. HOWEVER, I'd like to ONLY send it to a specific person if a certain event is selected from a drop box on my form, and CC it to me. This way the organization that is holding the event can receive a copy of the completed form. I would like to also send a customized message to the person it's being sent to if possible. So for example:
If the person filling out the form selects the event, "Heart Walk," then the form results should be sent to "Bob" at "bob#email.com" with a message saying, "Hi Bob, you have received a new volunteer for your Heart Walk event. Below is a copy of the registration."
And of course I get a copy.
Can I do an if/then statement or an array for the $sendtoemail command? And then copy it to me by putting the following:
$headers .= "Cc: me#myemail.com\r\n";
What would be the best way to do this? Thanks for your help! :)
EDIT :
Here is my code:
<?php
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
//send an email from the server TO YOUR EMAIL
$fromname = $_REQUEST['firstname'];
$fromemail = $_REQUEST['email'];
$subject = "NMVN EVENT REGISTRATION";
$message = " <b>EVENT:</b> ".$_REQUEST['pickevent'];
$message .= " <br><br> <b>First Name:</b> ".$_REQUEST['firstname'];
$message .= " <br> <b>Last Name:</b> ".$_REQUEST['lastname'];
$message .= " <br> <b>Cell Phone:</b> ".$_REQUEST['cellphone'];
$message .= " <br> <b>Alternative Phone:</b> ".$_REQUEST['altphone'];
//This is the person who is going to receive the email
$sendtoname = "Mike Gandy";
$sendtoemail = "me#myemail.com";
//Email header stuff
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $fromname <$fromemail>\r\n";
$headers .= "To: $sendtoname <$sendtoemail>\r\n";
$headers .= "Reply-To: $fromname <$fromemail>\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-MSMail-Priority: Normal\r\n";
$headers .= "X-Mailer: Created by Mike Gandy";
//this next line creates and sends the email
mail($sendtoemail, $subject, $message, $headers);
?>
I was thinking about replacing this:
$sendtoname = "Mike Gandy";
$sendtoemail = "me#myemail.com";
With this:
if ($_REQUEST['pickevent'] == 'HeartWalk'))
//if "HeartWalk" is filled out, send to email
{
//send email
$sendtoname = "Bob";
$sendtoemail = "bob#email.com";
}
elseif ($_REQUEST['pickevent'] == 'RaceCure'))
//if "RaceCure" is filled out, send to email
{
//send email
$sendtoname = "Susan";
$sendtoemail = "susan#email.com";
}
elseif ($_REQUEST['pickevent'] == 'Bowling'))
//if "Bowling" is filled out, send to email
{
//send email
$sendtoname = "John";
$sendtoemail = "john#email.com";
}
But additionally I need to require that an event be selected, so the "else" would be a popup that says "Pick an event!". Does that help?
LAST EDIT :
Ok, so I got the validation working. Thank you. I am replacing this:
$sendtoname = "Mike Gandy";
$sendtoemail = "me#myemail.com";
With this:
switch(strtolower($event){
case 'HeartWalk':
$sendtoname('Bob')
$sendtoemail('bob#email.com');
break;
case 'RaceCure':
$sendtoname('Susan')
$sendtoemail('susan#email.com');
break;
case 'Bowling':
$sendtoname('John')
$sendtoemail('john#email.com');
break;
}
Adding this:
$headers .= "Cc: somebody#domain.com" . "\r\n";
And changed the beginning of my message to this:
$message = "Dear $sendtoname, <br><br>A new volunteer has registered for your "$_REQUEST['pickevent'];
$message .= " event. Below is a copy of their registration: ".$_REQUEST['blank'];
$message .= " <br><br> <b>First Name:</b> ".$_REQUEST['firstname'];
And included this in my form:
<input type="hidden" name="blank" value="">
Yes? No?
Use the select HTML tag to create the drop down menu:
<select name="event">
<option value="heartwalk">Heart Walk</option>
<option value="other">Other</option>
</select>
When handling the post, use the $_REQUEST["event"] for decision like:
switch ($_REQUEST["event"])
{
case 'heartwalk':
$sendtoemail = "heartwalk#example.com";
break;
default:
$sendtoemail = "other#example.com";
break;
}
For validation, you can start with JavaScript validation on client, when submitting the form. For example refer to: https://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Of course, some validation on server side is recommended too. Depending on how robust you want your system to be, you may start with simply not doing anything to redirecting browser back to the form and displaying message on the page.
You could try a switch statement.
switch(strtolower($event){
case 'heart walk':
$sendtoemail('bob#email.com');
break;
case 'some other walk':
$sendtoemail('theotherguy#email.com');
break;
default:
$sendtoemail('info#email.com');
break;
}
Alright, I'm starting to pull my hair and I need some help :)
Here is my file which is used to select activated emails from users and send them some sort of newsletter.
Content of the newsletter.php
<?php
//Include configuration file
include 'config/config.php';
$pdo = new PDO("mysql:host=localhost;dbname=$db", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Define messages
//Error messages
define('ERROR_MESSAGE_SUBJECT', 'Enter subject');
define('ERROR_MESSAGE_CONTENT', 'Enter some content');
//Define variables
$errorFlag = false;
$to = array();
//Grab variables
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newsletterSubject = check_input($_POST['newsletterSubject']);
$newsletterContent = $_POST['newsletterContent'];
if(!$newsletterSubject) {
$errorSubject = ERROR_MESSAGE_SUBJECT;
$errorFlag = true;
}
if(!$newsletterContent) {
$errorContent = ERROR_MESSAGE_CONTENT;
$errorFlag = true;
}
}
?>
<form action="newsletter.php" method="post">
<label>Naslov newsletter-a: <?php echo '<span class="error">'.$errorSubject.'</span>';?></label>
<input type="text" class="linput rounded" name="newsletterSubject">
<label>Sadržaj newsletter-a: <?php echo '<span class="error">'.$errorContent.'</span>';?></label>
<textarea name="newsletterContent" class="rounded"></textarea><br>
<input type="submit" class="submit button rounded" name="newsletterSend" value="Pošalji newsletter korisnicima">
</form>
<?php
if (!$errorFlag) {
echo '
<div class="heading">
<h1>Sending statistic</h1>
</div>';
$query = $pdo->prepare('SELECT email FROM users WHERE active=:active');
$query->bindValue(':active', '1');
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
$i=1;
while($row = $query->fetch()) {
$to[] = $row['email'];
}
print_r($to);
if(!empty($to)) {
foreach($to as $mail) {
$headers = "From: " . $fromEmail . "\r\n";
$headers .= "Reply-To: ". $fromEmail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= $newsletterContent;
$message .= '</body></html>';
mail($mail, $newsletterSubject, $message, $headers);
$i++;
}
}
}
?>
After selecting active emails from database, array $to contains:
Array ( [0] => somemail1#domain.com [1] => somemail2#domain.com )
And that is correct, but both emails will receive 2 emails, so 4 in total. Normally one email should receive one newsletter.
And there is also something else strange, when first newsletter is received, it contains subject and message. However second newsletter doesnt contain anything except 'to' field.
So to sum up, this file sends two emails per one email in database.
I tried to create test file with same array and this is content of it:
test.php
<?php
$fromEmail = 'from#mydomain.com';
$to = array('somemail1#domain.com', 'somemail2#domain.com');
print_r($to);
foreach($to as $mail) {
$headers = "From: " . $fromEmail . "\r\n";
$headers .= "Reply-To: ". $fromEmail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= $newsletterContent;
$message .= '</body></html>';
mail($mail, $newsletterSubject, $message, $headers);
$i++;
}
?>
This test file sends normal email - one email per one email. So server configuration should be okay.
It looks like it's because your send code isn't inside the code block which checks that it is POST, so it sends once when you load the page and again when you fill in the form and submit it.
Move the whole if (!$errorFlag) block into the if ($_SERVER['REQUEST_METHOD'] == 'POST') block.