How can I use mailgun to extend CEmailLogRoute in Yii? - php

I am using the Mailgun Yii extension(https://github.com/baibaratsky/php-mailgun) and am able to send a test email from inside the 'views/site/SiteController.php' file using the following code:
$message = Yii::app()->mailgun->newMessage();
$message->setFrom('sender#domain.com', 'Sender Name');
$message->addTo('recipient#domain.com', 'Recipient Name');
$message->setSubject('Mailgun API library test');
$message->setText('Test Email Content Text');
$message->send();
Now I am trying to extend the CEmailLogRoute class so that I can send any log emails using mailgun with no success. This is the class I wrote to extend it:
class CMailGunLogRoute extends CEmailLogRoute {
protected function sendEmail($email, $subject, $message) {
$message = Yii::app()->mailgun->newMessage();
$message->setFrom('sender#domain.com', 'Sender Name');
$message->addTo($email);
$message->setSubject($subject);
$message->setText($message);
$message->send();
}
}
And this is what I added to the 'config/main.php' file:
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CEmailLogRoute',
'levels'=>'info',
'emails'=>'recipient#domain.com',
'sentFrom'=>'sender#domain.com',
'subject'=>'Email Log File Message',
),
),
),
And this is the logging function I am declaring on the root index file:
function d2l($what, $where='fb.somewhere') {
$what = print_r($what,true);
Yii::log($what, 'info','application.'.$where);
}
And this is where I am calling that function from within the 'SiteController.php' file:
d2l('Test Log Message','site.index');
Unfortunately, none of this seems to get it to send the log email. Initially I tried to send the log email without using mailgun and that didn't work either, so perhaps the issue is with the code I wrote for the mail logging.

I figured out how to do this:
CMailGunLogRoute.php
// components/CMailGunLogRoute.php
class CMailGunLogRoute extends CEmailLogRoute {
protected function sendEmail($email, $subject, $message) {
$mail = Yii::app()->mailgun->newMessage();
$mail->setFrom($this->getSentFrom());
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setText($message);
$mail->send();
}
}
SiteController.php
// controllers/SiteController.php
Yii::log('Test Log Message', 'info','application');
main.php
// config/main.php
'import'=>array(
'application.components.*',
),
'mailgun' => array(
'class' => 'application.extensions.php-mailgun.MailgunYii',
'domain' => 'mydomain.com',
'key' => 'API_KEY_NUM',
'tags' => array('yii'), // You may also specify some Mailgun parameters
'enableTracking' => true,
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CMailGunLogRoute',
'levels'=>'info',
'filter'=>'CLogFilter',
'emails'=>'recipient#domain.com',
'sentFrom'=>'sender#domain.com',
'subject'=>'Email Log File Message',
),
),
),
If you have any additional tips on how to improve this, please feel free to add them below.

Related

mailer symfony 4 not working

