Yii swift mailer not sending mail - yii

I am using yii mail swiftmailer extension to send mail .when am using this mail extension along with ccaptcha validation in the same form the mail is not sending.when it has be used alone without captcha validation it is sending email.i need to send email using this extension along with the ccaptcha validation in yii.
for email:
$subjek="verifymail";
$from="sender#gmail.com";
$getEmail="to#gmail.com";
$message= new YiiMailMessage;
$message->subject=$subjek;
$message->from=$from;
$message->setBody($activationlink, 'text/html');
$message->addTo($getEmail);
Yii::app()->mail->send($message);

I think you are missing port and host information in your code,unless you didnt show your whole code,see example here
public function actionViewTest() {
// Render view and get content
// Notice the last argument being `true` on render()
$content = $this->render('viewTest', array(
'Test' => 'TestText 123',
), true);
// Plain text content
$plainTextContent = "This is my Plain Text Content for those with cheap emailclients ;-)\nThis is my second row of text";
// Get mailer
$SM = Yii::app()->swiftMailer;
// Get config
$mailHost = 'mail.example.com';
$mailPort = 25; // Optional
// New transport
$Transport = $SM->smtpTransport($mailHost, $mailPort);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage('My subject')
->setFrom(array('from#example.com' => 'Example Name'))
->setTo(array('recipient#example.com' => 'Recipient Name'))
->addPart($content, 'text/html')
->setBody($plainTextContent);
// Send mail
$result = $Mailer->send($Message);
}
If your host is gmail,put the port to 587 or 465
$mail->Port = 587; or $mail->Port = 465;
here is a question almost similar to your question

Related

Xero Oauth2 Node Examples

