Script won't send Email

cpradio I have similar problem to jstead and i see the amazing help you gave, so can you hel me too, because i don’t understand anything about php?
I have a contact form using muse and my host can’t have php mail functioning so it seems they are using pear but i don’t mind to test phpmailer

This is the form_process.php code (i have in the scripts folder one called form_throttle.php and form-u191.php i will upload them if you want)

<?php 
/* 	
If you see this text in your browser, PHP is not configured correctly on this hosting provider. 
Contact your hosting provider regarding PHP configuration for your site.

PHP file generated by Adobe Muse CC 2014.1.375
*/

require_once('form_throttle.php');

function process_form($form) {
	if ($_SERVER['REQUEST_METHOD'] != 'POST')
		die(get_form_error_response('Unknown server request method'));

	if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
		die(get_form_error_response('Too many recent submissions from this IP'));
	
	// will die() if there are any errors
	check_required_fields($form);
	
	// will die() if there is a send email problem
	email_form_submission($form);
}

function get_form_error_response($error) {
	return get_form_response(false, array('error' => $error));
}

function get_form_response($success, $data) {
	if (!is_array($data))
		die('data must be array');
		
	$status = array();
	$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
	
	return json_serialize($status);
}

function check_required_fields($form) {
	$errors = array();

	foreach ($form['fields'] as $field => $properties) {
		if (!$properties['required'])
			continue;

		if (!array_key_exists($field, $_REQUEST) || empty($_REQUEST[$field]))
			array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
		else if (!check_field_value_format($form, $field, $properties))
			array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
	}

	if (!empty($errors))
		die(get_form_error_response(array('fields' => $errors)));
}

function check_field_value_format($form, $field, $properties) {
	$value = get_form_field_value($field, $properties);

	switch($properties['type']) {
		case 'checkbox':
		case 'string':
		case 'captcha':
			// no format to validate for those fields
			return true;

		case 'recaptcha':
			if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
				die(get_form_error_response('Invalid reCAPTCHA private key.'));
			$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
			return $resp->is_valid;

		case 'email':
			return 1 == preg_match('/^[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\\'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);

		default:
			die(get_form_error_response(sprintf('Unknown field type \\'%s\\'.', $properties['type'])));
	}
}

function email_form_submission($form) {
	if(!defined('PHP_EOL'))
		define('PHP_EOL', '\\r\
');

	$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');

	$to = $form['email']['to'];
	$subject = $form['subject'];
	$message = get_email_body($subject, $form['heading'], $form['fields']);
	$headers = get_email_headers($to, $form_email);	

	$sent = @mail($to, $subject, $message, $headers);
	
	if(!$sent)
		die(get_form_error_response('Failed to send email'));
	
	$success_data = array(
		'redirect' => $form['success_redirect']
	);
	
	echo get_form_response(true, $success_data);
}

function get_email_headers($to_email, $form_email) {
	$headers = 'From: ' . $to_email . PHP_EOL;
	$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
	$headers .= 'X-Mailer: Adobe Muse CC 2014.1.375 with PHP' . PHP_EOL;
	$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
	
	return $headers;
}

function get_email_body($subject, $heading, $fields) {
	$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
	$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
	$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
	$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
	$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
	$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">'; 

	foreach ($fields as $field => $properties) {
		// Skip reCAPTCHA from email submission
		if ('recaptcha' == $properties['type'])
			continue;

		$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($properties['label']) . ':</b></td><td>' . get_form_field_value($field, $properties) . '</td></tr>';
	}

	$message .= '</table>';
	$message .= '<br/><br/>';
	$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">Form submitted from website: ' . encode_for_form($_SERVER['SERVER_NAME']) . '</div>';
	$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">Visitor IP address: ' . encode_for_form($_SERVER['REMOTE_ADDR']) . '</div>';
	$message .= '</body></html>';

	return cleanup_message($message);
}

function is_assoc_array($arr) {
	if (!is_array($arr))
		return false;
	
	$keys = array_keys($arr);
	foreach (array_keys($arr) as $key)
		if (is_string($key)) return true;

	return false;
}

function json_serialize($data) {

	if (is_assoc_array($data)) {
		$json = array();
	
		foreach ($data as $key => $value)
			array_push($json, '"' . $key . '": ' . json_serialize($value));
	
		return '{' . implode(', ', $json) . '}';
	}
	
	if (is_array($data)) {
		$json = array();
	
		foreach ($data as $value)
			array_push($json, json_serialize($value));
	
		return '[' . implode(', ', $json) . ']';
	}
	
	if (is_int($data) || is_float($data))
		return $data;
	
	if (is_bool($data))
		return $data ? 'true' : 'false';
	
	return '"' . encode_for_json($data) . '"';
}

function encode_for_json($value) {
	return preg_replace(array('/([\\'"\\\	\\\\\\\\])/i', '/\\\\r/i', '/\\\
/i'), array('\\\\\\\\$1', '\\\\r', '\\\
'), $value);
}

function encode_for_form($text) {
	return htmlentities($text, ENT_COMPAT, 'UTF-8');
}

function get_form_field_value($field, $properties) {
	$value = $_REQUEST[$field];
	
	switch($properties['type']) {
		case 'checkbox':
			return (($value == '1' || $value == 'true') ? 'Checked' : 'Unchecked');
		
		case 'string':
		case 'captcha':
		case 'recaptcha':
		case 'email':
			return encode_for_form($value);

		default:
			die(get_form_error_response(sprintf('Unknown field type \\'%s\\'.', $properties['type'])));
	}
}

function cleanup_email($email) {
	$email = encode_for_form($email);
	$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\\
|\\\\r)\\S).*=i', null, $email);
	return $email;
}

