Weird Behavior of Google ReCaptcha V2 - php

I am using PHP Mailer to mail the details of a form to a particular Email Address. But before that the code checks the server side validation of Google Recaptcha Version 2. I am facing this weird behavior where the server validation is always returning me false. I am not able to figure out why? I have double-checked the site and secret keys and both are as defined my google account. Following is the code:
<?php
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
require 'PHPMailer-master/src/Exception.php';
if(isset($_POST['submit']))
{
$captcha;
$target_dir = "Upload_Attachment/";
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$mobile = htmlentities($_POST['mobile']);
$edu_qual = htmlentities($_POST['edu_qual']);
$years_exp = htmlentities($_POST['years_exp']);
$comments = htmlentities($_POST['frmrequirements']);
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<script>alert("Something Went Wrong!");</script>';
exit;
}
$secretKey = "MY_SECRET_KEY";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<script>alert("Something Went Wrong!");</script>';
exit;
}
else
{
$ds= DIRECTORY_SEPARATOR;
$target_dir = "resume_files".$ds;
$target_file = $target_dir . basename($_FILES["my_File"]["name"]);
if (move_uploaded_file($_FILES["my_File"]["tmp_name"], $target_file))
{
//echo "The file ". basename($file). " has been uploaded.";
}
else
{
echo '<script>alert("Something Went Wrong!");</script>';
}
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP(); // enable SMTP
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->isHTML();
$mail->Username = "MY_USER_NAME";
$mail->Password = "MY_PASSWORD";
$mail->SetFrom("MY_EMAIL");
$mail->Subject = "Job Enquiry from ".$_POST['name'];
$mail->Body = "
<html>
<body>
<table cellspacing = '5' cellpadding = '5' border='2'>
<tr>
<td>Name:</td>
<td>".$name."</td>
</tr>
<tr>
<td>Email ID:</td>
<td>".$email."</td>
</tr>
<tr>
<td>Mobile No:</td>
<td>".$mobile."</td>
</tr>
<tr>
<td>Years of Experience:</td>
<td>".$years_exp."</td>
</tr>
<tr>
<td>Educational Qualification:</td>
<td>".$edu_qual."</td>
</tr>
<tr>
<td>Comments:</td>
<td>".$comments."</td>
</tr>
</table>
</body>
</html>
";
$mail->addAttachment($target_file);
$mail->AddAddress("TARGET_EMAIL_ID");
if(!$mail->Send())
{
echo '<script>alert("Something Went Wrong!");</script>';
}
else
{
unlink($target_file);
}
echo "<script>location='careers?success=1'</script>";
}
}
?>
Please help me.

It looks like you're using a GET request instead of POST to query Google.
You can build a POST request using stream_context_create.
Example:
$data = ['secret' => $secret, 'response' => $response, 'remoteip' => $ip];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $context);

Related

Issue with PHPmailer and Google reCapcha V2 validation