I am doing some expermenting with the xero API, however i cant seem to get past the Connect to Xero returning an error
"Sorry, something went wrong
Go back and try again.
If the issue continues, check out our Status Page."
I have setup my App in the xero dev center
I have tried these 2 repos
https://github.com/XeroAPI/xero-node-oauth2-app
https://github.com/XeroAPI/node-oauth2-example
Both yeld the same result just an error page, no information in console/dev tools
Any help would be amazing as im completely stuck with this
So that looks like the error you get when either API keys and/or callback urls are not setup correctly.
Have you swapped in all your api keys & callback urls to the .env (environment) files?
Create a .env file in the root of your project & replace the 3 variables
Create an .env file in the root of your project using touch .env or edit the sample prefix off sample.env and change out with your /myapps credentials of the app you just made.
CLIENT_ID=...
CLIENT_SECRET=...
REDIRECT_URI=...
Here is the library that is used successfully with ouath2.0 tokenization. The token is expired in 30 mints. After that, we need to refresh the token with old token objects.
First set up an app in developer.xero.com.
Add Company Name and Redirect URL while creating the app.
Setup environment configuration in your file.
X_CLIENT_ID=CD43E78278ED4BE68F35F155C3E708F7
X_CLIENT_SECRET=IuP5TrE70JoyYiezMRM2KwvcHFYoLy3qRbD3NFlOkYLN0Asy
X_REDIRECT_URL=https://baseredirecturl.com/xero/default/redirect
Step-1: Here is the code for creating a token and refresh token.
public function actionConnectXero()
{
$session = Yii::$app->session;
$request = Yii::$app->request;
if (empty($request->get('code'))) {
// If we don't have an authorization code then get one
$authUrl = $this->provider->getAuthorizationUrl([
'scope' => 'offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read'
]);
//offline_access openid email profile accounting.settings accounting.transactions accounting.contacts accounting.reports.read projects accounting.journals.read
$session->set('oauth2state', $this->provider->getState());
$this->redirect($authUrl);
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($request->get('state')) || ($request->get('state') !== $session->get('oauth2state'))) {
$session->remove('oauth2state');
exit('Invalid state');
} else {
// Try to get an access token (using the authorization code grant)
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$session->set('access_token', $token);
//If you added the openid/profile scopes you can access the authorizing user's identity.
$identity = $this->provider->getResourceOwner($token);
echo "<pre>";
print_r($identity);
//Get the tenants that this user is authorized to access
$tenants = $this->provider->getTenants($token);
print_r($tenants);
$session->set('tenantId', $tenants[0]->tenantId);
exit;
}
}
Step-2: Redirect to URL.
public function actionRedirectXero()
{
$request = Yii::$app->request;
$codeStr = explode("?", $request->getUrl());
$token = $this->provider->getAccessToken('authorization_code', [
'code' => $request->get('code')
]);
$tenants = $this->provider->getTenants($token);
$exits = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
$xeroConf = $exits ? XeroConfigs::findOne($exits->id) : new XeroConfigs();
$xeroConf->access_token = $token;
$xeroConf->refresh_token = $token->getRefreshToken();
$xeroConf->expiry = $token->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;
$xeroConf->token_object = serialize($token);
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$this->redirect('/xero/default/get-xero-data?'.$codeStr[1]);
}
Step-3: Get data from xero. I just save and get contacts. for more examples, you can check the package documentation.
public function actionGetXeroData(){
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
if($configs->expiry < time()){
$newAccessToken = $this->provider->getAccessToken('refresh_token', [
'grant_type' => 'refresh_token',
'refresh_token' => $configs->refresh_token
]);
$tenants = $this->provider->getTenants($newAccessToken);
$xeroConf = XeroConfigs::findOne($configs->id);
$xeroConf->access_token = $newAccessToken;
$xeroConf->refresh_token = $newAccessToken->getRefreshToken();
$xeroConf->expiry = $newAccessToken->getExpires();
$xeroConf->tenant_id = isset($tenants[0]) ? $tenants[0]->id : 0;;
$xeroConf->token_object = serialize($newAccessToken);;
$xeroConf->updated_at = Carbon::now()->toDateTimeString();
$xeroConf->created_by = Yii::$app->user->identity->id;
$xeroConf->save();
$configs = XeroConfigs::find()->where(['created_by' => Yii::$app->user->identity->id])->one();
}
$tokenObj = unserialize($configs->token_object);
$tenants = $this->provider->getTenants($tokenObj);
$xero = new \XeroPHP\Application($tokenObj, $tenants[0]->tenantId);
$contact = new Contact($xero);
$contact->setName('Hassan Raza')
->setAccountNumber('0245541574185741')
->setContactID('852986')
->setGUID('52552548-5585-8715-8888-871222554154')
->setBankAccountDetail('0245541574185741')
->setTaxNumber('55545352')
->setContactStatus('ACTIVE')
->setSkypeUserName('hassan_raza2010')
->setTrackingCategoryName('Manager')
->setFirstName('Hassan')
->setLastName('Raza')
->setEmailAddress('hassan#xero.com');
$response = $contact->save();
dd($response->getResponseBody());

Twilio Programmable Voice isn't working

When i try to pass param from my application using [TwilioVoice Call] method i am not able to get those param on twiML application. but when i try to pass same data from POSTMAN with FormData its working fine and also successfully able to create call.
Would you please help me how can i use param passed from my iOS application into twiML
TwiML Application in PHP :
<?php
/*
* Makes a call to the specified client using the Twilio REST API.
*/
include('./vendor/autoload.php');
include('./config.php');
$to = isset($_GET["to"]) ? $_GET["to"] : "";
if (!isset($to) || empty($to)) {
$to = isset($POST["to"]) ? $_POST["to"] : "";
}
$from = isset($_GET["from"]) ? $_GET["from"] : "";
if (!isset($from) || empty($from)) {
$from = isset($POST["from"]) ? $_POST["from"] : "";
}
use Twilio\Twiml;
$response = new Twiml();
$dial = $response->dial(['callerId' => $from]);
$dial->client($to);
echo $response;
iOS Objective-C :
self.call = [TwilioVoice call:[self fetchAccessToken]
params:#{#"to": #"1",#"from":#"2"}
uuid:uuid
delegate:self];
Twilio Error Log when i try to pass param from iOS
Warning - 13224 Dial: Twilio does not support calling this number or the number is invalid
Reference TwiML Application Code
https://github.com/twilio/voice-quickstart-server-php
Twilio developer evangelist here.
The 12100 error comes from Twilio not being able to parse the TwiML returned from your server. In this case, it is because your PHP is not returning TwiML, it's trying to make a call using the REST API.
It should return a <Dial> with a nested <Client>. You can build this up using the helper library too. Try changing your code to this:
<?php
include('./vendor/autoload.php');
include('./config.php');
$to = isset($_REQUEST["To"]) ? $_REQUEST["To"] : "";
$to = str_replace("client:", "", $to);
$from = isset($_REQUEST["From"]) ? $_REQUEST["From"] : "";
use Twilio\Twiml;
$response = new Twiml();
$dial = $response->dial(['callerId' => $from]);
$dial->client($to);
echo $response;
Let me know if that helps.
Step 1. In the name you have to pass name of the user(any thing you want)
Step 2. You need to generate token using 3 parameters
Step 3. You need to create object of VoiceGrant
Step 4. You need to pass Id
Step 5. You need to set PUSH notification Id generate from twilio
$name = $this->input->post('name');
//$PUSH_CREDENTIAL_SID = 'CRaf1a66dd4a7656876e16c7820ef5c01e';
$outgoingApplicationSid = 'APf9b1b789ba690b8789d95a42511f2018';
// choose a random username for the connecting user
$identity = $name;
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$this->twilioAccountSid,
$this->twilioApiKey,
$this->twilioApiSecret,
3600,
$identity
);
// $chatGrant = new ChatGrant( $pushCredentialSid= "CRaf1a66dd4a7656876e16c7820ef5c01e");
//
// print_r($chatGrant);die;
// Create Chat grant
// $voiceGrant = new VoiceGrant($serviceSid = 'IS840a7e5f64634ab6bf179c3f8b0adfc4',$pushCredentialSid = 'CRaf1a66dd4a7656876e16c7820ef5c01e');
$voiceGrant = new VoiceGrant();
$voiceGrant->setOutgoingApplicationSid($outgoingApplicationSid);
// Optional: add to allow incoming calls
$voiceGrant->setIncomingAllow(true);
$voiceGrant->setPushCredentialSid('CRaf1a66dd4a7656876e16c7820ef5c01e');
// Add grant to token
$token->addGrant($voiceGrant);
// render token to string
$voice_token = $token->toJWT();
if($voice_token){
$data['token'] = $voice_token;
$this->response = array('status'=>1,'data'=>$data);
}else{
$this->response = array('status'=>0,'message'=>'Not found');
}

