kovordaniy
11/25/2015 - 8:26 AM

WP phpmailer

WP phpmailer

// Vacancy Form via Ajax
add_action('wp_ajax_vacancy_sendform', 'vacancy_sendform');
add_action('wp_ajax_nopriv_vacancy_sendform', 'vacancy_sendform');
function vacancy_sendform() {
	global $wpdb, $headers_from, $headers_from_email, $headers_from_name;

	require_once ABSPATH . WPINC . '/class-phpmailer.php';

	$mail = new PHPMailer();

	$response = array();

	try
	{
		$name = $_POST['name'];
		if(empty($name)) {
			throw new Exception("Name is required field");
		}

		$email = $_POST['email'];
		if(empty($email))
		{
			throw new Exception("Email is required field");
		}

		if ( !$_FILES['cv']['error'] == 4 ) { //something was send
			if ( $_FILES['cv']['error'] == 0 && is_uploaded_file($_FILES['cv']['tmp_name']) )
				$mail->AddAttachment($_FILES['cv']['tmp_name'], $_FILES['cv']['name']);
			else
				throw new Exception("Error: there was a problem with the file upload. Try again later.");
		}

		$subscribe = $_POST['subscribe'];
		switch ($subscribe) {
			case "on": $subscribe = "Yes"; break;
			default: $subscribe = "No"; break;
		}

		$subject = "Vacancy - " . $_POST['title'];

		$body = "
		             <strong>Name:</strong> $name<br/>
		             <strong>E-mail:</strong> $email<br/>
		             <strong>Subscribe:</strong> $subscribe";

		$to = get_field("vacancies_email", "option");

		if(empty($to))
		{
			throw new Exception("Please fill e-mail field in admin panel");
		}

		if(!empty($to))
		{
			$mail->SetFrom($headers_from_email, $headers_from_name);
			$mail->AddAddress($to);
			$mail->Subject = $subject;
			$mail->MsgHTML($body);
			$mail->Send();

			// Subscribe
			if ($subscribe == "Yes") {

				$exists = intval($wpdb->get_var("SELECT COUNT(*) FROM ".$wpdb->prefix."sml where sml_email like '".esc_sql($email)."' limit 1"));

				if ($exists < 1) {

					$wpdb->query(
						$wpdb->prepare(
							"INSERT INTO ".$wpdb->prefix."sml (sml_name, sml_email) values ( %s, %s )",
							esc_sql($name),
							esc_sql($email)
						)
					);
				}


			}
		}

		$response['result'] = get_field("vacancies_email_message", "option");
		$response['referer'] = $_SERVER['HTTP_REFERER'];
	}
	catch(Exception $ex)
	{
		$response['error'] = $ex->getMessage();
	}

	print json_encode($response);
	die();
}