I'm having issues with Google reCapcha verification in a form using PHPmailer. When the form is completed and the check in "I'm not a robot" is ok, press SEND and this message appears:
"reCaptcha is not Valid! Please try again.".
I've tried with reloading, change navigator to latest version, delete historial, and nothing works.
This is the message in the Google reCapcha admin panel: "We have detected that your website does not verify reCAPTCHA solutions. These verifications are necessary for the service to function properly on your website. You can get more information on our developer website".
Furthermore, I've set the allow_url_fopen = on for testing, but still doesn't work.
Does anyone figure out what's going on, and what's the best solution?
Actualization 13/06:
The ERROR_LOG shows this:
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mywebsite/public_html/include/contact-form.php on line 90
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=XX--very long code here--XX): failed to open stream: no suitable wrapper could be found in /home/mywebsite/public_html/include/contact-form.php on line 90
The contact-form.PHP file original is this:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/Exception.php';
require 'php-mailer/src/PHPMailer.php';
//require 'php-mailer/src/SMTP.php';
// Enter your email address. If you need multiple email recipes simply add a comma: email#domain.com, email2#domain.com
$to = "";
// Add your reCaptcha Secret key if you wish to activate google reCaptcha security
$recaptcha_secret_key = '';
// Default message responses
const RESPONSE_MSG = [
'success' => [
"message_sent" => "We have <strong>successfully</strong> received your message. We will get back to you as soon as possible."
],
'form' => [
"recipient_email" => "Message not sent! The recipient email address is missing in the config file.",
"name" => "Contact Form",
"subject" => "New Message From Contact Form"
],
'google' => [
"recapthca_invalid" => "reCaptcha is not Valid! Please try again.",
"recaptcha_secret_key" => "Google reCaptcha secret key is missing in config file!"
]
];
//This functionality will process post fields without worrying to define them on your html template for your customzied form.
//Note: autofields will process only post fields that starts with name widget-contact-form OR with custom prefix field name
$form_prefix = isset($_POST["form-prefix"]) ? $_POST["form-prefix"] : "widget-contact-form-";
$form_title = isset($_POST["form-name"]) ? $_POST["form-name"] : RESPONSE_MSG['form']['name'];
$subject = isset($_POST[$form_prefix."subject"]) ? $_POST[$form_prefix."subject"] : RESPONSE_MSG['form']['subject'];
$email = isset($_POST[$form_prefix."email"]) ? $_POST[$form_prefix."email"] : null;
$name = isset($_POST[$form_prefix."name"]) ? $_POST[$form_prefix."name"] : null;
if( $_SERVER['REQUEST_METHOD'] == 'POST') {
if($email != '') {
if(empty($to)) {
$response = array ('response'=>'warning', 'message'=> RESPONSE_MSG['form']['recipient_email']);
echo json_encode($response);
die;
}
//If you don't receive the email, enable and configure these parameters below:
//$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
//$mail->IsSMTP();
//$mail->Host = 'mail.yourserver.com'; // Specify main and backup SMTP servers, example: smtp1.example.com;smtp2.example.com
//$mail->SMTPAuth = true;
//$mail->Port = 587; // TCP port to connect to 587 or 465
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
//$mail->Username = 'SMTP username'; // SMTP username
//$mail->Password = 'SMTP password'; // SMTP password
$mail = new PHPMailer;
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
if(strpos($to, ',') !== false){
$email_addresses = explode(',', $to);
foreach($email_addresses as $email_address) {
$mail->AddAddress(trim($email_address));
}
}
else {$mail->AddAddress($to);}
$mail->AddReplyTo($email, $name);
$mail->Subject = $subject;
// Check if google captch is present
if(isset($_POST['g-recaptcha-response'])) {
if(empty($recaptcha_secret_key)) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recaptcha_secret_key']);
echo json_encode($response);
die;
}
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$recaptcha_secret_key.'&response='.$_POST['g-recaptcha-response']);
$response_data = json_decode($response);
if ($response_data->success !== true ) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recapthca_invalid']);
echo json_encode($response);
die;
}
}
//Remove unused fields
foreach (array("form-prefix", "subject", "g-recaptcha") as $fld) {
unset($_POST[$form_prefix . $fld]);
}
unset($_POST['g-recaptcha-response']);
//Format eMail Template
$mail_template = '<table width="100%" cellspacing="40" cellpadding="0" bgcolor="#F5F5F5"><tbody><tr><td>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%"><tbody>';
$mail_template .= '<tr><td style="padding-top:20px;padding-left:0px;padding-right:0px;width:100%;text-align:right; font-size:12px;line-height:22px">This email is sent from '.$_SERVER['HTTP_HOST'].'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="padding: 50px; border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%; background-color:#ffffff;"><tbody>';
$mail_template .= '<tr><td style="font-weight:bold;font-family:Arial,sans-serif;font-size:36px;line-height:42px">'.$form_title.'</td></tr>';
$mail_template .= '<tr><td style="padding-top:25px;padding-bottom:40px; font-size:16px;">';
foreach ($_POST as $field => $value) {
$split_field_name = str_replace($form_prefix, '', $field);
$ucwords_field_name = ucfirst(str_replace('-', ' ', $split_field_name));
$mail_template .= '<p style="display:block;margin-bottom:10px;"><strong>'.$ucwords_field_name.': </strong>'.$value.'</p>';
}
$mail_template .= '</td></tr>';
$mail_template .= '<tr><td style="padding-top:16px;font-size:12px;line-height:24px;color:#767676; border-top:1px solid #f5f7f8;">Date: '.date("F j, Y, g:i a").'</td></tr>';
$mail_template .= '<tr><td style="font-size:12px;line-height:24px;color:#767676">From: '.$email.'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '</td></tr></tbody></table>';
$mail->Body = $mail_template;
// Check if any file is attached
$attachments = [];
if (!empty($_FILES[$form_prefix.'attachment'])) {
$result = array();
foreach ($_FILES[$form_prefix.'attachment'] as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$result[$i][$key] = $value[$i];
}
}
foreach ( $result as $key => $attachment) {
$mail->addAttachment($attachment['tmp_name'],$attachment['name']);
}
}
if(!$mail->Send()) {
$response = array ('response'=>'error', 'message'=> $mail->ErrorInfo);
}else {
$response = array ('response'=>'success', 'message'=> RESPONSE_MSG['success']['message_sent']);
}
echo json_encode($response);
} else {
$response = array ('response'=>'error');
echo json_encode($response);
}
}
?>
Thank you,
Alejandra