How to include "cc" and "bcc" fields using mailer extension of Yii Framework

I am working on mail sending functionality using yii framework. I am using mailer extension given on link="http://www.yiiframework.com/extension/mailer".
I have added all files in extension folder. And i have made separate class file with code as-
public function sendEmail($FromEmail,$ToEmail,$Subject,$Message)
{
$settings=new Settings();
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = 'ssl';
$mailer->Host =$settings->Host;
$mailer->Port =$settings->Port;
$mailer->CharSet = 'UTF-8';
$mailer->Username =$FromEmail;
$mailer->Password ='';
$mailer->FromName = 'feedback#balaee.com';
$mailer->AddAddress($ToEmail);
$mailer->Subject = $Subject;
$mailer->IsHTML(true);
$mailer->Body=$Message;
if($mailer->Send())
{
echo "Mail send Successfully.Please you have check mail ";
}
else
{
echo "Fail to send your message!";
}
}
So its working correctly. Its sending emails as per required. But i want include "cc" and "bcc" parameters while using this in order to maintain security. So how can i use "cc" and "bcc" using mailer extension?
According to the README.md on the original PHPMailer's Github home, you can just call $mailer->AddCC('recipient#example.com');. BCC is just as simple: $mailer->AddBCC('another_recipient#example.com');.
The reason I am referring to PHPMailer is that the yii extension page does so too.