I started a project using symfony 4 and the mailer doesn't work, however it should be easy.
before you ask, if i copy past the login and password from my code i'm able to log into my mail account, also i also tried with a netcourrier mail account, also the 2 way authentification is not active and i allowed less secure app to access the mail account.
Here's my conf:
in my .env:
MAILER_URL=gmail://*******#gmail.com:********#localhost
in my controller:
public function contact( \Swift_Mailer $mailer){
$message = (new \Swift_Message('Hello Email'))
->setFrom('*****#gmail.com')
->setTo('*******#gmail.com')
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'email/registration.html.twig',
array('url' => $url)
),
'text/html'
);
$mailer->send($message);
return $this->render(
'email/index.html.twig');}
and the error i get doing so is :
Connection could not be established with host smtp.gmail.com [ #0]
The problem is your connection SMTP with google, This is correct:
MAILER_URL=smtp://smtp.gmail.com:587?encryption=tls&username=userGmail&password=PassGmail
I have it defined as a service in App/Services, this is the code
<?php
namespace App\Services;
class Enviomail {
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function sendEmail($to, $subject, $texto) {
$message = (new \Swift_Message($subject))
->setFrom('juanitourquiza#gmail.com')
->setTo($to)
->setBody(($texto),'text/html');
return $this->mailer->send($message);
}
}
And to use it I call it from the controller
use App\Services\Enviomail;
........
public function mailsolucion(Request $request, Enviomail $enviomail) {
if ($request->isMethod('POST')) {
$nombre=$request->get("nombre");
$email=$request->get("email");
$numero=$request->get("numero");
$empresa=$request->get("empresa");
$solucion=$request->get("solucion");
if (($nombre=="")||($email=="")||($numero=="")||($empresa=="")){
$this->addFlash(
'alert alert-danger',
'Toda la informaciĆ³n es obligatoria'
);
return $this->redirectToRoute('registro');
}
$emailreceptor="juanitourquiza#gmail.com";
$asunto="Soluciones gruporadical.com";
$texto=$this->renderView(
'emails/soluciones.html.twig',
array(
'nombre' => $nombre,
'email' => $email,
'numero' => $numero,
'empresa' => $empresa,
'solucion' => $solucion,
)
);
$enviomail->sendEmail($emailreceptor,$asunto, $texto);
$this->addFlash(
'alert alert-success',
'Pronto nos pondremos en contacto.'
);
return $this->redirectToRoute('registro');
}
return $this->render('AppBundle:App:contacto.html.twig');
}
Works perfect on Symfony 4.x
I think this is not an issue with the mailer, but with gmail. I copied your steps to try to connect through the smtp server of gmail, but got the same error. When using a different MAILER_URL (a different smtp-server) in the .env file, everything works like it should.

Laravel 5.4 change the subject of markdown mail

I have used markdown mailables which is a new feature in laravel 5.4. I have successfully implemented a mail sender. It seems, the subject of the mail is named as the name of the mailable class. I need to change the subject of the mail and it's hard to find any resources regarding this.
There is subject method in laravel mailables.
All of a mailable class' configuration is done in the build method. Within this method, you may call various methods such as from, subject, view, and attach to configure the email's presentation and delivery. : https://laravel.com/docs/5.4/mail#writing-mailables
You can achieve this like this :
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->subject('Your Subject')
->markdown('emails.orders.shipped');
}
You may need to execute php artisan view:clear after modifying your class.
If the email subject is the same for all emails then just overload the $subject parameter in your extended Mailable class.
/**
* The subject of the message.
*
* #var string
*/
public $subject;
complete code (tested)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
class ContactController extends Controller {
public function sendContactMail(Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'user_message' => 'required'
]);
Mail::send('contact_email',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'subject' => $request->get('subject'),
'user_message' => $request->get('user_message'),
), function($message) use ($request)
{
$message->from($request->email );
$message->subject("Your Subject");
$message->to('email to');
});
return back()->with('success', 'Your message was sent successfully');
}
}

Running a module controller in yii

I have just created a module named myfirstmodule using gii in yii and then just hit the URl in my browser like:
localhost/yii_learn/index.php?r=myfirstmodule
defaultcontroller will run and display the output. Now I created a new controller and view in the same module and just run by:
http://localhost/yii_learn/index.php?r=myfirstmodule/mycontroller/index
It's redirecting me to home page of project.
Below is the code:
mycontroller.php
class mycontroller {
//put your code here
public function actionIndex(){
$this->render('myfirst');
}
And my view file code is
<?php
$this->breadcrumbs=array(
$this->module->id,
);
?>
<h1><?php echo $this->uniqueId . '/' . $this->action->id; ?></h1>
<p>
This is the view content for action "<?php echo $this->action->id; ?>".
The action belongs to the controller "<?php echo get_class($this); ?>"
in the "<?php echo $this->module->id; ?>" module.
</p>
<p>
You may customize this page by editing <tt><?php echo __FILE__; ?></tt>
</p>
Main.php file code
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Web Application',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
'modules'=>array('testmodule','CustomerOnBoarding',
'myfirstmodule'=>array(),
// 'myfirstmodule'=>array(
// 'class'=>'\myfirstmodule\DefaultController',
// ),
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>false,
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
// 'urlManager'=>array(
// 'caseSensitive' => true,
// 'urlSuffix' => '/',
// 'showScriptName' => false,
//
// 'urlFormat'=>'path',
'rules'=>array('myfirstmodule'=>'myfirstmodule/mycontroller/index',
// '<controller:\w+>/<id:\d+>'=>'<controller>/view','<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
// database settings are configured in database.php
'db'=>require(dirname(__FILE__).'/database.php'),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
// array(
// 'class'=>'CWebLogRoute',
// ),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
Can anyone help me in this, that how can I run my controller and view .
The format of the url is http://localhost/yii_learn/index.php?r=controllername/functionname. If you want to access a function through url, it should be prefixed with action. For example a function actionSampleFunction() in testcontroller can be accessed by http://localhost/yii_learn/index.php?r=testcontroller/samplefunction.
Have you try via access rules for this action
like. Simply add this to your controller and try.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index'),
'users'=>array('*'),
),
);
}
if worked let me know.