Stripe payment email

I'm using PHP, is there a way of sending emails when a successful payment is done in Stripe for TEST ACCOUNT other than sending it manually from the dashboard using any code or alternative ways?
EDIT1: I've added phpmailer code to my file and it says email sent but I didn't receive any emails. I've tried it in a contact form in another page it works but when I add it in the file where there is stripe (with some changes) it doesn't work. Here is the code in thankYou.php:
<?php
require_once 'core/init.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
if(isset($_POST['submit_2'])) {
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->addAddress($_POST['email']);
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->IsHTML(true);
$mail->SingleTo = true;
$mail->From = "myemail";
$mail->Subject = "Stripe";
$mail->Body = "Test";
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
} else {
echo "Email sent";
}
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey(STRIPE_PRIVATE);
// Get the credit card details submitted by the form
$token = isset($_POST['stripeToken'])? $_POST['stripeToken']:'';
// Get the rest of the post data
$full_name = isset($_POST['full_name'])? sanitize($_POST['full_name']):'';
$email = isset($_POST['email'])? sanitize($_POST['email']):'';
$street = isset($_POST['street'])? sanitize($_POST['street']):'';
$street2 = isset($_POST['street2'])? sanitize($_POST['street2']):'';
$city = isset($_POST['city'])? sanitize($_POST['city']):'';
$state = isset($_POST['state'])? sanitize($_POST['state']):'';
$phone_number = isset($_POST['phone_number'])? sanitize($_POST['phone_number']):'';
$country = isset($_POST['country'])? sanitize($_POST['country']):'';
$tax = isset($_POST['tax'])? sanitize($_POST['tax']):'';
$sub_total = isset($_POST['sub_total'])? sanitize($_POST['sub_total']):'';
$grand_total = isset($_POST['grand_total'])? sanitize($_POST['grand_total']):'';
$cart_id = isset($_POST['cart_id'])? sanitize($_POST['cart_id']):'';
$description = isset($_POST['description'])? sanitize($_POST['description']):'';
$charge_amount = number_format((float)$grand_total,2) * 100;
$metadata = array(
"cart_id" => $cart_id,
"tax" => $tax,
"sub_total" => $sub_total,
);
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
"amount" => $charge_amount, // amount in cents, again
"currency" => CURRENCY,
"source" => $token,
"description" => $description,
"receipt_email" => $email,
"metadata" => $metadata)
);
//adjust inventory
$itemQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$iresults = mysqli_fetch_assoc($itemQ);
$items = json_decode($iresults['items'],true);
foreach($items as $item){
$newAges = array();
$item_id = $item['id'];
$productQ = $db->query("SELECT ages, sold FROM products WHERE id = '{$item_id}'");
$product = mysqli_fetch_assoc($productQ);
$ages = agesToArray($product['ages']);
$soldproducts = $product['sold'];
foreach($ages as $age){
if($age['age'] == $item['age']){
$q = $age['quantity'] - $item['quantity'];
$newAges[] = array('age' => $age['age'],'quantity' => $q,'threshold' => $age['threshold']);
}else{
$newAges[] = array('age' => $age['age'],'quantity' => $age['quantity'],'threshold' => $age['threshold']);
}
}
if (isset($item['quantity'])) {
$sold = ($soldproducts + $item['quantity']);
}
$ageString = agesToString($newAges);
$db->query("UPDATE products SET ages = '{$ageString}', sold = '{$sold}' WHERE id = '{$item_id}'");
}
//update cart
$db->query("UPDATE cart SET paid = 1 WHERE id = '{$cart_id}'");
$db->query("INSERT INTO transactions
(charge_id,cart_id,full_name,email,street,street2,city,state,phone_number,country,sub_total,tax,grand_total,description,txn_type)
VALUES ('$charge->id','$cart_id','$full_name','$email','$street','$street2','$city','$state','$phone_number','$country','$sub_total',
'$tax','$grand_total','$description','$charge->object')");
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')? '.'.$_SERVER['HTTP_HOST']:false;
setcookie(CART_COOKIE,'',1,"/",$domain,false);
include 'includes/head.php';
include 'includes/navigation.php';
?>
<div class="container-fluid" style="margin-top:100px;">
<h1 class="text-center text-success">Thank You!</h1>
<p> Your card has been successfully charged <?=money($grand_total);?>. You have been emailed a receipt. Please
check you spam folder if it is not in your inbox. Additionally you can print this page as a receipt.</p>
<p>Your receipt number is: <strong><?=$cart_id;?></strong></p>
<p>Your order will be shipped to the address below.</p>
<address>
<?=$full_name;?><br>
<?=$city. ', '.$state.' ';?><br>
<?=$street;?><br>
<?=$street2;?><br>
<?=$phone_number;?><br>
</address>
</div>
<?php
include 'includes/footer.php';
} catch(\Stripe\Error\Card $e) {
// The card has been declined
echo $e;
}
?>
And in the cart.php file (NOT ALL THE CODES):
<div class="form-group col-lg-6">
<label for="email">Email:</label>
<input class="form-control" id="email" name="email" type="text">
</div>
<button type="submit" name="submit_2" class="btn btn-primary" id="checkout_button" style="display:none;">Check Out >></button>
Please help...
This is from the Stripe API documentation (PHP):
receipt_email optional
The email address to which this charge’s receipt will be sent. The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. If this charge is for a Customer, the email address specified here will override the customer’s email address. If receipt_email is specified for a charge in live mode, a receipt will be sent regardless of your email settings
In "test" mode, it's totally impossible to automatically send email from stripe after payment even if you set "receipt_email" parameter. Only in "live" mode, it's possible.
Actually, I couldn't find the information above on stripe documentation so I asked stripe support, then, they said so as I said above.