Retrieving email-id from database and send mail to them

In yii i am creating sendemail functionality. I am using mailer extension and its working correctly after making all settings of SMTP. i had made method actionEmail in controller as-
public function actionEmail()
{
$model=new User;
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#gmail.com";
$mailer->Password = "abc";
$mailer->From = "xyz#gmail.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress('shilpa.kirad#shailani.com');
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
// $html = $this->renderPartial('myview',array('content'=>'Hello World'),true);
$mailer->Body = "Welcomeclick on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check mail";
//Yii::app()->user->setFlash('register','Thank you for contacting us. We will respond to you as soon as possible.');
// $this->refresh();
}
else {
echo "Fail to send your message!";
}
}
This method is implementing correctly.It is sending mail to address which is mentioned in mailer->AddAdress.But now i want to retrive email id's from database corresponding to specific user's id and send mail to him. i.e.I dont want to insert hard coded value for this field. So how can i do this. Please help me.
for fetch use id of user to get email address as
$user_model=User::model()->findByPk($id);
and set in email as
$mailer->AddAddress($user_model->email_id);
where id and email_id are the table column name.
check other ways .
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
For this to be done, you can fetch email id from database using following query:
$email = SELECT email FROM USER WHERE user_id = "X";
Here X is user_id of user whom you want to send email.
And provide this $email in the receipient's email field. Thanks.

symfony setPostValidator with sfValidatorFile

I am going through an issue to setup a file upload validator on callback.
I want to achieve this:
I have a form, where user choose the type of the file they are uploading and upload the file.
So I want to set the validator to handle images in case they chose "img" as type, and pdf if they chose "pdf".
Moreover I want to specify the mime type and path and validatedFileClass according to the type.
I tried this.. but i can't get it to work
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'validateUploadedFiles')))
);
the function:
public function validateUploadedFiles($form_validator, $values){
$this_year = date("Y");
$this_month = date("m");
$basic_validator = array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').'restaurant/media/'.$this_year.'/'.$this_month.'/'
);
$doc_validator = $video_validator = $img_validator = $pdf_validator = $basic_validator;
$pdf_validator['mime_types'] = array ('application/pdf');
$doc_validator['mime_types'] = array ('application/msword', 'application/vnd.openxmlformats');
$img_validator['mime_types'] = 'web_images';
//$img_validator['validated_file_class'] = 'imgHandling';
$video_validator['mime_types'] = array('video/mpeg', 'video/3gpp', 'video/mp4', 'video/quicktime');
switch( $values['type'] ):
case 'pdf' : $validator = $pdf_validator; break;
case 'img' : $validator = $img_validator; break;
case 'word' : $validator = $doc_validator; break;
case 'video' : $validator = $video_validator; break;
endswitch;
//$form->getValidatorSchema()->offsetUnset('url') ;
//print_r($validator_fields);
$validator = new sfValidatorFile( $validator );
$validator_schema = new sfValidatorSchema();
$validator_schema->offsetSet('url', $validator);
//$validator_fields = $form->getValidatorSchema()->getFields();
$schema = parent::getValidatorSchema();
$schema->offsetUnset('url') ;
$schema->offsetSet('url', $validator);
// $path = sfConfig::get('sf_upload_dir').'restaurant/media/'.$this_year.'/'.$this_month.'/';
// $values['url'] = new sfValidatedFile( $values['url']['name'], $values['url']['type'], $values['url']['tmp_name'], $values['url']['size'] , $path);
//TODO get this url value run through the new added validator
//$values['url'] = $validator_schema->clean(array( 'url' => $values['url'] ));
return $values;
}
the problem i am facing is that , this function receives the url value as array, and even if I update the validators schema, it's not validating the url and keeps on sending it as array to the object saving method.
So how to make something like
url.validateFile() from inside this function
Not sure about the best solution, but I'd prefer to split validation process into 2 parts:
Validate mime type
If mime is ok, then validate URL
Or vise versa, your choice.
The glue would be sfValidatorAnd.
Did I understand you right?