link passing through mail php codeigniter

For user identification,I need to send the url of localhost via mail in php codeigniter . . I also need to pass the token which I had generated for that user along with the url. My user need to be verified by clicking that link which must be identified by the corresponding token. And I have no idea about passing variables via url . . How could I proceed my code?
My code follows. .
<?php
class Site_model extends CI_Model
{
public function __construct()
{
parent:: __construct();
$this->load->database();
}
public function insert($token)
{
$data = array(
'name'=>$this->input->post('name'),
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'date_of_birth'=>$this->input->post('dob'),
'user_type'=>$this->input->post('utype'),
'token'=>$token,
);
$this->db->insert('tbl_user',$data);
$email=$this->input->post('email');
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => '465',
'smtp_user' => 'someone#gmail.com',
'smtp_pass' => 'something',
'mailtype' => 'html',
'starttls' => true,
'newline' => "\r\n"
);
$this->load->library('email',$config);
$this->email->From("someone#gmail.com");
$this->email->to($email);
$this->email->subject('test');
$this->email->message("worked");
$this->email->send();
if($this->email->send()) {
echo '<script>alert("Email sent successfully")</script>';
} else {
$this->email->print_debugger();
}
}
}
?>
To pass data along with a URL you can use URI segments.
In your situation the easiest thing to do would probably to be to use GET parameters. To use these you would output the link as normal and then append a parameter to the end like:
http://yoursite.com/user/verify/**token**
This example would be for if you had a user controller with a function called verify. The method signature would be something like:
public function verify($token = NULL) { ... }
The last part of the URL will populate $token which you can then use in the verify function to check the user is valid and perform any actions you need to.
You could always re-route a URL to an alternative method through routes.php if you needed to as well.
Simply pass this link with the token inserted into the email so that when the user clicks on it then the verify method runs with the necessary parameters.

CodeIgniter and Postmark Integration

I am very new to codeigniter and postmark, is there a way on how to integrate the two?
I created a controller called cron.php and put the postmark code inside the method inbound, here's my code:
public function inbound()
{
try {
require_once '../lib/Postmark/Autoloader.php';
\Postmark\Autoloader::register();
// this file should be the target of the callback you set in your postmark account
$inbound = new \Postmark\Inbound(file_get_contents('php://input'));
$this->data['client'] = $this->client_model->get_where($m_where);
if(!empty($this->data['client']))
{
$m_insert = array('cme_username' => $inbound->FromName(),
'cme_title' => $inbound->Subject(),
'cme_message' => $inbound->TextBody(),
'cme_client' => $this->data['client']['ccl_id'],
'cme_from' => 'client',
'cme_through' => 'email',
'cme_date_sent' => date('Y-m-d H:i:s'),
'cme_admin' => 0);
$this->message_model->insert($m_insert);
}
}
catch (Exception $e) {
echo $e->getMessage();
}}
I'm also wondering if I am doing it correctly? Many thanks!
You can simply pull one of the example classes from the PostMarkApp.com website (I used this one and renamed it simply postmark) in the application/libraries/ directory and use it like any other CI Library. Make sure you have the proper globals defined (I defined them in application/config/config.php).
application/config/config.php
define('POSTMARKAPP_API_KEY', 'YOUR-POSTMARKAPP-API-KEY');
define('POSTMARKAPP_MAIL_FROM_ADDRESS', 'you#yourdomain.com');
application/controllers/somecontroller.php
class somecontroller extends CI_Controller {
function someControllerMethod(){
$this->load->library('postmark');
$this->postmark->addTo('someone#somewhere.com', 'John Doe')
->subject('My email subject')
->messagePlain('Here is a new message to John!')
->tag('some-tag')
->send();
}
}
Hope that helps!

Categories