Sending mail with api data using codeigniter

I need to send mail to the admin with the inserted data using APi function ,
the function is look like that
public function requestbookingresort_post()
{
$languageid = $this->input->post('languageId');
$resort_id = $this->input->post('resortId');
$booking_from = $this->input->post('bookingFrom');
$booking_to = $this->input->post('bookingTo');
$contact_name = $this->input->post('contactName');
$contact_email = $this->input->post('contactEmail');
$contact_phone = $this->input->post('contactPhone');
$userid = $this->input->post('userId');
if (empty($languageid))
{
$languageRecord = getDefaultlanguage();
$languageid = $languageRecord->languageid;
}
$language_file = languagefilebyid($languageid);
$this->lang->load($language_file, $language_file);
if (empty($resort_id) || empty($booking_from) || empty($booking_to) || empty($contact_name) || empty($contact_email) || empty($contact_phone))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_in_booking');
$arr['data'] = array();
}
else
{
$dataArray = array(
"languageid" => $languageid,
"userid" => empty($userid) ? "0" : $userid,
"resortid" => $resort_id,
"bookingfrom" => date("Y-m-d", strtotime($booking_from)),
"bookingto" => date("Y-m-d", strtotime($booking_to)),
"contactname" => $contact_name,
"contactemail" => $contact_email,
"contactphone" => $contact_phone,
"requestdatetime" => date("Y-m-d H:i:s"),
);
$this->load->model("Resort_model");
$booking_id = $this->Resort_model->saveBookingRequest($dataArray);
if (empty($booking_id))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_occurred');
$arr['data'] = array();
}
else
{
$arr['status'] = 'success';
$arr['statusMessage'] = lang('booking_request_submit');
$arr['data'] = array();
}
}
$response = array(
"response" => $arr
);
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
But i'm new at codeigniter and didn't know how to get this passed data from the database to send mail with that to the admin mail or something ?
Try this.
public function requestbookingresort_post()
{
// Your operations
$response = array(
"response" => $arr
);
$this->sendMail($response)
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function sendMail($response)
{
$settings=$this->Some_model->getEmailSettings();
$mail = new PHPMailer();
$mail->IsSMTP(); // we are going to use SMTP
$mail->SMTPAuth = true; // enabled SMTP authentication
$mail->SMTPSecure = "ssl"; // prefix for secure protocol to connect to the server
$mail->Host = $settings->host; // setting GMail as our SMTP server
$mail->Port = $settings->port; // SMTP port to connect to GMail
$mail->Username = $settings->email; // user email address
$mail->Password = $settings->password; // password in GMail
$mail->SetFrom($settings->sent_email, $settings->sent_title); //Who is sending the email
$mail->AddReplyTo($settings->reply_email,$settings->reply_email); //email address that receives the response
$mail->Subject = "Your Booking has been confirmed";
$mail->IsHTML(true);
$body = $this->load->view('path/email_template', $response, true);
$mail->MsgHTML($body);
$destination = $response['contactEmail']; // Who is addressed the email to
$mail->AddAddress($destination);
if(!$mail->Send()) {
$data['code']=300;
$data["message"] = "Error: " . $mail->ErrorInfo;
}
}
Make sure you have PHPMailer in your libraries and you are loading the library in your constructor and I hope you are keeping Email settings in your database. If not you can manually provide host, port, username and password fields

Zend_mail success message comes but mail not send

guys i have using a script to send mails, all seems fine with it and even i get the success message but sadly the emails are not delivered.. can any body look for any lapses in this code
Code
$body = "This is testmail please ignore";
$mail = new Zend_Mail ();
$tr = new Zend_Mail_Transport_Sendmail ( '-f' . $sentFromEmail );
Zend_Mail::setDefaultTransport ( $tr );
$mail->setReturnPath("user#admin.com");
$mail->setFrom ( "user#admin.com", 'Reporters' );
$mail->setBodyHtml ( $body );
$mail->addTo ( "samjam#gmail.com" );
$mail->setSubject ( "Weekly Report" );
try {
$mail->send ();
echo "Success";
} catch ( Exception $e ) {
echo "Mail sending failed.\n";
}
SMTP configuration
if (isset($config['ssl'])) {
switch (strtolower($config['ssl'])) {
case 'tls':
$this->_secure = 'tls';
break;
case 'ssl':
$this->_transport = 'ssl';
$this->_secure = 'ssl';
if ($port == null) {
$port = 465;
}
break;
}
}
if ($port == null) {
if (($port = ini_get('smtp_port')) == '') {
$port = 25;
}
}
The answer is that samjam#gmail.com is not an email address of any email account that you have access to.
It belongs to a private individual who you do not know.
This is the correct answer.

Yii Mailer doesn't work

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'
),

Categories