protected function setupEmail(Email $email) { $this->sendgridEmail = new \SendGrid\Email(); foreach ($email->to() as $e => $n) { $this->sendgridEmail->addTo($e, $n); } foreach ($email->cc() as $e => $n) { $this->sendgridEmail->addCc($e, $n); } foreach ($email->bcc() as $e => $n) { $this->sendgridEmail->addBcc($e, $n); } foreach ($email->from() as $e => $n) { $this->sendgridEmail->setFrom($e); $this->sendgridEmail->setFromName($n); } $this->sendgridEmail->setSubject($email->subject()); $this->sendgridEmail->setText($email->message(Email::MESSAGE_TEXT)); $this->sendgridEmail->setHtml($email->message(Email::MESSAGE_HTML)); if ($email->attachments()) { foreach ($email->attachments() as $attachment) { $this->sendgridEmail->setAttachment($attachment['file'], $attachment['custom_filename']); } } }
/** * Test required fields * * @return void */ public function testMissingRequiredFields() { $this->setExpectedException('BadMethodCallException'); $this->SparkPostTransport->config($this->validConfig); $email = new Email(); $email->transport($this->SparkPostTransport); $email->to('*****@*****.**')->subject('This is test subject')->emailFormat('text')->send('Testing Maingun'); }
/** * mailer method * * @param array $data Dados para formar o email. * @return boolean True ou False. */ public function mailer($data, $template, $subject) { $email = new Email(); $email->transport('mailSgl'); $email->emailFormat('html'); $email->template($template); $email->from('*****@*****.**', 'SGL'); $email->to($data['email'], $data['nome']); $email->viewVars($data); $email->subject($subject); $email->send(); }
/** * TestSend method * * @return void */ public function testSendWithEmail() { $config = ['transport' => 'queue', 'charset' => 'utf-8', 'headerCharset' => 'utf-8']; $this->QueueTransport->config($config); $Email = new Email($config); $Email->from('*****@*****.**', 'CakePHP Test'); $Email->to('*****@*****.**', 'CakePHP'); $Email->cc(['*****@*****.**' => 'Mark Story', '*****@*****.**' => 'Juan Basso']); $Email->bcc('*****@*****.**'); $Email->subject('Testing Message'); $Email->attachments(['wow.txt' => ['data' => 'much wow!', 'mimetype' => 'text/plain', 'contentId' => 'important']]); $Email->template('test_template', 'test_layout'); $Email->subject("L'utilisateur n'a pas pu être enregistré"); $Email->replyTo('*****@*****.**'); $Email->readReceipt('*****@*****.**'); $Email->returnPath('*****@*****.**'); $Email->domain('cakephp.org'); $Email->theme('EuroTheme'); $Email->emailFormat('both'); $Email->set('var1', 1); $Email->set('var2', 2); $result = $this->QueueTransport->send($Email); $this->assertEquals('Email', $result['jobtype']); $this->assertTrue(strlen($result['data']) < 10000); $output = unserialize($result['data']); $emailReconstructed = new Email($config); foreach ($output['settings'] as $method => $setting) { call_user_func_array([$emailReconstructed, $method], (array) $setting); } $this->assertEquals($emailReconstructed->from(), $Email->from()); $this->assertEquals($emailReconstructed->to(), $Email->to()); $this->assertEquals($emailReconstructed->cc(), $Email->cc()); $this->assertEquals($emailReconstructed->bcc(), $Email->bcc()); $this->assertEquals($emailReconstructed->subject(), $Email->subject()); $this->assertEquals($emailReconstructed->charset(), $Email->charset()); $this->assertEquals($emailReconstructed->headerCharset(), $Email->headerCharset()); $this->assertEquals($emailReconstructed->emailFormat(), $Email->emailFormat()); $this->assertEquals($emailReconstructed->replyTo(), $Email->replyTo()); $this->assertEquals($emailReconstructed->readReceipt(), $Email->readReceipt()); $this->assertEquals($emailReconstructed->returnPath(), $Email->returnPath()); $this->assertEquals($emailReconstructed->messageId(), $Email->messageId()); $this->assertEquals($emailReconstructed->domain(), $Email->domain()); $this->assertEquals($emailReconstructed->theme(), $Email->theme()); $this->assertEquals($emailReconstructed->profile(), $Email->profile()); $this->assertEquals($emailReconstructed->viewVars(), $Email->viewVars()); $this->assertEquals($emailReconstructed->template(), $Email->template()); //for now cannot be done 'data' is base64_encode on set but not decoded when get from $email //$this->assertEquals($emailReconstructed->attachments(),$Email->attachments()); //debug($output); //$this->assertEquals($Email, $output['settings']); }
/** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { $correo = $this->Correos->newEntity(); if ($this->request->is('post')) { $correo = $this->Correos->patchEntity($correo, $this->request->data); $email = new Email('default'); $email->to($this->request->data('destinario'))->subject($this->request->data('asunto'))->send($this->request->data('mensaje')); if ($this->Correos->save($correo)) { $this->Flash->success(__('The correo has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The correo could not be saved. Please, try again.')); } } $this->set(compact('correo')); $this->set('_serialize', ['correo']); }
/** * TestSend method * * @return void */ public function testSendWithEmail() { $Email = new Email(); $Email->from('*****@*****.**', 'CakePHP Test'); $Email->to('*****@*****.**', 'CakePHP'); $Email->cc(['*****@*****.**' => 'Mark Story', '*****@*****.**' => 'Juan Basso']); $Email->bcc('*****@*****.**'); $Email->subject('Testing Message'); $Email->transport('queue'); $config = $Email->config('default'); $this->QueueTransport->config($config); $result = $this->QueueTransport->send($Email); $this->assertEquals('Email', $result['job_type']); $this->assertTrue(strlen($result['data']) < 10000); $output = json_decode($result['data'], true); $this->assertEquals('Testing Message', $output['settings']['_subject']); }
/** * Send an activation link to user email * @param $user */ public function _sendActivationEmail(Entity $user, $url = '/register/active/') { $ActivationKeys = TableRegistry::get('Users.ActivationKeys'); $activationKeyEntity = $ActivationKeys->newEntity(); $activationKeyEntity->user_id = $user->id; do { $activationKeyEntity->activation_key = Text::uuid(); } while (!$ActivationKeys->save($activationKeyEntity)); //send email with activation key $activationUrl = Router::url($url . $activationKeyEntity->activation_key, true); $email = new Email('default'); // $email->transport(); $email->emailFormat('html'); $email->viewVars(compact('activationUrl')); $email->helpers(['Html']); $email->to($user->username); return $email; }
public function sendNewMissionsToInterestedUsers($nbrDays = 7) { $created = Time::now()->subDays($nbrDays); $missions = $this->Missions->find('all', ['conditions' => ['Missions.created >=' => $created]])->toArray(); $newMissions = []; foreach ($missions as $mission) { $users = $this->Users->find('all')->toArray(); foreach ($users as $user) { $usersTypeMissions = $this->UsersTypeMissions->findByUserId($user['id'])->toArray(); foreach ($usersTypeMissions as $userTypeMissions) { // Check if the current mission has the same type has the current userType mission if ($userTypeMissions['type_mission_id'] == $mission['type_mission_id']) { // Add a new mission to the list of missions to send if (isset($newMissions[$user['email']])) { $newMission = []; $newMission['link'] = Router::url(['controller' => 'Missions', 'action' => 'view', $mission['id']]); $newMission['name'] = $mission['name']; //print("Mission " . $newMission['name'] . " added to user " . $user['email'] . "\n"); array_push($newMissions[$user['email']], $newMission); } else { //print("Creating mission list for user " . $user['email'] . "\n"); $newMissions[$user['email']] = []; $newMission = []; $newMission['link'] = Router::url(['controller' => 'Missions', 'action' => 'view', $mission['id']]); $newMission['name'] = $mission['name']; //print("Mission " . $newMission['name'] . " added to user " . $user['email'] . "\n"); array_push($newMissions[$user['email']], $newMission); } } } } } // For each user send their associated list of missions foreach ($newMissions as $userEmail => $missionsToSend) { $email = new Email(); $email->domain('maisonlogiciellibre.org'); $email->to($userEmail); $email->subject('New missions available at ML2'); $email->template('new_missions'); $email->emailFormat('both'); $email->viewVars(['missions' => $missionsToSend]); $email->send(); } }
/** * Send mail * * @param \Cake\Mailer\Email $email Email * @return array */ public function send(Email $email) { if (!empty($this->_config['queue'])) { $this->_config = $this->_config['queue'] + $this->_config; $email->config((array) $this->_config['queue'] + ['queue' => []]); unset($this->_config['queue']); } $settings = ['from' => [$email->from()], 'to' => [$email->to()], 'cc' => [$email->cc()], 'bcc' => [$email->bcc()], 'charset' => [$email->charset()], 'replyTo' => [$email->replyTo()], 'readReceipt' => [$email->readReceipt()], 'returnPath' => [$email->returnPath()], 'messageId' => [$email->messageId()], 'domain' => [$email->domain()], 'getHeaders' => [$email->getHeaders()], 'headerCharset' => [$email->headerCharset()], 'theme' => [$email->theme()], 'profile' => [$email->profile()], 'emailFormat' => [$email->emailFormat()], 'subject' => method_exists($email, 'getOriginalSubject') ? [$email->getOriginalSubject()] : [$email->subject()], 'transport' => [$this->_config['transport']], 'attachments' => [$email->attachments()], 'template' => $email->template(), 'viewVars' => [$email->viewVars()]]; foreach ($settings as $setting => $value) { if (array_key_exists(0, $value) && ($value[0] === null || $value[0] === [])) { unset($settings[$setting]); } } $QueuedJobs = $this->getQueuedJobsModel(); $result = $QueuedJobs->createJob('Email', ['settings' => $settings]); $result['headers'] = ''; $result['message'] = ''; return $result; }
/** * Send notification * * @param \CvoTechnologies\Notifier\Notification $notification Notification instance. * @return array */ public function send(Notification $notification) { $email = new Email(); $email->profile($this->config('profile')); $email->to($notification->to(null, static::TYPE)); $email->subject($notification->title()); $email->viewBuilder()->templatePath($notification->viewBuilder()->templatePath()); $email->viewBuilder()->template($notification->viewBuilder()->template()); $email->viewBuilder()->plugin($notification->viewBuilder()->plugin()); $email->viewBuilder()->theme($notification->viewBuilder()->theme()); $email->viewBuilder()->layout($notification->viewBuilder()->layout()); $email->viewBuilder()->autoLayout($notification->viewBuilder()->autoLayout()); $email->viewBuilder()->layoutPath($notification->viewBuilder()->layoutPath()); $email->viewBuilder()->name($notification->viewBuilder()->name()); $email->viewBuilder()->className($notification->viewBuilder()->className()); $email->viewBuilder()->options($notification->viewBuilder()->options()); $email->viewBuilder()->helpers($notification->viewBuilder()->helpers()); $email->viewVars($notification->viewVars()); return $email->send(); }
/** * Send mail via SparkPost REST API * * @param \Cake\Mailer\Email $email Email message * @return array */ public function send(Email $email) { // Load SparkPost configuration settings $apiKey = $this->config('apiKey'); // Set up HTTP request adapter $adapter = new CakeHttpAdapter(new Client()); // Create SparkPost API accessor $sparkpost = new SparkPost($adapter, ['key' => $apiKey]); // Pre-process CakePHP email object fields $from = (array) $email->from(); $sender = sprintf('%s <%s>', mb_encode_mimeheader(array_values($from)[0]), array_keys($from)[0]); $to = (array) $email->to(); $recipients = [['address' => ['name' => mb_encode_mimeheader(array_values($to)[0]), 'email' => array_keys($to)[0]]]]; // Build message to send $message = ['from' => $sender, 'html' => empty($email->message('html')) ? $email->message('text') : $email->message('html'), 'text' => $email->message('text'), 'subject' => mb_decode_mimeheader($email->subject()), 'recipients' => $recipients]; // Send message try { $sparkpost->transmission->send($message); } catch (APIResponseException $e) { // TODO: Determine if BRE is the best exception type throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)', $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription())); } }
/** * Sends an email with a link that can be used in the next * 24 hours to give the user access to /users/resetPassword * * @param int $userId User ID * @return array */ public function sendPasswordResetEmail($userId) { $timestamp = time(); $usersTable = TableRegistry::get('Users'); $hash = $usersTable->getPasswordResetHash($userId, $timestamp); $resetUrl = Router::url(['prefix' => false, 'controller' => 'Users', 'action' => 'resetPassword', $userId, $timestamp, $hash], true); $email = new Email('reset_password'); $user = $usersTable->get($userId); $email->to($user->email); $email->viewVars(compact('user', 'resetUrl')); return $email->send(); }
/** * testGetLastResponse method * * @return void */ public function testGetLastResponse() { $this->assertEmpty($this->SmtpTransport->getLastResponse()); $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true)); $this->socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n")); $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n"); $this->socket->expects($this->at(3))->method('read')->will($this->returnValue(false)); $this->socket->expects($this->at(4))->method('read')->will($this->returnValue("250-PIPELINING\r\n")); $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250-SIZE 102400000\r\n")); $this->socket->expects($this->at(6))->method('read')->will($this->returnValue("250-VRFY\r\n")); $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("250-ETRN\r\n")); $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250-STARTTLS\r\n")); $this->socket->expects($this->at(9))->method('read')->will($this->returnValue("250-AUTH PLAIN LOGIN\r\n")); $this->socket->expects($this->at(10))->method('read')->will($this->returnValue("250-AUTH=PLAIN LOGIN\r\n")); $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250-ENHANCEDSTATUSCODES\r\n")); $this->socket->expects($this->at(12))->method('read')->will($this->returnValue("250-8BITMIME\r\n")); $this->socket->expects($this->at(13))->method('read')->will($this->returnValue("250 DSN\r\n")); $this->SmtpTransport->connect(); $expected = [['code' => '250', 'message' => 'PIPELINING'], ['code' => '250', 'message' => 'SIZE 102400000'], ['code' => '250', 'message' => 'VRFY'], ['code' => '250', 'message' => 'ETRN'], ['code' => '250', 'message' => 'STARTTLS'], ['code' => '250', 'message' => 'AUTH PLAIN LOGIN'], ['code' => '250', 'message' => 'AUTH=PLAIN LOGIN'], ['code' => '250', 'message' => 'ENHANCEDSTATUSCODES'], ['code' => '250', 'message' => '8BITMIME'], ['code' => '250', 'message' => 'DSN']]; $result = $this->SmtpTransport->getLastResponse(); $this->assertEquals($expected, $result); $email = new Email(); $email->from('*****@*****.**', 'CakePHP Test'); $email->to('*****@*****.**', 'CakePHP'); $this->socket->expects($this->at(0))->method('write')->with("MAIL FROM:<*****@*****.**>\r\n"); $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false)); $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("250 OK\r\n")); $this->socket->expects($this->at(3))->method('write')->with("RCPT TO:<*****@*****.**>\r\n"); $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false)); $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n")); $this->SmtpTransport->sendRcpt($email); $expected = [['code' => '250', 'message' => 'OK']]; $result = $this->SmtpTransport->getLastResponse(); $this->assertEquals($expected, $result); }
/** * Send emails * * @param string $template * @param array $data * @param string $config * @throws SocketException if mail could not be sent */ public function send($data = [], $template = 'default', $config = 'default') { // initialize class $email = new Email($config); // to? if (isset($data['to'])) { $email->to($data['to']); } // brand $from = $email->from(); $brand = reset($from); // subject? $subject = isset($data['subject']) ? $data['subject'] : $email->subject(); $email->subject(trim($config == 'debug' ? $brand . ' report: ' . $subject : $subject . ' - ' . $brand)); // template? $email->template($template); // data & send $email->viewVars(['subject' => $subject, 'form' => isset($data['form']) ? $data['form'] : [], 'brand' => $brand, 'info' => ['ip' => $this->request->clientIP(), 'useragent' => env('HTTP_USER_AGENT'), 'date' => strftime('%d.%m.%Y %H:%M')]])->send(); }
/** * Builds an instance of the Email object with some default settings applied * from the model data. * * @return \Cake\Mailer\Email */ private function getEmailInstance() { $email = new Email(); $email->to($this->email)->viewVars(['key' => $this->personal_key])->emailFormat('both'); return $email; }
/** * sendmail method * Send Email using postmark addon * @param string|null $id Word id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function sendmail($email, $subject, $mailText) { $mail = "mail"; $loginuser = $this->Auth->user(); $data = []; $data = ['mailFrom' => '*****@*****.**', 'email' => $email, 'mailSubject' => $subject, 'mailText' => $mailText]; $email = new Email('default'); $email->from(['*****@*****.**' => 'Word Master']); $email->to($data['email']); $email->subject($data['mailSubject']); $email->send($data['mailText']); $this->set('result', $data); }
public function registerLecturer() { $user = $this->Users->newEntity(); if ($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->data); $user->username = $user->email; $user->role_id = 3; $user->enable = false; if ($this->endsWith($user->email, '@vanlanguni.edu.vn')) { if ($this->Users->save($user)) { $this->Flash->success(__('You are registered successfully.')); $hash = Security::hash('vlucanteen' . $user->id . $user->username); $email = new Email('default'); $email->to($user->email, $user->full_name)->from('*****@*****.**', 'VLUCanteen')->subject('VLUCanteen: Bạn đã đăng ký thành công')->send("Bạn đã đăng ký thành công. Bạn có thể đăng nhập bằng tài khoản đã đăng ký.\n\n" . "Trân trọng,\n\nVLUCanteen"); return $this->redirect(['action' => 'login']); } else { $this->Flash->error(__('You are not registered successfully.')); } } else { $this->Flash->error(__('Invalid email.')); } } $faculties = $this->Users->Faculties->find('list'); $roles = $this->Users->Roles->find('list'); $this->set(compact('user', 'faculties', 'roles')); }
/** * @param mixed $charset * @param mixed $headerCharset * @return \Cake\Mailer\Email */ protected function _getEmailByNewStyleCharset($charset, $headerCharset) { $email = new Email(['transport' => 'debug']); if (!empty($charset)) { $email->charset($charset); } if (!empty($headerCharset)) { $email->headerCharset($headerCharset); } $email->from('*****@*****.**', 'どこかの誰か'); $email->to('*****@*****.**', 'どこかのどなたか'); $email->cc('*****@*****.**', 'ミク'); $email->subject('テストメール'); $email->send('テストメールの本文'); return $email; }
/** * sendCalendarReminder method * Notification about the reminder is sent only * when the record belonds to anyone. * @param Cake\Event $event from the afterSave * @param Cake\Datasource\EntityInterface $entity from the afterSave * @return array|bool $sent on whether the email was sent */ public function sendCalendarReminder(Event $event, EntityInterface $entity) { $sent = false; $currentUser = null; //get applications's timezone $timezone = Time::now()->format('e'); $dtz = new \DateTimeZone($timezone); $table = $event->subject(); //get attendees Table for the event if (method_exists($table, 'getConfig') && is_callable([$table, 'getConfig'])) { $config = $table->getConfig(); $remindersTo = $table->getTableAllowRemindersField(); } // skip if attendees Table is not defined if (empty($remindersTo)) { return $sent; } // Figure out which field is a reminder one $reminderField = $table->getReminderFields(); if (empty($reminderField) || !is_array($reminderField)) { return $sent; } $reminderField = $reminderField[0]; if (!is_array($reminderField) || empty($reminderField['name'])) { return $sent; } $reminderField = $reminderField['name']; // Skip sending email if reminder field is empty if (empty($entity->{$reminderField})) { return $sent; } $attendeesFields = $this->_getAttendeesFields($table, ['tables' => $remindersTo]); // skip if no attendees fields found if (empty($attendeesFields)) { return $sent; } // skip if none of the required fields was modified $requiredFields = array_merge((array) $reminderField, $attendeesFields); if (!$this->_requiredFieldsModified($entity, $requiredFields)) { return $sent; } /* * Figure out the subject of the email * * This should happen AFTER the `$table->getConfig()` call, * in case the display field of the table is changed from the * configuration. * * Use singular of the table name and the value of the entity's display field. * For example: "Call: Payment remind" or "Lead: Qobo Ltd". */ $fhf = new FieldHandlerFactory(); $emailSubjectValue = $fhf->renderValue($table, $table->displayField(), $entity->{$table->displayField()}, ['renderAs' => 'plain']); $eventSubject = $emailSubjectValue ?: 'reminder'; $emailSubject = Inflector::singularize($table->alias()) . ": " . $eventSubject; $emailContent = Inflector::singularize($table->alias()) . " information was "; // If the record is being updated, prefix the above subject with "(Updated) ". if (!$entity->isNew()) { $emailSubject = '(Updated) ' . $emailSubject; $emailContent .= "updated"; } else { $emailContent .= "created"; } $emails = $this->_getAttendees($table, $entity, $attendeesFields); if (empty($emails)) { return $sent; } if (method_exists($table, 'getCurrentUser') && is_callable([$table, 'getCurrentUser'])) { $currentUser = $table->getCurrentUser(); $emailContent .= " by " . $currentUser['email']; } // append changelog if entity is not new if (!$entity->isNew()) { $emailContent .= "\n\n" . $this->_getChangelog($entity); } foreach ($emails as $email) { $vCalendar = new \Eluceo\iCal\Component\Calendar('//EN//'); $vAttendees = $this->_getEventAttendees($emails); $vEvent = $this->_getCalendarEvent($entity, ['dtz' => $dtz, 'organizer' => $email, 'subject' => $emailSubject, 'attendees' => $vAttendees, 'field' => $reminderField, 'timezone' => $timezone]); $vEvent->setAttendees($vAttendees); $vCalendar->addComponent($vEvent); $headers = "Content-Type: text/calendar; charset=utf-8"; $headers .= 'Content-Disposition: attachment; filename="event.ics"'; $emailer = new Email('default'); $emailer->to($email)->setHeaders([$headers])->subject($emailSubject)->attachments(['event.ics' => ['contentDisposition' => true, 'mimetype' => 'text/calendar', 'data' => $vCalendar->render()]]); $sent = $emailer->send($emailContent); } return $sent; }
/** * Prepares the recipient email addresses. * * @param \Cake\Mailer\Email $email Email instance * @return array */ protected function _prepareRecipientAddresses($email) { $to = $email->to(); $cc = $email->cc(); $bcc = $email->bcc(); return array_merge(array_keys($to), array_keys($cc), array_keys($bcc)); }
public function answer($postId) { $answer = $this->Posts->newEntity(['type' => 'answer', 'parent_post_id' => $postId]); $post = $this->Posts->get($postId, ['contain' => ['Users']]); if ($this->request->is('post')) { $answer = $this->Posts->patchEntity($answer, $this->request->data); if ($this->Posts->save($answer)) { $email = new Email(); $email->to($post->user->email)->template('answered', 'default')->emailFormat('html')->subject("Your question has been answered")->viewVars(['post' => $post])->send(); return $this->redirect(['controller' => 'posts', 'action' => 'view', $postId]); } else { $this->Flash->error("Failed to save your answer, please try again"); $this->set(compact('post', 'answer')); $this->render('view'); } } return $this->redirect(['action' => 'view', $postId]); }