function cleanup_message($message) {
	$message = wordwrap($message, 70, "\\r\
");
	return $message;
}
?>

Thanks in advance.

Does your host require SMTP authentication? If it does, then you will definitely need to use either Pear:Mail or PHPMailer. I’ve got lots of experience with PHPMailer, so I’m more than willing to help you get that up and running.

Let me know! :slight_smile:

Yes they want i use smtp authentication. I think they have Pear installed, but i dont’t mind to try phpmailer. They have disabled the php mail function due to spam.
Again thanks for the help. I think i will need to learn php :slight_smile:

Not necessarily. It is possible to simply replace the mail() call with an fsockopen() call and some fputs() to write the email directly to the SMTP port.

All those two solutions provide is a wrapper around those calls.

Of course using one of those two is probably the best way for someone unfamiliar with PHP to apply the change but you don’t have to use one of those two.

I discovered yesterday that the new host I moved to a few weeks ago requires SMTP authentication and I decided trying to amend my form2mail script to use either of those two would be harder than simply substituting the direct calls.

Harder than PHPMailer? Really? They make it dead simple (they hide the internals very well). Granted, if you don’t want the additional files, I understand why you may do it on your own :smiley:

Cheers, okay so you will need to download the latest release of PHPMailer, extract it into the folder your form_process.php file exists
Then update your form_process.php file to contain the following for email_form_submission($form)

function email_form_submission($form) {
	if(!defined('PHP_EOL'))
		define('PHP_EOL', '\\r\
');

	$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');

	$to = $form['email']['to'];
	$subject = $form['subject'];
	$message = get_email_body($subject, $form['heading'], $form['fields']);

	require 'PHPMailer-5.2.8/PHPMailerAutoload.php';
	$mail = new PHPMailer;
	$mail->isSMTP();
	$mail->Host = 'smtp.mydomain.com'; // update this line
	$mail->SMTPAuth = true;
	$mail->Username = 'myusername@mydomain.com'; // update this line
	$mail->Password = 'mysecretpassword'; // update this line

	$mail->From = 'myemail@mydomain.com'; // update this line
	$mail->FromName = 'whatever you want here'; // update this line
	$mail->addAddress($to);
	$mail->isHTML(true);

	$mail->Subject = $subject;
	$mail->Body = $message;

	$sent = $mail->send();

	if(!$sent)
		die(get_form_error_response('Failed to send email'));

	$success_data = array(
		'redirect' => $form['success_redirect']
	);

	echo get_form_response(true, $success_data);
}

If you are still getting errors, please let me know and before pasting any code here, remove your username, password, SMTP server, and email address (if you want that to remain hidden).

Amazing! It works like a charm. ( On the mail->Host field instead of using smtp.mydomain.com or mail.mydomain.com, because that is my smtp, i need to put localhost, that is the only way to make it work. ) .You’re the man :slight_smile: Thanks a lot for your help and a fast help. Thanks again. You saved me from some white hairs :slight_smile:
This week i will need to do another site with contact form hosted on the same company. If i replace the actual email_form_submission that adobe muse output to the form_process.php with the one you gave me it is supposed to work too right?

If you need some help using Adobe Muse i’m available to show you some things. Is the least i can do after this :wink:

Best regards

cpradio one more question a little bit off-topic.
I want to place a button on a website where people can send me one file (pdf or doc) from his pc, something like an attachment. Can you point me to somewhere? I think this could be done with php too but… :slight_smile: Thanks

Glad to hear it.

So long as Muse builds similar code to what you originally pasted here, yes, it would work. :slight_smile:

This would be done via a “contact form” as well and where using tools like PHPMailer make this really easy. However, it seems Muse doesn’t support attachments (at least I haven’t found any way for it to do that).

So you’ll have to do multiple things to get your Muse creation to support the attachments and they’ll likely get overwritten if you need to alter your Muse site later on.

First thing you must do is add the following attribute, enctype=“multipart/form-data”, to the <form> tag (where … is the initial attributes Muse places in your <form> tag.

<form .... encytpe="multipart/form-data">

Next you’ll need to add the file input field between the <form> and </form> tag (you may want to format this so it uses a similar syntax as your other form fields).

Attach your file: <input type="file" name="fileAttachment" />

This is where things start to get sketchy :slight_smile: There are a few pieces that Adobe Muse builds that may need altered, and without seeing what happens, I’m not 100% sure if these changes will work, but I think you only need to do the following:

In your email_form_submission, you will need to add these lines before $sent = $mail->send(); is called.

$mail->AddAttachment($_FILES['fileAttachment']['tmp_name'], $_FILES['fileAttachment']['name'], 'base64', $_FILES['fileAttachment']['type']);

Now ideally you’d want to add some validation to only attach files that are a specific file type (word document, image, pdf, etc.), which isn’t covered in the above. So realize that any type of file can be sent with the above.

Muse don’t support attachments, but you can insert html code on it, so i think that could work, but yes i need to think it carefully because that way we have some more risks.
If i understand, that way the attachment goes exactly as an attachment with the contact form through mail or it will stay in a folder on the server?

I will make some tests and tell you what i’m doing. Thanks again for all your help.

Right, so use with risk knowing your changes may get overwritten.

The code examples above only keep the file in the temp folder which gets cleared out by itself on reboots and other activities. So nothing is physically moved into the client’s directory/folder structure.