public function sendMail($parameters = array()) { $em = $this->container->get('doctrine')->getManager(); $mailer = $this->container->get('mailer'); $body = $this->container->get('templating'); $baseUrl = $this->container->get('router')->getContext()->getHost(); if ($this->mailSubject === NULL || $this->mailSubject === '') { throw new MissingOptionsException('El parámetro mailSubject (asunto del correo) no ha sido definido. mailSubject: ' . $this->mailSubject); } if ($this->mailFrom === NULL || $this->mailFrom === '') { $this->mailFrom = $this->container->getParameter('mailer_email'); if ($this->mailFrom === NULL || $this->mailFrom === '') { throw new ParameterNotFoundException('mail.service', 'mailer_email'); } } if ($this->mailTo === NULL || $this->mailTo === '') { throw new MissingOptionsException('El parámetro mailTo (correo destinatario) no ha sido definido: ' . $this->mailTo); } $parameters['baseurl'] = $baseUrl; $this->mailTemplate = $this->mailTemplate ? $this->mailTemplate : 'ApplicationCoreBundle:Mail:standardEmailLayout.html.twig'; $message = \Swift_Message::newInstance()->setSubject($this->mailSubject)->setFrom($this->mailFrom)->setTo($this->mailTo)->setBody($body->render($this->mailTemplate, $parameters), 'text/html'); $result = $mailer->send($message); if ($result == 0) { return false; } else { return true; } }
public function sendEmail() { $this->emailConfig = $this->getEmailConfiguration(); $this->setMailer(); $mailerObject = Swift_Mailer::newInstance($this->transport); #$mailerObject = sfContext::getInstance()->getMailer(); $message = Swift_Message::newInstance() ->setFrom($this->sender) ->setTo($this->receiver) ->setSubject($this->subject) ->setContentType($this->contentType) ->setBody($this->body); if(isset($this->attachments)) { foreach($this->attachments as $file) { $fileObj = new File(); $filecontent = $fileObj->getFileContent($file['filepath']); $message->attach(Swift_Attachment::newInstance($filecontent, $file['filename'])); } } try { if($this->emailConfig['allowemailtransport'] == 1) { $mailerObject->send($message); } } catch (Exception $e) { } }
public static function send() { $transport = \Swift_SmtpTransport::newInstance('smtp.mail.ru', 465, 'ssl')->setUsername('*****@*****.**')->setPassword(''); $mailer = \Swift_Mailer::newInstance($transport); $messages = \Swift_Message::newInstance('Wonderful Subject')->setFrom('*****@*****.**')->setTo(['*****@*****.**' => 'Работа'])->setContentType("text/html; charset=UTF-8")->setBody('Тестовое сообщение о БД', 'text/html'); $result = $mailer->send($messages); }
/** * Class constructor. * Load all data from configurations and generate the initial clases * to manage the email * * @param string Content type for message body. It usually text/plain or text/html. * Default is 'text/plain' but can be changed later */ public function __construct($content_type = 'text/plain') { $config = RMFunctions::configs(); $config_handler =& xoops_gethandler('config'); $xconfig = $config_handler->getConfigsByCat(XOOPS_CONF_MAILER); // Instantiate the Swit Transport according to our preferences // We can change this preferences later switch ($config['transport']) { case 'mail': $this->swTransport = Swift_MailTransport::newInstance(); break; case 'smtp': $this->swTransport = Swift_SmtpTransport::newInstance($config['smtp_server'], $config['smtp_port'], $config['smtp_crypt'] != 'none' ? $config['smtp_crypt'] : ''); $this->swTransport->setUsername($config['smtp_user']); $this->swTransport->setPassword($config['smtp_pass']); break; case 'sendmail': $this->swTransport = Swift_SendmailTransport::newInstance($config['sendmail_path']); break; } // Create the message object // Also this object could be change later with message() method $this->swMessage = Swift_Message::newInstance(); $this->swMessage->setReplyTo($xconfig['from']); $this->swMessage->setFrom(array($xconfig['from'] => $xconfig['fromname'])); $this->swMessage->setContentType($content_type); }
function __construct() { // include swift mailer require ENGINE_PATH . 'swiftmailer/classes/Swift.php'; Swift::init(); Swift::registerAutoload(); //Yii::import('system.vendors.swiftMailer.classes.Swift', true); //Yii::registerAutoloader(array('Swift','autoload')); require_once ENGINE_PATH . 'swiftmailer/swift_init.php'; //Yii::import('system.vendors.swiftMailer.swift_init', true); switch ($this->params['transportType']) { case 'smtp': $transport = Swift_SmtpTransport::newInstance($this->params['smtpServer'], $this->params['smtpPort'], $this->params['smtpSequre'])->setUsername($this->params['smtpUsername'])->setPassword($this->params['smtpPassword']); break; case 'sendmail': $transport = Swift_SendmailTransport::newInstance($this->params['sendmailCommand']); break; default: case 'mail': $transport = Swift_MailTransport::newInstance(); break; } $this->toEmail = 'noreplay@' . $_SERVER['HTTP_HOST']; $this->fromEmail = 'noreplay@' . $_SERVER['HTTP_HOST']; $this->path = "http://" . $_SERVER['HTTP_HOST'] . "/submit/mailtpl/"; $this->mailer = Swift_Mailer::newInstance($transport); $this->mes = Swift_Message::newInstance(); }
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { if ($request->request->has('_username')) { $username = $request->request->get('_username'); } else { $username = ''; } //if ($exception->getMessage() === 'Captcha is invalid') { //} else { $failedLoginIp = $request->getClientIp(); $user = $this->fosUM->findUserByUsername($username); if ($user) { $failedLogin = $user->getFailedLogin(); $failedLogin++; $user->setFailedLogin($failedLogin); $user->setFailedLoginIp($failedLoginIp); if ($failedLogin === 3) { //email do użytkownika i admina $message = \Swift_Message::newInstance()->setSubject('Nieautoryzowane próby dostępu do konta')->setFrom('*****@*****.**')->setTo(array('*****@*****.**', $user->getEmail()))->setBody($username . ' próbował zalogować się zbyt wiele razy z adresu IP: ' . $failedLoginIp . ' ' . $exception->getMessage()); $this->mailer->send($message); } if ($failedLogin === 5) { $user->setLocked(1); } $this->fosUM->updateUser($user); } //} $url = 'fos_user_security_login'; $response = new RedirectResponse($this->router->generate($url)); return $response; }
/** * {@inheritdoc} */ public function register(Application $app) { $app['email.support'] = '*****@*****.**'; $app['logger.message_generator'] = function () use($app) { $message = \Swift_Message::newInstance(); $message->setSubject('Error report from ' . $_SERVER['HTTP_HOST'])->setFrom($app['email.support'])->setTo($app['email.support']); return $message; }; $app['logger.swift_mailer_handler'] = $app->share(function ($app) { $handler = new SwiftMailerHandler($app['mailer'], $app['logger.message_generator'], Logger::DEBUG); $handler->setTransport($app['swiftmailer.transport']); return $handler; }); if (!$app['debug']) { if ($this->send_emails) { $app['monolog'] = $app->share($app->extend('monolog', function ($monolog, $app) { /** @var $monolog Logger */ $bufferHander = new BufferHandler($app['logger.swift_mailer_handler']); $fingersCrossedHandler = new FingersCrossedHandler($bufferHander, Logger::ERROR, 200); $monolog->pushHandler($fingersCrossedHandler); return $monolog; })); } } }
/** * Send email using swift api. * * @param $body * @param $recipients * @param $from * @param $subject */ public function sendEmail($body, $recipients, $from, $subject) { $config = Zend_Registry::get('config'); $failures = ''; Swift_Preferences::getInstance()->setCharset('UTF-8'); //Create the Transport $transport = Swift_SmtpTransport::newInstance($config->mail->server->name, $config->mail->server->port, $config->mail->server->security)->setUsername($config->mail->username)->setPassword($config->mail->password); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance(); $headers = $message->getHeaders(); $headers->addTextHeader("signed-by", Constant::EMAIL_DOMAIN); //Give the message a subject $message->setSubject($subject); //Set the From address with an associative array $message->setFrom($from); //Set the To addresses with an associative array $message->setTo($recipients); //Give it a body $message->setBody($body); $message->setContentType("text/html"); //Send the message $myresult = $mailer->batchSend($message); if ($myresult) { return null; } else { return Constant::EMAIL_FAIL_MESSAGE; } }
/** * Sends a message via email created by information given in the event. * * @param Event $event */ public function send(Event $event) { $subject = $this->varContainer->replace($this->subject); $body = $this->container->get('templating')->render('KoalamonNotificationBundle:Sender:EMail/email_' . $event->getStatus() . '.html.twig', $this->varContainer->getTemplateVariables()); $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom(['*****@*****.**' => 'KoalaAlert'])->setTo($this->emailAddresses)->setBody($body, 'text/html'); $this->container->get('mailer')->send($message); }
/** * Prepares the (swift) email and sends it. * * @return int * * @throws \Exception If subject or recpient (to) not specified */ public function swiftMessageInitializeAndSend(array $data = array()) { $swiftMessageInstance = \Swift_Message::newInstance(); if (!isset($data['subject'])) { throw new \Exception('You need to specify a subject'); } if (!isset($data['to'])) { throw new \Exception('You need to specify a recipient'); } $from = isset($data['from']) ? $data['from'] : $this->app['email']; $to = $data['to']; $swiftMessageInstance->setSubject($data['subject'])->setTo($to)->setFrom($from); if (isset($data['cc'])) { $swiftMessageInstance->setCc($data['cc']); } if (isset($data['bcc'])) { $swiftMessageInstance->setBcc($data['bcc']); } $templateData = array('app' => $this->app, 'user' => $this->app['user'], 'email' => $to, 'swiftMessage' => $swiftMessageInstance); if (isset($data['templateData'])) { $templateData = array_merge($templateData, $data['templateData']); } if (isset($data['body'])) { $bodyType = isset($data['bodyType']) ? $data['bodyType'] : 'text/html'; $isTwigTemplate = isset($data['contentIsTwigTemplate']) ? $data['contentIsTwigTemplate'] : true; $swiftMessageBody = $this->app['mailer.css_to_inline_styles_converter']($data['body'], $templateData, $isTwigTemplate); $swiftMessageInstance->setBody($swiftMessageBody, $bodyType); } return $this->app['mailer']->send($swiftMessageInstance); }
/** * * @param \Doctrine\ORM\Event\PostFlushEventArgs $args */ public function postFlush(Event\PostFlushEventArgs $args) { foreach ($this->inserted_entities as $entity) { if ($entity instanceof Post && $entity->getId() > 0) { $email = $entity->getTemplate()->getPostNotify(); if ($email) { if (!$this->servicesLoaded) { $this->loadServices(); } $post = []; foreach ($entity->getValueSet()->getValues() as $value) { $post[$value->getAttribute()->getDisplayName()] = []; if ($value instanceof OptionValue) { $post_value = []; foreach ($value->getOptions() as $option) { $post_value[] = $option->getDisplayName(); } } elseif ($value instanceof DateTimeValue) { $post_value = [date("m/d/Y", $value->getValue()->getTimestamp())]; } else { $post_value = [$value->getValue()]; } $post[$value->getAttribute()->getDisplayName()] = $post_value; } $txt_template = "OpiferCmsBundle:Email:post-notify.txt.twig"; $txt_body = $this->twig->render($txt_template, ['post' => $post]); $message = \Swift_Message::newInstance()->setSender($this->admin_email)->setFrom($this->admin_email)->setTo($email)->setBody($txt_body); $this->sendEmail($message); } } } }
public function createAction(request $request) { $em = $this->getDoctrine()->getManager(); //getting the content $content = $request->get('content'); //getting the user $user = $this->container->get('security.context')->getToken()->getUser(); //getting the video $video = $em->getRepository('BFSiteBundle:Video')->find($request->get('videoId')); $comment = new Comment(); $comment->setContent($content)->setVideo($video)->setDate(new \Datetime())->setUser($user); //we create a notification for the user of the video. $message = $user->getUsername() . ' a laissé un commentaire sur la vidéo: ' . $video->getTitle() . '.'; $link = $this->generateUrl('bf_site_video', array('code' => $video->getCode())); $service = $this->container->get('bf_site.notification'); $notification = $service->create($video->getUser(), $message, null, $link); $em->persist($comment); $em->persist($notification); $em->flush(); if ($video->getUser()->getMailComment() === true) { $message = \Swift_Message::newInstance()->setSubject($user->getUsername() . ' posted a new comment on your ' . $video->getTitle() . ' video')->setFrom('*****@*****.**')->setTo($video->getUser()->getEmail())->setBody($this->renderView('Emails/comment.html.twig', array('user' => $video->getUser(), 'commenter' => $user, 'video' => $video)), 'text/html'); $this->get('mailer')->send($message); } $this->addFlash('success', 'Your comment has been added.'); return new response(); }
function send($view = 'default', $subject = '') { // Create the message, and set the message subject. $message = & Swift_Message::newInstance(); $message->setSubject($subject); // Append the HTML and plain text bodies. $bodyHTML = $this->_getBodyHTML($view); $bodyText = $this->_getBodyText($view); $message->setBody($bodyText, "text/plain"); $message->addPart($bodyHTML, "text/html"); // Set the from address/name. $message->setFrom(array($this->from => $this->fromName)); // Create the recipient list. //$recipients =& new Swift_RecipientList(); $message->setTo(array($this->to => $this->toName)); $transport->setHost('smtp.googlemail.com'); $transport->setPort(465); $transport->setEncryption('tls'); $transport->setUsername('*****@*****.**'); $transport->setPassword('whatafind6186'); $mailer = Swift_Mailer::newInstance($transport); // Attempt to send the email. $result = $mailer->send($message); return $result; }
public function inscriptionAction(Request $request) { $user = new Utilisateur(); $user->setConfirmation(gencode(10)); // On crée le FormBuilder grâce à la méthode du contrôleur $formBuilder = $this->createFormBuilder($user); // On ajoute les champs de l'entité que l'on veut à notre formulaire $formBuilder->add('username', TextType::class, array('label' => 'Identifiant'))->add('password', RepeatedType::class, array('type' => PasswordType::class, 'invalid_message' => 'Les mots de passe doivent correspondre', 'options' => array('required' => true), 'first_options' => array('label' => 'Mot de passe'), 'second_options' => array('label' => 'Mot de passe (validation)')))->add('email', EmailType::class, array('label' => 'E-mail'))->add('fichierAvatar', VichImageType::class, array('required' => false, 'label' => 'Avatar'))->add('facebook', TextType::class, array('required' => false, 'label' => 'Facebook'))->add('twitter', TextType::class, array('required' => false, 'label' => 'Twitter'))->add('googlePlus', TextType::class, array('required' => false, 'label' => 'Google+'))->add('skype', TextType::class, array('required' => false, 'label' => 'Skype'))->add('nom', TextType::class, array('required' => false, 'label' => 'Nom'))->add('prenom', TextType::class, array('required' => false, 'label' => 'Nom'))->add('dateNaissance', DateType::class, array('required' => false, 'label' => 'Date de naissance', 'widget' => 'single_text', 'format' => 'dd MMMM y', 'attr' => array('class' => 'datepicker')))->add('nom', TextType::class, array('required' => false, 'label' => 'Prénom'))->add('adresse', TextType::class, array('required' => false, 'label' => 'Adresse'))->add('codePostal', TextType::class, array('required' => false, 'label' => 'Code postal'))->add('ville', TextType::class, array('required' => false, 'label' => 'Ville'))->add('telephone', TextType::class, array('required' => false, 'label' => 'Téléphone'))->add('acceptConditions', CheckboxType::class, array('required' => true, 'label' => 'J\'ai lu et j\'accepte les ', 'mapped' => false, 'attr' => array('class' => 'filled-in'))); // À partir du formBuilder, on génère le formulaire $form = $formBuilder->getForm(); // On fait le lien Requête <-> Formulaire // À partir de maintenant, la variable $user contient les valeurs entrées dans le formulaire par le visiteur $form->handleRequest($request); // On vérifie que les valeurs entrées sont correctes if ($form->isValid()) { // On encrypte le mot de passe $factory = $this->get('security.encoder_factory'); $encoder = $factory->getEncoder($user); $password = $encoder->encodePassword($user->getPassword(), $user->getSalt()); $user->setPassword($password); // On enregistre notre objet $user dans la base de données $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); $message = \Swift_Message::newInstance()->setSubject('[Gatsun Site] Confirmation de l\'inscription')->setFrom('*****@*****.**')->setTo($user->getEmail())->setBody($this->renderView('GatsunWebsiteBundle:Utilisateur:emailConfirmation.html.twig', array('utilisateur' => $user)), 'text/html'); $this->get('mailer')->send($message); // On redirige vers la page indiquant que le mail de confirmation vient d'être envoyé return $this->render('GatsunWebsiteBundle:Utilisateur:inscriptionTerminee.html.twig', array('utilisateur' => $user)); } // À ce stade : // - Soit la requête est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire // - Soit la requête est de type POST, mais le formulaire n'est pas valide, donc on l'affiche de nouveau // On passe la méthode createView() du formulaire à la vue afin qu'elle puisse afficher le formulaire toute seule return $this->render('GatsunWebsiteBundle:Utilisateur:inscription.html.twig', array('form' => $form->createView())); }
public function testAttachmentSending() { $mailer = $this->_getMailer(); $message = Swift_Message::newInstance('[Swift Mailer] HtmlWithAttachmentSmokeTest')->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Swift Mailer'))->setTo(SWIFT_SMOKE_EMAIL_ADDRESS)->attach(Swift_Attachment::fromPath($this->_attFile))->setBody('<p>This HTML-formatted message should contain an attached ZIP file (named "textfile.zip").' . PHP_EOL . 'When unzipped, the archive should produce a text file which reads:</p>' . PHP_EOL . '<p><q>This is part of a Swift Mailer v4 smoke test.</q></p>', 'text/html'); $this->assertEqual(1, $mailer->send($message), '%s: The smoke test should send a single message'); $this->_visualCheck('http://swiftmailer.org/smoke/4.0.0/html_with_attachment.jpg'); }
public function updateStatus(OrderEvent $event) { $order = $event->getOrder(); $colissimo = new Colissimo(); if ($order->isSent() && $order->getDeliveryModuleId() == $colissimo->getModuleModel()->getId()) { $contact_email = ConfigQuery::getStoreEmail(); if ($contact_email) { $message = MessageQuery::create()->filterByName('mail_colissimo')->findOne(); if (false === $message) { throw new \Exception("Failed to load message 'order_confirmation'."); } $order = $event->getOrder(); $customer = $order->getCustomer(); $this->parser->assign('customer_id', $customer->getId()); $this->parser->assign('order_ref', $order->getRef()); $this->parser->assign('order_date', $order->getCreatedAt()); $this->parser->assign('update_date', $order->getUpdatedAt()); $this->parser->assign('package', $order->getDeliveryRef()); $message->setLocale($order->getLang()->getLocale()); $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::getStoreName()); // Build subject and body $message->buildMessage($this->parser, $instance); $this->mailer->send($instance); Tlog::getInstance()->debug("Colissimo shipping message sent to customer " . $customer->getEmail()); } else { $customer = $order->getCustomer(); Tlog::getInstance()->debug("Colissimo shipping message no contact email customer_id", $customer->getId()); } } }
public function action_request() { $id = (int) base64_decode($this->request->param('id')); $friendship = false; if ($id && $id != $this->user->id) { $friendship = ORM::factory('Friends')->setFriendship($this->user->id, $id); } if ($friendship) { $to = ORM::factory('User')->where('id', '=', $id)->find(); // notify! if ($to->loaded() && $to->details->notify_friendship) { // SWIFTMAILER MAGIC $swc = (object) Kohana::$config->load('smtp.default'); $transport = Swift_SmtpTransport::newInstance($swc->host, $swc->port, $swc->ssl ? 'ssl' : null)->setUsername($swc->user)->setPassword($swc->password); $mailer = Swift_Mailer::newInstance($transport); $body = $swc->body_friendship; $body = str_replace('%TO%', $to->username, $body); $body = str_replace('%FROM%', $this->user->username, $body); $message = Swift_Message::newInstance(__($this->user->username . ' möchte dein Freund auf ' . $this->project_config->project_name . ' werden'))->setFrom($swc->from)->setTo(array($to->email))->setBody($body, 'text/html'); $result = $mailer->send($message); } $this->redirect('/user/show/' . ORM::factory('User')->getUsername($id)); } else { $this->redirect('/user/show/' . ORM::factory('User')->getUsername($id)); } }
public function indexAction(Request $request) { //mini formulaire d'abonnement $news = new Newsletter(); $form = $this->createFormBuilder($news)->add('news', 'email')->add('Envoyer', 'submit')->getForm(); $form->handleRequest($request); if ($form->isValid()) { $email = $news->getNews(); $message = \Swift_Message::newInstance()->setSubject('Bonjour')->setFrom($email)->setTo('*****@*****.**')->setBody('Bonjour Fabrice cet email : ' . $email . ' souhaite un abonnement à votre newsletter, cordialement'); $this->get('mailer')->send($message); return $this->redirect($this->generateUrl('front_homepage')); } $essais = $this->getCat('essais'); $arr = $this->get('front.base.service')->recupInfo(); $arr['essais'] = $essais; $arr['nav_accueil'] = ' '; $arr['nav_xix'] = ' '; $arr['nav_essais'] = 'active'; $arr['nav_litt'] = ' '; $arr['nav_audio'] = ' '; $arr['nav_video'] = ' '; $arr['nav_info'] = ' '; $arr['newsletter'] = $form->createView(); $response = new Response(); if ($this->getRequest()->isMethod('GET')) { $response->setPublic(); $response->setSharedMaxAge(1); $response->setVary(array('Accept-Encoding', 'User-Agent')); } return $this->render('FrontBundle:Essais:index.html.twig', $arr, $response); }
/** * Compose the email data to be sent. * * @param FormConfig $formConfig * @param EmailConfig $emailConfig * @param FormData $formData */ private function emailCompose(FormConfig $formConfig, EmailConfig $emailConfig, FormData $formData) { /* * Create message object */ $this->message = \Swift_Message::newInstance(); $this->message->setEncoder(\Swift_Encoding::get8BitEncoding()); // Set our Twig lookup path $this->addTwigPath(); // If the form has it's own templates defined, use those, else the globals. $templateSubject = $formConfig->getTemplates()->getSubject() ?: $this->config['templates']['subject']; $templateEmail = $formConfig->getTemplates()->getEmail() ?: $this->config['templates']['email']; $fieldmap = $this->config['fieldmap']['email']; /* * Subject */ $html = $this->app['render']->render($templateSubject, array($fieldmap['subject'] => $formConfig->getNotification()->getSubject(), $fieldmap['config'] => $emailConfig, $fieldmap['data'] => $formData)); $subject = new \Twig_Markup($html, 'UTF-8'); /* * Body */ $html = $this->app['render']->render($templateEmail, array($fieldmap['fields'] => $formConfig->getFields(), $fieldmap['config'] => $emailConfig, $fieldmap['data'] => $this->getBodyData($emailConfig, $formData))); $body = new \Twig_Markup($html, 'UTF-8'); $text = preg_replace('/<style\\b[^>]*>(.*?)<\\/style>/s', '', $body); /* * Build email */ $this->message->setSubject($subject)->setBody(strip_tags($text))->addPart($body, 'text/html'); }
public function InviteAction(Request $request) { $invitation = new Invitation(); $form = $this->createForm(SendInvitationType::class, $invitation); if ($form->handleRequest($request)->isValid()) { // If email already existe, resend the same code. if ($result = $this->getDoctrine()->getRepository('USTAUserBundle:Invitation')->findOneByEmail($invitation->getEmail())) { $result->setFirstname($invitation->getFirstname())->setLastname($invitation->getLastname())->setDate($invitation->getDate()); $invitation = $result; } // send the invitation $message = \Swift_Message::newInstance()->setSubject('[UStA] Code d\'activation')->setFrom('*****@*****.**')->setTo($invitation->getEmail())->setBody($this->renderView('USTAUserBundle:Registration:inviteEMAIL.html.twig', array('invitation' => $invitation)), 'text/html'); $this->get('mailer')->send($message); // On dit que le mail a était envoyé et on enregistre dans la base de donnée $invitation->send(); $em = $this->getDoctrine()->getManager(); $em->persist($invitation); $em->flush(); $this->addFlash('success', "L'invitation de <strong>" . $invitation->getLastname() . " " . $invitation->getFirstname() . " (" . $invitation->getEmail() . ")</strong> a été envoyé avec succés !"); if ($this->get('kernel')->getEnvironment() == "dev") { $this->addFlash('info', "<strong>[ " . $this->get('kernel')->getEnvironment() . " ]</strong> code : <strong>" . $invitation->getCode() . "</strong>"); } $invitation = new Invitation(); $form = $this->createForm(SendInvitationType::class, $invitation); } $allInvitationOrderByDate = $this->getDoctrine()->getRepository('USTAUserBundle:Invitation')->getAllInvitationOrderByDate(); return $this->render('USTAUserBundle:Registration:invite.html.twig', array('form' => $form->createView(), 'invitations' => $allInvitationOrderByDate)); }
/** * @param NotificationMessageInterface $message * * @return NotificationInterface */ public function createEmailNotification(NotificationMessageInterface $message) { $swiftMessage = \Swift_Message::newInstance(); $from = [$this->settings->get('email.from_address') => $this->settings->get('email.from_name')]; $swiftMessage->setFrom($from); $swiftMessage->setSubject($message->getSubject($this->translator)); foreach ($message->getUsers() as $user) { $swiftMessage->addTo($user->getEmail(), $user->getUsername()); } $format = (string) $this->settings->get('email.format'); switch ($format) { case 'html': $swiftMessage->setBody($message->getHtmlContent($this->templating), 'text/html'); break; case 'text': $swiftMessage->setBody($message->getTextContent($this->templating), 'text/plain'); break; case 'both': $swiftMessage->setBody($message->getHtmlContent($this->templating), 'text/html'); $swiftMessage->addPart($message->getTextContent($this->templating), 'text/plain'); break; default: throw new UnexpectedFormatException($format); } return new SwiftMailerNotification($swiftMessage); }
public function notifyAction() { $id = 1; $settings = R::load('settings', $id); $time_before = c::now()->modify('+' . $settings->time_before)->toDateString(); $transport = \Swift_SmtpTransport::newInstance($settings->mail_host, $settings->mail_port)->setUsername($settings->mail_username)->setPassword($settings->mail_password); $mailer = \Swift_Mailer::newInstance($transport); $client = new \Services_Twilio($settings->twilio_sid, $settings->twilio_token); $recepients = R::findAll('recepients'); $events = R::find("events", "is_enabled = 1 AND date = '{$time_before}'"); foreach ($events as $event) { foreach ($recepients as $recepient) { $subject = preg_replace(array('/{title}/', '/{date}/'), array($event->title, $event->date), $settings->subject); $end_date = c::parse($event->date)->modify('+' . $event->days . ' days')->toDateString(); $body_patterns = array('/{name}/', '/{title}/', '/{start_date}/', '/<!(\\w+) ({\\w+})>/'); $body_replacements = array($settings->name, $event->title, $event->date, "\$1 {$end_date}"); if ($event->days == 1) { $body_replacements[3] = ''; } $body = preg_replace($body_patterns, $body_replacements, $settings->msg_template); if ($recepient->email && $settings->mail_username && $settings->mail_password) { $message = \Swift_Message::newInstance()->setSubject($subject)->setBody($body)->setFrom(array($settings->email => $settings->name))->setTo(array($recepient->email => $recepient->name)); try { $response = $mailer->send($message); } catch (\Exception $e) { //todo: log error } } else { if ($recepient->phone_number && $settings->twilio_sid && $settings->twilio_token && $settings->twilio_phonenumber) { $message = $client->account->messages->sendMessage($settings->twilio_phonenumber, $recepient->phone_number, $body); } } } } }
public function mail($to, $template, $context = array()) { $config = $this->container->get('gitonomy_core.config'); $templating = $this->container->get('templating'); // Transform $to in an array(email => name) if ($to instanceof User) { if (!$to->hasDefaultEmail()) { throw new \RuntimeException('Can\'t send a mail to user ' . $to->getUsername() . ': no mail'); } $to = array($to->getDefaultEmail()->getEmail() => $to->getFullname()); } elseif ($to instanceof Email) { $to = array($to->getEmail() => $to->getUser()->getFullname()); } else { throw new \RuntimeException('Unexpected type of recipient: ' . gettype($to)); } $template = $templating->loadTemplate($template); $subject = $this->renderTwigBlock($template, 'subject', $context); $bodyText = $this->renderTwigBlock($template, 'body_text', $context); $bodyHtml = $this->renderTwigBlock($template, 'body_html', $context); $fromEmail = $config->get('mailer_from_email'); $fromName = $config->get('mailer_from_name'); $message = \Swift_Message::newInstance()->setSubject($subject)->setBody($bodyText, 'text/plain')->addPart($bodyHtml, 'text/html')->setFrom(array($fromEmail => $fromName))->setTo($to); $swiftmailer = SwiftmailerFactory::createFromConfig($config); $swiftmailer->send($message); }
/** * Checks if we are the payment module for the order, and if the order is paid, * then send a confirmation email to the customer. * * @params OrderEvent $order */ public function update_status(OrderEvent $event) { $payzen = new Payzen(); if ($event->getOrder()->isPaid() && $payzen->isPaymentModuleFor($event->getOrder())) { $contact_email = ConfigQuery::read('store_email', false); Tlog::getInstance()->debug("Sending confirmation email from store contact e-mail {$contact_email}"); if ($contact_email) { $message = MessageQuery::create()->filterByName(Payzen::CONFIRMATION_MESSAGE_NAME)->findOne(); if (false === $message) { throw new \Exception(sprintf("Failed to load message '%s'.", Payzen::CONFIRMATION_MESSAGE_NAME)); } $order = $event->getOrder(); $customer = $order->getCustomer(); $this->parser->assign('order_id', $order->getId()); $this->parser->assign('order_ref', $order->getRef()); $message->setLocale($order->getLang()->getLocale()); $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name')); // Build subject and body $message->buildMessage($this->parser, $instance); $this->getMailer()->send($instance); Tlog::getInstance()->debug("Confirmation email sent to customer " . $customer->getEmail()); } } else { Tlog::getInstance()->debug("No confirmation email sent (order not paid, or not the proper payement module."); } }
protected function execute(InputInterface $input, OutputInterface $output) { //generacion xlsx $em = $this->getContainer()->get('doctrine')->getManager(); $emailDara = $em->getRepository('BackendBundle:EmailList')->findOneByName('Email Dara'); $researches = $em->getRepository('BackendBundle:Research')->programationUnsendedToDara(); $date = date("d-M-Y h:i:s"); if (count($researches) == 0) { $output->writeln($date . ": No hay programaciones para este periodo"); } else { try { $this->generateProgramacionXLSX($researches); } catch (Exception $e) { $output->writeln($e->getMessage()); return $e->getMessage(); } $output->writeln($date . ": Programacion generada"); //enviar por email $today = date("d-M-Y"); $filename = "Programacion_" . $today; $path = $this->getContainer()->get('kernel')->getRootDir() . "/../web/Programaciones/"; $message = \Swift_Message::newInstance()->setSubject('Programación de Cursos IPre')->setFrom('*****@*****.**')->setTo(array($emailDara->getEmail()))->setBody("Hola, adjuntamos la programación de cursos de este mes, saludos, \nGestión IPre")->attach(\Swift_Attachment::fromPath($path . $filename . ".xlsx")); $this->getContainer()->get('mailer')->send($message); $output->writeln($date . ": Programacion enviada"); // seteamos los estados como programacion envada a dara foreach ($researches as $research) { $research->getApplication()->setState(4); $em->flush(); } } }
function createEmail($to, $subject, $body, $isHtml) { $email_config = getConfig("_email"); loadSwiftMailer(); $message = Swift_Message::newInstance(); $message->setSubject($subject); // Set the From and To address with a string or associative array //'*****@*****.**' or array('*****@*****.**' => 'Your Name')); $from = @$email_config["from"] ? array($email_config["username"] => $email_config["from"]) : $email_config["username"]; $message->setFrom($from); $message->setTo($to); // Give it a body $contentType = $isHtml ? 'text/html' : 'text/plain'; if (!$isHtml) { $body = strip_tags($body); } $message->setBody($body, $contentType); // And optionally an alternative body // Add alternative parts with addPart() if ($isHtml) { $textBody = strip_tags($body); debug("createEmail textBody", $textBody); $message->addPart($textBody, 'text/plain'); } return $message; }
/** * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response * @throws AccessDeniedException */ public function createAction() { /** @var Admin $user */ $user = $this->container->get('security.context')->getToken()->getUser(); if (!$user->getPermissions()['teacher']['create']) { throw new AccessDeniedException("No tienes permisos suficientes"); } /** @var \Symfony\Component\HttpFoundation\Request $request */ $request = $this->container->get('request'); $teacher = new Teacher(); /** @var \Symfony\Component\Form\Form $form */ $form = $this->createForm(new TeacherType(), $teacher); $form->handleRequest($request); if ($form->isValid()) { $teacher->setUserName($teacher->getEmail()); /** @var string $activationRoute */ $activationRoute = Teacher::generateActivationRoute(); $teacher->setActivationRoute($activationRoute); $teacher->setActive(false); /** @var \Doctrine\Common\Persistence\ObjectManager $em */ $em = $this->getDoctrine()->getManager(); $em->persist($teacher); $this->get('session')->getFlashBag()->add('info', 'Los datos del profesor se han creado correctamente'); /** @var \Ufuturelabs\Ufuturedesk\MainBundle\Entity\School $school */ $school = $em->getRepository('MainBundle:School')->findSchool()[0]; $txt = $this->render("TeacherBundle:Email:activation.txt.twig", array("school" => $school, "teacher" => $teacher, "host" => "http://" . $_SERVER['HTTP_HOST'])); $html = $this->render("TeacherBundle:Email:activation.html.twig", array("school" => $school, "teacher" => $teacher, "host" => "http://" . $_SERVER['HTTP_HOST'])); $activationMessage = \Swift_Message::newInstance()->setSubject("Bienvenido a uFutureDesk (" . $school->getName() . ")")->setFrom(array($school->getEmail() => $school->getName() . " - uFutureDesk"))->setTo($teacher->getEmail())->setBody($txt)->addPart($html, 'text/html'); $em->flush(); $this->container->get('mailer')->send($activationMessage); return $this->redirect($this->generateUrl('admin_teacher_view', array('id' => $teacher->getId()))); } return $this->render("AdminBundle:Teacher:create.html.twig", array("teacherForm" => $form->createView())); }
/** * Sends e-mails based on predefined templates. If the $body param * has value, the template will be ignored. * * @param array $to * @param string $subject * @param string $name Template name * @param array $params * @param array $body */ public function send($to, $subject, $name = null, $params = null, $body = null) { // Create the message $message = \Swift_Message::newInstance(); //Settings $mailSettings = $this->config->mail; //Images if (isset($params['images'])) { $this->images = $params['images']; } if (null === $body) { $template = $this->getTemplate($message, $name, $params); } else { $template = $this->insertImages($message, $body); } // Setting message params $message->setSubject($subject)->setTo($to)->setFrom(array($mailSettings->fromEmail => $mailSettings->fromName))->setBody($template, 'text/html'); // Check attachments to add foreach ($this->attachments as $file) { $message->attach(\Swift_Attachment::newInstance()->setBody($file['content'])->setFilename($file['name'])->setContentType($file['type'])); } if (!$this->_transport) { $this->_transport = \Swift_SmtpTransport::newInstance($mailSettings->smtp->server, $mailSettings->smtp->port, $mailSettings->smtp->security)->setUsername($mailSettings->smtp->username)->setPassword($mailSettings->smtp->password); } // Create the Mailer using your created Transport $mailer = \Swift_Mailer::newInstance($this->_transport); $result = $mailer->send($message); $this->attachments = array(); return $result; }
/** * Constructor * * @return void */ public function __construct() { // create mailer object $this->mailer = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\Mailer'); // create message object $this->message = \Swift_Message::newInstance(); }
/** * Send a message * * @param string $subject * @param string $body */ public function send($subject, $body) { if ($this->mailer) { $message = \Swift_Message::newInstance($subject)->setBody($body)->addTo($this->to)->setFrom($this->from)->attach(\Swift_Attachment::fromPath($this->logPath)->setDisposition('inline')); $this->mailer->send($message); } }