I've got a script that I downloaded that's a contact form with reCaptcha v3 which emails the filled out form.
The reCaptcha and mail is working, but am having a problem with the checkboxes.
When I fill out the form, my error log says
PHP Warning: Undefined variable $instype in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 121
The code at line 121 is:
'instype[]' => $instype
This is what I have in the AjaxForm.php for checkboxes -
if(!empty($_POST['instype[]'])) {
foreach($_POST['instype[]'] as $instype){
echo "value : ".$instype.'<br/>';
}
}
In my form, my checkboxes are -
<input class="form-check-input shadow-none" type="checkbox" value="Business insurance" name="instype[]" id="instype">
<label class="form-check-label" for="instype">Business insurance</label>
<input class="form-check-input shadow-none" type="checkbox" value="Life insurance" name="instype[]" id="instype">
<label class="form-check-label" for="instype">Life insurance</label>
I need to have multiple checkboxes in the contact form and have those displayed in the email that's sent.
I'm more on the UX/UI Design side, so I'm not really fluent in Ajax and PHP, so any help is appreciated.
Thanks!
NOTE: Here's the complete AjaxForm.php file.
<?php
/**
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
# https://www.php.net/manual/fr/timezones.php
date_default_timezone_set('America/Los_Angeles');
require __DIR__ . '/../PHPMailer/Exception.php';
require __DIR__ . '/../PHPMailer/PHPMailer.php';
require __DIR__ . '/../PHPMailer/SMTP.php';
require __DIR__ . '/../recaptcha/autoload.php';
class Ajax_Form {
# Constants to redefined
# Check this for more configurations: https://blog.mailtrap.io/phpmailer
const HOST = 'xxxxx'; # SMTP server
const USERNAME = 'xxxxx'; # SMTP username
const PASSWORD = 'xxxxx'; # SMTP password
const SECRET_KEY = 'xxxxx'; # GOOGLE secret key
const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;
const SMTP_AUTH = true;
const PORT = 587;
const SUBJECT = 'xxxxx';
const HANDLER_MSG = [
'success' => '✔️ Your message has been sent !',
'token-error' => '❌ Error recaptcha token.',
'enter_firstname' => '❌ Please enter your first name.',
'enter_lastname' => '❌ Please enter your last name.',
'enter_email' => '❌ Please enter a valid email.',
'enter_phone' => '❌ Please enter a valid phone number.',
'enter_message' => '❌ Please enter your message.',
'enter_instype' => '❌ Please enter instype.',
'bad_ip' => '❌ 56k ?',
'ajax_only' => '❌ Asynchronous anonymous.',
'email_body' => '
<h1>{{subject}}</h1>
<p><b>First name:</b> {{firstname}}</p>
<p><b>Last name:</b> {{lastname}}</p>
<p><b>Email:</b> {{email}}</p>
<p><b>Phone:</b> {{phone}}</p>
<p><b>Address 1:</b> {{address1}}</p>
<p><b>Address 2:</b> {{address2}}</p>
<p><b>City:</b> {{city}}</p>
<p><b>State:</b> {{state}}</p>
<p><b>Zip:</b> {{zip}}</p>
<p><b>Interested in:</b> {{instype}}</p>
'
];
/* <p><b>Date</b>: {{date}}</p>
<p><b>Name</b>: {{name}}</p>
<p><b>E-Mail</b>: {{email}}</p>
<p><b>Message</b>: {{message}}</p>
<p><b>IP</b>: {{ip}}</p>
'
];*/
/**
* Ajax_Form constructor
*/
public function __construct()
{
# Check if request is Ajax request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
$this->statusHandler('ajax_only');
}
# Check if fields has been entered and valid
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$firstname = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
$lastname = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
$email = filter_var($this->secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? $this->statusHandler('enter_email');
$phone = $this->secure($_POST['phone']) ?? $this->statusHandler('enter_phone');
$address1 = $this->secure($_POST['address1']) ?? $this->statusHandler('enter_address1');
$address2 = $this->secure($_POST['address2']) ?? $this->statusHandler('enter_address2');
$city = $this->secure($_POST['city']) ?? $this->statusHandler('enter_city');
$state = $this->secure($_POST['state']) ?? $this->statusHandler('enter_state');
$zip = $this->secure($_POST['zip']) ?? $this->statusHandler('enter_zip');
# if (!empty($_POST['instype']))
# $instype = $this->secure($_POST['instype']);
# else
# $this->statusHandler('enter_instype');
if(!empty($_POST['instype'])) {
foreach($_POST['instype'] as $instype){
echo "value : ".$instype.'<br/>';
}
}
# $message = $this->secure($_POST['message']) ?? $this->statusHandler('enter_message');
$token = $this->secure($_POST['recaptcha-token']) ?? $this->statusHandler('token-error');
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?? $this->statusHandler('bad_ip');
$date = new DateTime();
}
# Prepare email body
$email_body = self::HANDLER_MSG['email_body'];
$email_body = $this->template($email_body, [
'subject' => self::SUBJECT,
'date' => $date->format('j/m/Y H:i:s'),
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email,
'phone' => $phone,
'address1' => $address1,
'address2' => $address2,
'city' => $city,
'state' => $state,
'zip' => $zip,
'instype' => $instype
]);
# Verifying the user's response
$recaptcha = new \ReCaptcha\ReCaptcha(self::SECRET_KEY);
$resp = $recaptcha
->setExpectedHostname($_SERVER['SERVER_NAME'])
->verify($token, $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
# Instanciation of PHPMailer
$mail = new PHPMailer(true);
$mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');
try {
# Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF; # Enable verbose debug output
$mail->isSMTP(); # Set mailer to use SMTP
$mail->Host = self::HOST; # Specify main and backup SMTP servers
$mail->SMTPAuth = self::SMTP_AUTH; # Enable SMTP authentication
$mail->Username = self::USERNAME; # SMTP username
$mail->Password = self::PASSWORD; # SMTP password
$mail->SMTPSecure = self::SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
$mail->Port = self::PORT; # TCP port
# Recipients
$mail->setFrom(self::USERNAME, $firstname, $lastname);
$mail->addAddress($email, $firstname, $lastname);
$mail->AddCC(self::USERNAME, 'Dev_copy');
$mail->addReplyTo(self::USERNAME, 'Information');
# Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = self::SUBJECT;
$mail->Body = $email_body;
$mail->AltBody = strip_tags($email_body);
# Send email
$mail->send();
$this->statusHandler('success');
} catch (Exception $e) {
die(json_encode($mail->ErrorInfo));
}
} else {
die(json_encode($resp->getErrorCodes()));
}
}
/**
* Template string values
*
* #param string $string
* #param array $vars
* #return string
*/
public function template(string $string, array $vars): string
{
foreach ($vars as $name => $val) {
$string = str_replace("{{{$name}}}", $val, $string);
}
return $string;
}
/**
* Secure inputs fields
*
* #param string $post
* #return string
*/
public function secure(string $post): string
{
$post = htmlspecialchars($post, ENT_QUOTES);
$post = stripslashes($post);
$post = trim($post);
return $post;
}
/**
* Error or success message
*
* #param string $message
* #return json
*/
public function statusHandler(string $message): json
{
die(json_encode(self::HANDLER_MSG[$message]));
}
}
# Instance
new Ajax_Form();
Here's the AjaxForm.js code
const publicKey = "XXXXX"; // GOOGLE public key
// Get token from API
function check_grecaptcha() {
grecaptcha.ready(function () {
grecaptcha.execute(publicKey, {
action: "ajaxForm"
}).then(function (token) {
$("[name='recaptcha-token']").val(token);
});
});
}
// Show response in .alert
function alertShowing(response) {
$("#response-alert").html(JSON.parse(response));
$("#response-alert").removeClass("d-none");
$("#response-alert").addClass("d-block");
}
$(function () {
check_grecaptcha();
$("#contactform").validate({
// Form fields rules
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
message: {
required: false,
minlength: 5
}
},
// Error messages
messages: {
firstname: {
required: "Please enter your first name.",
minlength: "Must be at least 3 characters long."
},
lastname: {
required: "Please enter your last name.",
minlength: "Must be at least 3 characters long."
},
email: "Please enter a valid email.",
message: {
required: "Please enter your message.",
minlength: "Must be at least 5 characters long."
}
},
errorClass: "invalid-feedback",
// Dynamic validation classes
highlight: function (element) {
$(element).addClass("is-invalid").removeClass("is-valid");
},
unhighlight: function (element) {
$(element).addClass("is-valid").removeClass("is-invalid");
},
// Action on submit
submitHandler: function (form) {
$(".spinner-border").removeClass("d-none");
$("#sendtext").addClass("d-none");
$.post(form.action, $(form).serialize())
.done(function (response) {
alertShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
$("#submit-btn").prop("disabled", true);
check_grecaptcha();
setTimeout(function () {
$("#submit-btn").prop("disabled", false);
$("form").trigger("reset");
$("form").each(function () {
$(this).find(".form-control").removeClass("is-valid")
})
}, 3000);
})
.fail(function (response) {
alertShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
});
}
});
});
Like already stated in the comments. You never initialized your variable $instype, but you try to access it several times. At least inititialize the variable before any access with an empty value like
$instype = ''
or by uncommenting
$instype = $this->secure($_POST['instype']);
But be aware, this won't solve your problem since you have this line in a comment and also will never be run if the the if-condition does not match.
Related
Ever since I made a change to a send file, I am getting around 20 spam submissions a day on a form. Before the change there was never spam.
The subtle modifications to my send file are shown below. The change solely consisted of how I was getting the POST data. The commented code below was my original and non-commented is what it is now.
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
//$to_requester = Communication::mail_api($_POST, null, $template, 1, "../PDFs/" . $file_mapping[$_POST['pdf_downloaded']] . ".pdf");
There are several parts to my form. The process goes in this order:
Submission to Salesforce
Information sent to my database (via ajax)
Notification emails are sent to the user and myself (via ajax)
The spam submissions that are occurring are only submitted to salesforce. They never touch my send file (this includes the db submission and email notifications). The change I noted above is in the send file, so I have no idea why this would have any effect.
I have jQuery validation setup on the form itself.
The salesforce id and other information is held in a config file and called in the form file.
The submissions are entering salesforce like this:
The name/company fields are being filled with some sort of id/code. Again, the send file or database are not being reached with these submissions. The send file is reached with AJAX communicating in-between.
What could be causing these spam submissions? Is there anything I can do validation wise to make sure this spam is not submitted?
Form
<form action="<?php echo $config['sf_url']; ?>" method="POST" id="pdfForm">
<input type=hidden name="oid" value="<?php echo $config['oid']; ?>">
<input type=hidden name="retURL" value="<?php echo $config['retUrl']; ?>">
<input type="text" class="input block" id="first_name" maxlength="40" name="first_name"placeholder="First Name *">
<input type="text" class="input block" id="last_name" maxlength="80" name="last_name" placeholder="Last Name *">
<input type="email" class="input block" id="email" maxlength="80" name="email" placeholder="Email *">
<input id="pdfButton" class="button" type="submit" value="Download File">
</form>
Config
<?php
function getConfig($key)
{
$db = [
'username' => 'user',
'pass' => 'password',
'dbname' => 'db',
];
$ar = [
'sf' => [
'oid' => 'real id',
'sf_url' => 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8',
'retUrl' => 'https://example.com',
],
'pdo' => new PDO("mysql:host=localhost;dbname={$db['dbname']}", $db['username'], $db['pass'])
];
if(array_key_exists($key, $ar))
return $ar[$key];
}
Send file
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require_once '../config.php';
if ($_SERVER['REQUEST_METHOD'] != 'POST')
exit();
$file_mapping = [
//Index
'Linear Structure' => 'Belt_Driven_Linear_1_3D', //LM Index
'Dynamic Structure' => 'Belt_Driven_Linear_5_3D', //LM MH Index
//LM
'Ball-Screw Application' => 'Belt_Driven_Linear_2_3D',
'Belt-Driven Structure' => 'Belt_Driven_Linear_6_3D',
'Linear Motion Enclosure' => 'Belt_Driven_Linear_7_3D'
];
$first_name = trim(htmlspecialchars($_POST['first_name']));
$last_name = trim(htmlspecialchars($_POST['last_name']));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$company = trim(htmlspecialchars($_POST['company']));
$pdf_downloaded = trim(htmlspecialchars($_POST['pdf_downloaded']));
$page_name = $_POST['page_name'];
$hasError = false;
try {
$config = getConfig('db');
$sent = false;
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$consult_insert = "
INSERT INTO pdf_submissions
(first_name, last_name, email, phone, company, date, pdf_downloaded, page_source)
VALUES(?,?,?,?,?,NOW(),?,?)
";
$consult_stmt = $con->prepare($consult_insert);
$consult_stmt->execute(array($first_name, $last_name, $email, $phone, $company, $pdf_downloaded, $page_name));
if (!array_key_exists($pdf_downloaded, $file_mapping)) {
$date = new DateTime();
$hasError = true;
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: The file selected could not be found in the file mapping. {$pdf_downloaded}.", FILE_APPEND);
}
} catch (PDOException $e) {
// echo "Connection failed: " . $e->getMessage();
}
if ($hasError !== true) {
/************************ Start to Requester ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{phone}',
'{company}',
'{email}',
'{pdf_downloaded}'
];
$values = [
htmlentities($_POST['first_name']),
htmlentities($_POST['last_name']),
htmlentities($_POST['phone']),
htmlentities($_POST['company']),
htmlentities($_POST['email']),
htmlspecialchars($_POST['pdf_downloaded']),
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_requester.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
if (!$to_requester) {
$msg = [
'status_code' => 500,
'status_message' => 'Email Failed to send.'
];
echo json_encode($msg);
}
/************************ End to Requester ******************************/
/************************ Start to Domain ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{email}',
'{phone}',
'{company}',
'{file_requested}',
'{page_name}'
];
$values = [
$first_name = trim(htmlspecialchars($_POST['first_name'])),
$last_name = trim(htmlspecialchars($_POST['last_name'])),
$email = trim(htmlspecialchars($_POST['email'])),
$phone = trim(htmlspecialchars($_POST['phone'])),
$company = trim(htmlspecialchars($_POST['company'])),
$pdf_downloaded = trim(htmlspecialchars($pdf_downloaded)),
$page_name = $_POST['page_name'],
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_domain.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$_POST['sendTo'] = "info#example.com";
$to_company = Communication::mail_api($_POST, null, $template, 0);
/************************ End to Domain ******************************/
if (!$to_company) {
$msg = [
'status_code' => 500,
'status_message' => 'Email was not sent.'
];
} else {
$msg = [
'status_code' => 200,
'status_message' => 'Check your Email.'
];
}
echo json_encode($msg);
JS
$("form#pdfForm").submit(function (form, e) {
console.log(send);
if(!send)
{
return false;
console.log("Should never touch this " + send);
}
var formData = new FormData(this);
$.ajax({
url: 'https://example.com/php',
type: 'POST',
data: formData,
success: function (e) {
$.LoadingOverlay("hide");
},
cache: false,
contentType: false,
processData: false
});
});
I have this contact form but I am confused as to how I can insert PHPMailer (without Composer) into the script?
I am not sure how to properly add it so that way, once it processes and sends the form it alerts the user. I do not have the ability to utilize composer, so I would need to upload PHPMailer into the directory.
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
$data = http_build_query([
"secret" => $secret,
"response" => $clientResponse,
"remoteip" => $clientIp,
]);
$options = [
"http" => [
"header" =>
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($data)."\r\n",
"method" => "POST",
"content" => $data,
],
];
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify",
false,
stream_context_create($options)
);
if($response === false)
{
return false;
}
else if(($arr = json_decode($response, true)) === null)
{
return false;
}
else
{
return $arr["success"];
}
}
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['captcha'] = 'Captcha is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// 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);
Without autoloader:
<?php
//You shall use the following exact namespaces no
//matter in whathever directory you upload your
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Now include the following following files based
//on the correct file path. Third file is required only if you want to enable SMTP.
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
?>
You shall add the following class to initiate the mailer after checking if your query or condition is executed.
<?php
$mail = new PHPMailer(true);
?>
You shall find a nice and simple example at https://github.com/PHPMailer/PHPMailer/blob/master/README.md to start with.
I hope it helps.
How can I check the receiver email is real or not on mail send in CodeIgniter3? And if it is not available or not real [fake] mail address then show the alert box with Mail is not available.
For example : When we send mail in gmail with fake mail address [which is not available or not real] then gmail reply with below text.
Google tried to deliver your message, but it was rejected by the server for the recipient domain example.com by mta5.am0.example.net.
EDIT 1
Here is my email send code. Please guide me where to add that code. I added as you said but it show
undefined email variable.
My email send code below :
<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
* SENDS EMAIL WITH GMAIL
*/
class Emailsend extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('emailsend_model');
}
function index()
{
$mail_setting = $this->emailsend_model->getMailSetting();
$config = Array(
'protocol' => 'smtp',
//'smtp_host' => $mail_setting->smtp_server_name,
'smtp_host' => 'ssl://smtp.googlemail.com',
//'smtp_port' => 465,
'smtp_port' => 465,
//'smtp_user' => $mail_setting->smtp_user_name,
'smtp_user' => 'kzwkyawzinwai#gmail.com',
//'smtp_pass' => $mail_setting->smtp_password,
'smtp_pass' => 'mypassword',
'smtp_timeout' => '7',
'mailtype' => 'text',
'validation' => TRUE,
'charset' => 'utf-8',
'newline' => "\r\n",
'wordwrap' => TRUE,
'crlf' => "\r\n",
'newline' => "\r\n",
'dsn' => TRUE
);
$this->load->library('email', $config);
date_default_timezone_set("Asia/Tokyo");
$day = date('Y-m-d');
//$hour = date('H:i:00');
//$mail_informs = $this->emailsend_model->getSendMailInfo($day, $hour);
$mail_informs = $this->emailsend_model->getSendMailInfo($day);
if(!empty($mail_informs)){
function calculate_string($mathString) {
$mathString = trim($mathString);
$mathString = preg_replace('/[^0-9.\+\-\*\/\(\)]/', '', $mathString);
$compute = create_function("", "return (". $mathString .");");
return 0 + $compute();
}
foreach($mail_informs as $mail_inform)
{
$message = $mail_inform->subject;
$search_word = array("(氏名)", "(メールアドレス)", "(登録日)");
$mail_date = str_replace("-", '/', $mail_inform->insert_date);
$replace_word = array($mail_inform->user_name, $mail_inform->mail_addr, $mail_date);
$item_informs = $this->emailsend_model->getAllOriginalItemsById($mail_inform->user_plan_detail_id);
foreach($item_informs as $item_inform){
$item_name = "(". $item_inform->item_name . ")";
if($item_inform->data_type==2){
$item_value_date = $item_inform->item_value;
$item_value = str_replace("-", "/", $item_value_date);
}
else if($item_inform->data_type==1){
$item_value = $item_inform->item_value;
$item_name = str_replace(str_split('()'), '', $item_name);
}
else if($item_inform->data_type==0){
$item_value = $item_inform->item_value;
}
array_push($search_word, $item_name);
array_push($replace_word, $item_value);
}
$result_message = str_replace($search_word, $replace_word, $message);
preg_match_all("/\(([^)]*)\)/", $result_message, $matches);
$search_matches = $matches[0];
$cal_arr = $matches[1];
$cal_count = count($cal_arr);
$replace_matches = array();
for($i=0;$i<$cal_count;$i++)
{
$cal_val = calculate_string($cal_arr["$i"]);
array_push($replace_matches, $cal_val);
}
$final_message = str_replace($search_matches, $replace_matches, $result_message);
$this->email->set_newline("\r\n");
$this->email->from( $mail_setting->sender_mail_addr);
$this->email->to($mail_inform->mail_addr);
$this->email->subject(mb_convert_encoding($mail_inform->title, "UTF-8"));
$this->email->message(mb_convert_encoding($final_message, "UTF-8"));
$path = __DIR__;
$file = $path . '/../../uploads/'.$mail_inform->tpl_id.'/'.$mail_inform->file_attachment;
if(!empty($mail_inform->file_attachment)) {
$this->email->attach($file);
}
$r=#$this->email->send();
if (!$r) {
?>
<script type="text/javascript">
alert("Send Failed");
</script>
<?php
show_error($this->email->print_debugger());
}
else{
?>
<script type="text/javascript">
alert("Send Successfully");
</script>
<?php
echo $this->email->print_debugger();
//show_error($this->email->print_debugger());
}
/*if($r) {
$status = 2; // 送信済み
$id = $mail_inform->user_plan_detail_id;
$this->emailsend_model->setStatus($id, $status);
?>
<script type="text/javascript">
alert("Send Successfully");
</script>
<?php
}
else {
$status = 1; // 送信失敗
$id = $mail_inform->user_plan_detail_id;
$this->emailsend_model->setStatus($id, $status);
?>
<script type="text/javascript">
alert("Send Failed");
</script>
<?php
show_error($this->email->print_debugger());
}*/
$this->email->clear(TRUE);
}
}
}
}
The other possible solution (outside codeigniter) to consume public api like https://mailjagger.com/api/validate/rajehs#mta5.am0.example.net that would return true or false. And just execute mail sending section once received true.
Update:
Create a php file in your library folder named Genuinemail.php. contents as follows
class Genuinemail {
public function __construct() {
// Do your stuff with $arr
}
/**
* verify email format, dns and banned emails
* #param string $email
* #return mixed bool true if correct / string
*/
public static function check($email)
{
//get the email to check up, clean it
$email = filter_var($email,FILTER_SANITIZE_STRING);
// 1 - check valid email format using RFC 822
if (filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
return 'No valid email format';
//get email domain to work in nexts checks
$email_domain = preg_replace('/^[^#]++#/', '', $email);
// 2 - check if its from banned domains.
if (in_array($email_domain,self::get_banned_domains()))
return 'Banned domain '.$email_domain;
// 3 - check DNS for MX records
if ((bool) checkdnsrr($email_domain, 'MX')==FALSE)
return 'DNS MX not found for domain '.$email_domain;
// 4 - wow actually a real email! congrats ;)
return TRUE;
}
/**
* gets the array of not allowed domains for emails, reads from json stores file for 1 week
* #return array
* #see banned domains https://github.com/ivolo/disposable-email-domains/blob/master/index.json
* #return array
*/
private static function get_banned_domains()
{
//where we store the banned domains
$file = 'banned_domains.json';
//if the json file is not in local or the file exists but is older than 1 week, regenerate the json
if (!file_exists($file) OR (file_exists($file) AND filemtime($file) < strtotime('-1 week')) )
{
$banned_domains = file_get_contents("https://rawgit.com/ivolo/disposable-email-domains/master/index.json");
if ($banned_domains !== FALSE)
file_put_contents($file,$banned_domains,LOCK_EX);
}
else//get the domains from the file
$banned_domains = file_get_contents($file);
return json_decode($banned_domains);
}
}
This library can be used like this sample method
function checkSpam($email)
{
$this->load->library('genuinemail');
$check = $this->genuinemail->check($email);
if($check===TRUE) return true;
return false;
}
I trying to send mail using yii simple mailer ...
I followed the step :
http://www.yiiframework.com/extension/yii-simple-mailer/
And download the extension and put in yii extension folder :
https://github.com/tlikai/YiiMailer
Then put the code to config/main.php:
'mailer' => array(
// for smtp
'class' => 'ext.mailer.SmtpMailer',
'server' => 'theserver',
'port' => '25',
'username' => 'theadmin',
'password' => 'thepassword',
// for php mail
'class' => 'ext.mailer.PhpMailer',
),
Then in my controller I wrote this code to send mail:
$to = 'wahaha#gmail.com';
$subject = 'Hello Mailer';
$content = 'Some content';
Yii::app()->mailer->send($to, $subject, $content);
Then the browser gave me the error :
Property "PhpMailer.server" is not defined.
Did I miss something in my code?
In config/main.php
'Smtpmail'=>array(
'class'=>'ext.smtpmail.PHPMailer',
'Host'=>"localhost",
'Username'=>'thesmile1019#gmail.com',
'Password'=>'wakakaka',
'Mailer'=>'smtp',
'Port'=>25,
'SMTPAuth'=>true,
),
In Component/controller.php
public function mailsend($to,$from,$from_name,$subject,$message)
{
$mail = Yii::app()->Smtpmail;
$mail->SetFrom($from,$from_name);
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->AddAddress($to, "");
// Add CC
if(!empty($cc)){
foreach($cc as $email){
$mail->AddCC($email);
}
}
// Add Attchments
if(!empty($attachment)){
foreach($attachment as $attach){
$mail->AddAttachment($attach);
}
}
if(!$mail->Send()) {
return false; // Fail echo "Mailer Error: " . $mail->ErrorInfo;
}else {
return true; // Success
}
}
In controller
public function actionSendMail(){
$token = $_POST['YII_CSRF_TOKEN'];
if ($token !== Yii::app()->getRequest()->getCsrfToken()){
Yii::app()->end();
}
$to = 'thesmile1019#gmail.com';
$from = 'localhost';
$from_name = 'mface';
$subject = 'testing';
$message = 'testing';
if($token == true){
$util = new Utility();
$util->detectMobileBrowser();
$util->checkWebSiteLanguageInCookies();
$this->layout = "masterLayout";
$this->render('mailsend');
$this->mailsend($to,$from,$from_name,$subject,$message);
}else{
print_r("Not Sent");
die();
}
}
Process not problem going correct but didn't receive the mail
Change your port in pathtowebroot/protected/config/main.php
'Smtpmail'=>array(
'class'=>'ext.smtpmail.PHPMailer',
'Host'=>"smtp.gmail.com",
'Username'=>'thesmile1019#gmail.com',
'Password'=>'wakakaka',
'Mailer'=>'smtp',
'Port'=>465,
'SMTPAuth'=>true,
'SMTPSecure' => 'ssl'
),
I would like to send data with UrlFetchApp but something is not working. I not understand where is the problem are not very experienced in question, can someone explain to me how to configure both files to send and receive parameters?
Google Apps Script:
function sendEXTmail(name,email,subject,body) {
var url = "http://www.mysite.com/willy.php";
var options = {
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
var response = UrlFetchApp.fetch(url, options);
return response;
}
PHP:
require "phpmailer/class.phpmailer.php";
$from_name = (isset($_POST['From_Name'])) ? $_POST['From_Name'] : '';
$from_email = (isset($_POST['From_Email'])) ? $_POST['From_Email'] : '';
$to_name = (isset($_POST['To_Name'])) ? $_POST['To_Name'] : '';
$to_email = (isset($_POST['To_Email'])) ? $_POST['To_Email'] : '';
$subject = (isset($_POST['Subject'])) ? $_POST['Subject'] : '';
$message = (isset($_POST['Message'])) ? $_POST['Message'] : '';
$mail= new PHPmailer();
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->Host = "localhost";
$mail->Port = 25;
$mail->SMTPSecure = "none";
$mail->SMTPAuth = false;
$mail->addReplyTo($from_email, $from_name);
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->addAddress($to_email, $to_name);
$mail->Subject = $subject;
$mail->Body = '<html>'.$message.'</html>';
if(!$mail->Send()){
echo $mail->ErrorInfo;
}else{
echo 'Email inviata correttamente!';
}
$mail->SmtpClose();
unset($mail);
?>
On the Google Apps Script side, you can review the message to be sent by using UrlFetchApp.getRequest(). For example:
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
Here's what it logs:
[15-05-06 22:23:35:144 EDT] {
"headers": {
"X-Forwarded-For": "99.224.168.137"
},
"useIntranet": false,
"followRedirects": true,
"payload": "From_Name=Fix+Name&Subject=subject_param&Message=body&From_Email=fix_mail#domain.com&To_Email=email#example.com&To_Name=name_param",
"method": "post",
"contentType": "application/x-www-form-urlencoded",
"validateHttpsCertificates": true,
"url": "http://www.example.com/willy.php"
}
Based on that, it appears that your function has prepared a POST request that should match your PHP.
Next, check the result of the POST itself. To that, first use the muteHttpExceptions option, then look for and handle the return code in your function by using HttpResponse.getResponseCode(). Furthermore, to obtain the readable text from the response, use response.getContentText(). Here's how that might look:
function sendEXTmail(name,email,subject,body) {
name = name || "name_param";
email = email || "email#example.com";
subject = subject || "subject_param";
body = body || "body";
var url = "http://www.example.com/willy.php";
var options = {
"muteHttpExceptions": true,
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
if (rc !== 200) {
// Failure - log it
Logger.log( "Error %s: %s", rc, response.getContentText())
}
return response.getContentText();
}
Try this with your real URL, and see what you get back. If it's a 200, then the Google Apps Script side of the exchange has worked properly. If not, the response should tell you more about the nature of the failure, and help you along to a solution.