I am trying to send attached files using email class, I have achieved
this no what I need is a progress bar because it takes to long for the
email to send and I need something to tell the user the user that the
email is sending.
class Email extends CI_Controller{
public function send(){
/**
* Load Email Library
*/
$this->load->library('email');
/**
* Config
*/
$config = array(
'useragent' => 'CodeIgniter',
'mailtype'=>"html",
'smtp_host' => 'ssl://smtp.googlemail.com',
'charset' => 'utf-8',
'newline' => "\r\n",
'wordwrap' => true,
);
/**
* Override the config options
*/
$this->email->initialize($config);
$this->email->from('training#pilz.com', 'Training - Pilz');
$this->email->to($this->input->post('email'));
$this->email->subject('Pilz Course Material');
$this->email->message($this->input->post('message'));
//$data = base_url().'uploads/Steps_for_platform.txt';
$this->email->attach($this->input->post('documents'));
$this->email->attach($this->input->post('document2'));
$this->email->attach($this->input->post('document3'));
$this->email->attach($this->input->post('document4'));
if($this->email->send()){
$data['title'] = 'Downloads';
$data['DownloadFav'] = '';
$data['emailAddress'] = $this->input->post('email');
$this->load->view('templates/header', $data);
$this->load->view('pages/confirmemail', $data);
$this->load->view('templates/footer');
}else{
echo $this->email->print_debugger();
}
}
I just added a loading wheel gif and displayed none my modal using jQuery
Related
I am using laravel-IMAP to integrate Gmail with my laravel project and package I follow is Webklex/laravel-imap.
Issue is when i test my code the error poped-up, I followed to many links to figure-out my issue, one solution i find is to enable IMAP access: Enable IMAP, but it is not a solution for all the users, I want to fetch the emails of that user's those who will use this application with doing enable imap access. Is there any other solution to overcome this problem?
Controller
class TestController extends Controller
{
public function index(){
$oClient = new Client([
'host' => 'imap.gmail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => '**********',
'password' => '**********',
'protocol' => 'imap'
]);
/* Alternative by using the Facade
$oClient = Webklex\IMAP\Facades\Client::account('default');
*/
//Connect to the IMAP Server
$oClient->connect();
//Get all Mailboxes
/** #var \Webklex\IMAP\Support\FolderCollection $aFolder */
$aFolder = $oClient->getFolders();
//Loop through every Mailbox
/** #var \Webklex\IMAP\Folder $oFolder */
foreach($aFolder as $oFolder){
//Get all Messages of the current Mailbox $oFolder
/** #var \Webklex\IMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->messages()->all()->get();
/** #var \Webklex\IMAP\Message $oMessage */
foreach($aMessage as $oMessage){
echo $oMessage->getSubject().'<br />';
echo 'Attachments: '.$oMessage->getAttachments()->count().'<br />';
echo $oMessage->getHTMLBody(true);
}
}
}
}
I am trying to fetch an email from outlook Inbox with the Imap package of Laravel. it is working fine with Gmail. but when I try to fetch emails from outlook it gives No message error
ImapController.php
*/
public function index()
{
// dd(phpinfo());
// imap_open('{outlook.office365.com:993/imap/ssl/novalidate-cert}INBOX', 'info#coldxpress.com.au', 'Dac67132');
$oClient = Client::account('default');
$oClient->connect();
//Get all Mailboxes
/** #var \Webklex\IMAP\Support\FolderCollection $aFolder */
$aFolder = $oClient->getFolders('INBOX.Sent');
//Loop through every Mailbox
/** #var \Webklex\IMAP\Folder $oFolder */
foreach ($aFolder as $oFolder) {
//Get all Messages of the current Mailbox $oFolder
/** #var \Webklex\IMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->messages()->since('10.02.2020')->get();
/** #var \Webklex\IMAP\Message $oMessage */
foreach ($aMessage as $oMessage) {
echo $oMessage->getSubject() . '<br />';
// echo 'Attachments: ' . $oMessage->getAttachments()->count() . '<br />';
// echo $oMessage->getHTMLBody(true);
}
}
// return view('home');
}
Config/imap.php
'accounts' => [
'default' => [// account identifier
'host' => env('IMAP_HOST', 'outlook.office365.com'),
'port' => env('IMAP_PORT', 993),
'protocol' => env('IMAP_PROTOCOL', 'imap'), //might also use imap, [pop3 or nntp (untested)]
'encryption' => env('IMAP_ENCRYPTION', 'ssl'), // Supported: false, 'ssl', 'tls', 'notls', 'starttls'
'validate_cert' => env('IMAP_VALIDATE_CERT', false),
'username' => env('IMAP_USERNAME', 'info#coldxpress.com.au'),
'password' => env('IMAP_PASSWORD', '*********'),
],
I want to fetch Emails from Outlook account.
I am working on a Register and Login application with CodeIgniter 3 and Twitter Bootstrap.
When a user registers, an email should be send to the address he/she provided, with an account confirmation link. The problem is that the confirmation email does not send.
In the Usermodel I have:
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
{
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.code-love.tk',
'smtp_port' => 465,
'smtp_user' => 'razvan#code-love.tk',
'smtp_pass' => '******',
'smtp_crypto' => 'ssl',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$messg = 'Wellcome, '. $first_name . ' ' . $last_name . '! Click the <strong>confirmation link</strong> to confirm your account.';
$this->email->initialize($config);
$this->email->set_newline('\r\n');
$this->email->from('mail.code-love.tk','Razvan Zamfir');
$this->email->to($email);
$this->email->subject('Account activation');
$this->email->message($messg);
if (!$this->email->send()) {
show_error($this->email->print_debugger());
}
else {
echo 'Your e-mail has been sent!';
}
}
In my Signup controller I have this code:
public function signup() {
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
if ($this->form_validation->run()) {
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$verification_key = md5($email);
$date_created = date('Y-m-d H:i:s');
$date_updated = date('Y-m-d H:i:s');
$active = 0;
// Load user model
$this->load->model('Usermodel');
// If email does not already exist in the database
// signup new user
if (!$this->Usermodel->email_exists($email)) {
if ($this->Usermodel->user_register($first_name, $last_name, $email, $password, $verification_key, $date_created, $date_updated, $active) && $this->Usermodel->activationEmail($first_name, $last_name, $email, $verification_key)) {
$this->session->set_flashdata("signup_success", "Your account has just bean created. You must confirm it before you can sign in. We have send you a confirmation email at $email for this purpose.");
} else {
// unless sigup does not fail for whatever reason
$this->session->set_flashdata("signup_failure", "We ware unable to create your account.");
}
redirect('signup');
} else {
// If email is already in the database
// urge user to sign in (redirect to signup page too)
$this->session->set_flashdata("email_exists", "The email address $email already exists in the database. Please signin.");
redirect('signin');
}
} else {
$this->load->view('signup');
}
}
The sign up does happen, with the error below, and the verification email is not send. I am not doing this from a local XAMPP/WAMP/MAMP server, but from a "live" one, you can signup yourself.
Severity: Warning
Message: fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known
Filename: libraries/Email.php
Line Number: 1950
Backtrace:
File: /home/roxoqdat/code-love.tk/ciauth/application/models/Usermodel.php
Line: 52
Function: send
File: /home/roxoqdat/code-love.tk/ciauth/application/controllers/Signup.php
Line: 42
Function: activationEmail
File: /home/roxoqdat/code-love.tk/ciauth/index.php
Line: 292
Function: require_once
What am I doing wrong?
Check if you have the required SMTP service.
Try with google SMTP service.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('mygmail#gmail.com', 'myname');
$this->email->to('target#gmail.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$result = $this->email->send();
Next try with:
$config = array('mailtype' => 'html');
Remove the rest from $config = array.
First of all, after setting flashdata, I don't see you redirecting the user to where they can see it...
Also, send the mail first, then you set flash data as An Activation Link Has Been Sent To Your Email, Please Check Your Email To Activate Your Account!
So,
User Registers,
An email is sent to them only if it doesn't exist already,
Set flashdata for any errors that may arise... Eg:
Assign a variable to the email sending function:
$send_email = $this->activationEmail('params');
In your activationEmail function, make sure there is a simple control structure like this:
$success=$this->email->send();
if($success){ return true; } else{ return false; }
Now in your controller, compare to see if mail is actually sent:
if($send_email == true){ $this->session->flashdata('success','Your success message');
// use the redirect() helper function to the function that loads your view
} else { //set failed flashdata and redirect to where you want it seen like above}
You then will know where the problem is.
Let the program flow in your mind first, then implement it. Try that first and get back to me right after.
Hope it somehow helps
Debug whether your parameters are passing or not (specially last_name). Try to write the model method like this to avoid showing errors
public function activationEmail($first_name='', $last_name='', $email='', $verification_key='')
Try adding header to your email (You are setting mailtype twice, might be an issue).
$this->email->set_header('MIME-Version', '1.0; charset=utf-8');
$this->email->set_header('Content-type', 'text/html');
i have one requirement from in my application..so when ever user insert details in the requirement.and then submit..the mail will go to the particular vendor with one link..when vendor click on the link i redirect the page to login page..
So what i want to do is i want to send email link with last inserted id..
Here is my controller:
public function requirement()
{
$data["msg"]="";
$this->load->model('RequirementModel');
$data['user']=$this->RequirementModel->getusers();
$data['rolename']=$this->RequirementModel->getrolename();
if($this->input->post())
{
$this->RequirementModel->add_requirement($this->input->post());
$all_users = $this->input->post('user_id');
foreach($all_users as $key)
{
$get_email = $this->RequirementModel->get_user_email_by_id($key);
$req_id = $this->input->post('req_id');
$role_name = $this->input->post('role_name');
$vacancies = $this->input->post('vacancies');
$experience = $this->input->post('experience');
$jd = $this->input->post('jd');
$hiring_contact_name = $this->input->post('hiring_contact_name');
$hiring_contact_number = $this->input->post('hiring_contact_number');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://md-in-42.webhostbox.net',
'smtp_port' => 465,
'smtp_user' => 'test3#clozloop.com',
'smtp_pass' => 'test3'
);
$this->load->library('email',$config);
$this->email->set_mailtype("html");
$this->email->from('test3#clozloop.com', 'bharathi');
$this->email->to($get_email);
$this->email->subject('this is our requirements pls go through it');
$link = 'Click on this link - <a href="http://localhost/job_portal/index.php/Login/signin>Click Here</a>';
$this->email->message($link);
print_r($get_email);
if($this->email->send())
{
echo "email sent";
}
else
{
echo "email failed";
}
}
}
$this->load->view('Requirements/requirements',$data);
}
Can anyone help me..
Thanks in advance..
What you need is the database helper function insert_id(), it returns the id of the last insert: https://www.codeigniter.com/userguide3/database/helpers.html?highlight=insert_id
Have your add_requirement function of the RequirementModel model return the insert_id like so:
return $this->db->insert_id();
Then just save that value when you call the function:
$insert_id = $this->RequirementModel->add_requirement($this->input->post());
In ZF2, I'm trying to generate a PDF using DOMPDFModule and email it using EmailZF2.
Here's what I'm doing in my controller:
// fetch data
$user = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
$address = $this->getEntityManager()->getRepository('Application\Entity\Addresses')->find(1);
// generate PDF
$pdf = new PdfModel();
$pdf->setOption('filename', 'Renter_application-report-' . date("Y_m_d"));
$pdf->setOption('paperSize', 'a4');
$pdf->setVariables(array(
'User' => $user,
'Address' => $address,
));
So far all good, however DOMPDFModule would require me to return $pdf to prompt the PDF generated, and none of the DOMPDF seemed to work (e.g. $pdf->render() or $pdf->output()).
I tried also to render the view myself unsuccessfully as follows (maybe some issue with headers generation?)
// Render PDF
$pdfView = new ViewModel($pdf);
$pdfView->setTerminal(true)
->setTemplate('Application/index/pdf')
->setVariables(array(
'User' => $user,
'Address' => $address,
));
$pdfOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($pdfView);
Lastly, the goal would be to get this rendered PDF and wither save it somewhere to be able to attach it or to attach it straight away - even as simple as
// Save PDF to disk
$file_to_save = '/path/to/pdf/file.pdf';
file_put_contents($file_to_save, $pdfOutput);
// Send Email
$view = new ViewModel(array(
'name' => $User->getName(),
));
$view->setTerminal(true);
$view->setTemplate('Application/view/emails/user');
$this->mailerZF2()->send(array(
'to' => $User->getEmail(),
'subject' => 'Test email'
), $view, $file_to_save);
Which I manage to make working by editing the file \src\EmailZF2\Controller\Plugin\Mailer.php with these lines to attach the PDF:
...
public function send($data = array(), $viewModel, $pdf)
...
if($pdf && file_exists($pdf)) {
$pdf = fopen($pdf, 'r');
$MessageAttachment = new MimePart($pdf);
$MessageAttachment->type = 'application/pdf';
$MessageAttachment->filename = 'output.pdf';
$MessageAttachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$MessageAttachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
}
...
$body_html = new MimeMessage();
$body_html->setParts(array($text, $html, $MessageAttachment));
Any help is appreciated, thank you! :)
I don't know if this id the right way, but I managed to make it working so I'll be posting how we did it in case somebody else will encounter the same issue.
I've used DOMPDFModule as base engine, and then in the controller, in the action that generates the PDF, I rendered the PDF through a Viewmodel to use the view scripts as templates
use Zend\View\Model\ViewModel,
DOMPDFModule\View\Model\PdfModel;
...
public function indexAction()
{
$User = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
// generate PDF
$pdf = new PdfModel();
$pdf->setOption('filename', 'user_details-' . date("Y_m_d"));
$pdf->setOption('paperSize', 'a4');
$pdf->setVariables(array(
'User' => $User,
));
// Render PDF
$pdfView = new ViewModel($pdf);
$pdfView->setTerminal(true)
->setTemplate('Application/index/pdf.phtml')
->setVariables(array(
'User' => $User,
));
$html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdfView);
$eng = $this->getServiceLocator()->get('viewpdfrenderer')->getEngine();
$eng->load_html($html);
$eng->render();
$pdfCode = $eng->output();
// Send the email
$mailer->sendEmail($User->getId(), $pdfCode);
}
The emailzf2 module has also been deprecated, and custom mailer module now manages the attachment and sending of emails. To do so, in Mailer/config/module.config.php a new service has been registered:
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
'service_manager' => array(
'factories' => array(
__NAMESPACE__ . '\Service\MailerService' => __NAMESPACE__ . '\Service\MailerServiceFactory',
),
),
Which references to the file Mailer/src/Mailer/Service/MailerServiceFactory.php:
<?php
namespace Mailer\Service;
use Mailer\Service\MailerService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MailerServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
$viewRenderer = $serviceLocator->get('ViewRenderer');
$config = $serviceLocator->get('config');
return new MailerService($entityManager, $viewRenderer, $config);
}
}
And Mailer/src/Mailer/Service/MailerService.php:
use Zend\Mime\Message as MimeMessage;
use Zend\View\Model\ViewModel;
class MailerService
{
protected $em;
protected $view;
protected $config;
protected $options;
protected $senderName;
protected $senderEmail;
public function __construct(\Doctrine\ORM\EntityManager $entityManager, $viewRenderer, $config)
{
$this->em = $entityManager;
$this->view = $viewRenderer;
$this->config = $config;
$this->options = array(
'name' => $config['mailer']['smtp_host'],
);
$this->senderName = $config['mailer']['sender']['from_name'];
$this->senderEmail = $config['mailer']['sender']['from_address'];
}
protected function send($fromAddress, $fromName, $toAddress, $toName, $subject, $bodyParts)
{
// setup SMTP options
$options = new Mail\Transport\SmtpOptions($this->options);
$mail = new Mail\Message();
$mail->setBody($bodyParts);
$mail->setFrom($fromAddress, $fromName);
$mail->setTo($toAddress, $toName);
$mail->setSubject($subject);
$transport = new Mail\Transport\Smtp($options);
$transport->send($mail);
}
protected function setBodyHtml($content, $pdf = null, $pdfFilename = null) {
$html = new MimePart($content);
$html->type = "text/html";
$body = new MimeMessage();
if ($pdf != '') {
$pdfAttach = new MimePart($pdf);
$pdfAttach->type = 'application/pdf';
$pdfAttach->filename = $pdfFilename;
$pdfAttach->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$pdfAttach->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
$body->setParts(array($html, $pdfAttach));
} else {
$body->setParts(array($html));
}
return $body;
}
public function sendEmail($UserId)
{
$User = $this->em->getRepository('Application\Entity\Users')->find($UserId);
$vars = array( 'firstname' => $User->getFirstname(),
'lastname' => $User->getLastname());
$content = $this->view->render('emails/user-profile', $vars);
$body = $this->setBodyHtml($content);
$sendToName = $User->getOaFirstname() .' '. $User->getLastname();
$this->send($this->senderEmail, $this->senderName, $User->getEmailAddress(), $sendToName, 'User profile', $body);
}
}