newInstance() публичный статический Метод

Create a new Attachment.
public static newInstance ( string | Swift_OutputByteStream $data = null, string $filename = null, string $contentType = null ) : Swift_Mime_Attachment
$data string | Swift_OutputByteStream
$filename string
$contentType string
Результат Swift_Mime_Attachment
 public function testSend()
 {
     $message = new Swift_Message();
     $message->setFrom('*****@*****.**', 'Johnny #5');
     $message->setSubject('Is alive!');
     $message->addTo('*****@*****.**', 'A. Friend');
     $message->addTo('*****@*****.**');
     $message->addCc('*****@*****.**');
     $message->addCc('*****@*****.**', 'Extra 2');
     $message->addBcc('*****@*****.**');
     $message->addBcc('*****@*****.**', 'Extra 4');
     $message->addPart('<q>Help me Rhonda</q>', 'text/html');
     $message->addPart('Doo-wah-ditty.', 'text/plain');
     $attachment = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
     $attachment2 = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
     $attachment2->setDisposition('inline');
     $message->attach($attachment);
     $message->attach($attachment2);
     $message->setPriority(1);
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-PM-Tag', 'movie-quotes');
     $messageId = $headers->get('Message-ID')->getId();
     $transport = new PostmarkTransportStub('TESTING_SERVER');
     $client = $this->getMock('GuzzleHttp\\Client', array('request'));
     $transport->setHttpClient($client);
     $o = PHP_OS;
     $v = phpversion();
     $client->expects($this->once())->method('request')->with($this->equalTo('POST'), $this->equalTo('https://api.postmarkapp.com/email'), $this->equalTo(['headers' => ['X-Postmark-Server-Token' => 'TESTING_SERVER', 'User-Agent' => "swiftmailer-postmark (PHP Version: {$v}, OS: {$o})", 'Content-Type' => 'application/json'], 'json' => ['From' => '"Johnny #5" <*****@*****.**>', 'To' => '"A. Friend" <*****@*****.**>,you+two@example.com', 'Cc' => 'another+1@example.com,"Extra 2" <*****@*****.**>', 'Bcc' => 'another+3@example.com,"Extra 4" <*****@*****.**>', 'Subject' => 'Is alive!', 'Tag' => 'movie-quotes', 'TextBody' => 'Doo-wah-ditty.', 'HtmlBody' => '<q>Help me Rhonda</q>', 'Headers' => [['Name' => 'Message-ID', 'Value' => '<' . $messageId . '>'], ['Name' => 'X-PM-KeepID', 'Value' => 'true'], ['Name' => 'X-Priority', 'Value' => '1 (Highest)']], 'Attachments' => [['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt'], ['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt', 'ContentID' => 'cid:' . $attachment2->getId()]]]]));
     $transport->send($message);
 }
Пример #2
0
 public function postUpdate(LifecycleEventArgs $args)
 {
     $entity = $args->getEntity();
     $this->mailer = $this->container->get('mailer');
     $this->mailerHelper = $this->container->get('stfalcon_event.mailer_helper');
     $this->pdfGeneratorHelper = $this->container->get('stfalcon_event.pdf_generator.helper');
     if ($entity instanceof Payment) {
         if ($entity->getStatus() === Payment::STATUS_PAID) {
             $tickets = $this->container->get('doctrine')->getManager()->getRepository('StfalconEventBundle:Ticket')->getAllTicketsByPayment($entity);
             /** @var Ticket $ticket */
             foreach ($tickets as $ticket) {
                 /** @var $user User */
                 $user = $ticket->getUser();
                 /** @var Event $event */
                 $event = $ticket->getEvent();
                 $successPaymentTemplateContent = $this->mailerHelper->renderTwigTemplate('StfalconEventBundle:Interkassa:_mail.html.twig', ['user' => $user, 'event' => $event]);
                 $mail = new Mail();
                 $mail->addEvent($event);
                 $mail->setText($successPaymentTemplateContent);
                 $html = $this->pdfGeneratorHelper->generateHTML($ticket);
                 $message = $this->mailerHelper->formatMessage($user, $mail);
                 $message->setSubject($event->getName())->attach(\Swift_Attachment::newInstance($this->pdfGeneratorHelper->generatePdfFile($ticket, $html), $ticket->generatePdfFilename()));
                 $this->mailer->send($message);
             }
         }
     }
 }
 /**
  * Méthode d'envoie d'email
  *
  * @param array $data
  * @param array|array<UserInterface> $aEmailTo
  * @param array $aAttachement
  */
 protected function send($data, $aEmailTo, $aAttachement = array(), MailParametersInterface $mailParameters)
 {
     $mailerForSend = $this->mailer;
     foreach ($aEmailTo as $user) {
         //Create the message
         /* @var $message \Swift_Message */
         $message = \Swift_Message::newInstance()->setSubject($data['objet'])->setFrom(array($this->config['from_email']['address'] => $this->config['from_email']['sender_name']));
         foreach ($aAttachement as $oneAttachment) {
             $attachment = \Swift_Attachment::newInstance($oneAttachment['content'], $oneAttachment['name'], $oneAttachment['type']);
             $message->attach($attachment);
         }
         $failedRecipients = array();
         $numSent = 0;
         if (is_object($user) && method_exists($user, 'getEmail')) {
             $message->setTo($user->getEmail());
         } elseif (is_string($user)) {
             $message->setTo($user);
         } else {
             throw new \RuntimeException('Invalid email');
         }
         $message->setBody($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.html.twig', $data), "text/html");
         $message->addPart($this->templating->render($this->getTemplateDirectory($mailParameters) . ':Mails:' . $data['template'] . '.txt.twig', $this->getRaw($data)), "text/plain");
         $numSent += $mailerForSend->send($message, $failedRecipients);
         if ($this->logger && $this->config['active_log'] === true) {
             $this->logger->info(sprintf("Email: '%s' sended to: '%s'", $data['objet'], current(array_keys($message->getTo()))), array('CnertaMailingBundle', 'email-sended'));
         }
     }
     return $numSent;
 }
Пример #4
0
 public function createParticipation($user, $drink)
 {
     $dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
     $dEndDrink = clone $dDrink;
     $dEndDrink->modify('+3 hours');
     $dateFormat = 'Ymd\\THis';
     $icsInvite = \Swift_Attachment::newInstance()->setContentType('text/calendar;charset=UTF-8;method=REQUEST')->setBody($this->twig->render('drink/invite_ics.twig', array('user' => $user, 'drink' => $drink, 'datetimes' => array('start' => $dDrink->format($dateFormat), 'end' => $dEndDrink->format($dateFormat), 'current' => date($dateFormat)))))->setEncoder(\Swift_Encoding::getQpEncoding());
     return $this->mailer->createMessage()->setSubject('[Aperophp.net] Inscription à un ' . $drink['kind'])->setFrom(array('*****@*****.**'))->setTo(array($user['email']))->setBody($this->twig->render('drink/participation_mail.html.twig', array('user' => $user, 'drink' => $drink)), 'text/html')->attach($icsInvite);
 }
Пример #5
0
 public function send($to, $subject, $body, $from = null, $cc = null, $attachmentData = [])
 {
     $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($from ?: $this->from)->setTo($to)->setBody($body)->setContentType('text/html');
     if (isset($attachmentData['filename']) && isset($attachmentData['contentType']) && isset($attachmentData['data'])) {
         $attachment = \Swift_Attachment::newInstance($attachmentData['data'], $attachmentData['filename'], $attachmentData['contentType']);
         $message->attach($attachment);
     }
     // set carbon copy
     if ($cc) {
         $message->setCc($cc);
     }
     $this->mailer->send($message);
 }
Пример #6
0
 /**
  * Email the CSV to the given recipients.
  *
  * @param $recipients
  *
  * @return array|string array of recipients or ; delimited list
  */
 public function emailCsvFile($recipients)
 {
     if (!is_array($recipients)) {
         $recipients = explode(';', $recipients);
     }
     $csv = $this->pendingApplicationsCSV();
     $message = Yii::app()->mailer->newMessage();
     $message->setFrom(array('*****@*****.**' => 'OpenEyes Reports'));
     $message->setTo($recipients);
     $message->setSubject('Pending Therapy Applications Report');
     $message->setBody('Your report on currently pending Therapy Applications');
     $message->attach(Swift_Attachment::newInstance($csv, 'PendingApplications.csv', 'text/csv'));
     return Yii::app()->mailer->sendMessage($message);
 }
 /**
  * @Template("TestBundle:Event:index.html.twig")
  */
 public function indexAction()
 {
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('EntityBundle:Orders')->findOrdersAll();
     $html = $this->renderView('TestBundle:Event:index.html.twig');
     $pdfgenerator = $this->get('knp_snappy.pdf');
     $file = $pdfgenerator->getOutputFromHtml($html);
     $attachment = \Swift_Attachment::newInstance($file, 'my-file.pdf', 'application/pdf');
     $customer = new Customer();
     $customer->setName('Radumta Sitepu');
     $customer->setEmail('*****@*****.**');
     $message = \Swift_Message::newInstance()->setSubject('Hello Email')->setFrom('*****@*****.**')->setTo('*****@*****.**')->setBody($this->renderView('TestBundle:Event:index.html.twig'))->attach($attachment);
     $this->get('mailer')->send($message);
     return array();
 }
Пример #8
0
 public function sendMail(OrderInterface $order)
 {
     $body = $this->render($this->template, ['order' => $order, 'translationDomain' => $this->translationDomain]);
     $attach = \Swift_Attachment::newInstance();
     $attach->setFilename('bill.pdf');
     $attach->setContentType('application/pdf');
     $attach->setBody($this->getBillingGenerator()->generate($order));
     $message = $this->createMessage();
     $message->addFrom($this->from);
     $message->setSubject($this->getTranslator()->trans($this->subject, [], $this->translationDomain));
     $message->addTo($order->getCustomerEmail());
     $message->setBody($body, 'text/html');
     $message->attach($attach);
     $this->send($message);
 }
Пример #9
0
 public static function send($template_name, $vars)
 {
     $transport = Config::get('mailer.transport');
     $mailer = Swift_Mailer::newInstance($transport);
     $message = Swift_Message::newInstance();
     $message->setFrom(array('*****@*****.**' => 'SOW Composer'));
     if ($template_name == "SOW_COMPLETED") {
         $sow = Sow::find($vars["sow_id"]);
         $attachment = Swift_Attachment::newInstance()->setFilename($sow->title . '.doc')->setContentType('application/msword')->setBody(View::make('partials.doc')->with('sow', $sow));
         $message->setSubject("Here's your completed SOW, \"{$sow->title}\"")->setTo(array($sow->author_email))->addPart(View::make('mailer.sow_completed_text')->with('sow', $sow), 'text/plain')->setBody(View::make('mailer.sow_completed_html')->with('sow', $sow), 'text/html')->attach($attachment);
     } else {
         throw new Exception("Couldn't find the SowMailer template that you requested.");
     }
     $mailer->send($message);
 }
 public function sendEmail($from, $to, $cc, $subject, $body, $attachmentFilename)
 {
     $this->assertNotNull($this->mailer, 'Set provider first via haveMailProvider');
     $message = \Swift_Message::newInstance($subject, $body, 'text/plain');
     $message->addFrom($from);
     $message->addTo($to);
     $message->addPart("<p>{$body}</p>", 'text/html');
     $message->attach(\Swift_Attachment::newInstance($body, $attachmentFilename, 'application/octet-stream'));
     if (is_array($cc)) {
         $message->setCc($cc);
     } else {
         $message->addCc($cc);
     }
     $this->mailer->send($message);
     $this->debugSection('SmtpMailer', $subject . ' ' . $from . ' -> ' . $to);
 }
Пример #11
0
 public function testHTMLPartAppearsLastEvenWhenAttachmentsAdded()
 {
     $message = Swift_Message::newInstance();
     $message->setCharset('utf-8');
     $message->setSubject('test subject');
     $message->addPart('plain part', 'text/plain');
     $attachment = Swift_Attachment::newInstance('<data>', 'images.gif', 'images/gif');
     $message->attach($attachment);
     $message->setBody('HTML part', 'text/html');
     $message->setTo(array('*****@*****.**' => 'User'));
     $message->setFrom(array('*****@*****.**' => 'Other'));
     $message->setSender(array('*****@*****.**' => 'Other'));
     $id = $message->getId();
     $date = preg_quote(date('r', $message->getDate()), '~');
     $boundary = $message->getBoundary();
     $this->assertRegExp('~^' . 'Sender: Other <*****@*****.**>' . "\r\n" . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: Other <*****@*****.**>' . "\r\n" . 'To: User <*****@*****.**>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: multipart/mixed;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/alternative;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/plain; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'plain part' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'HTML part' . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: images/gif; name=images.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: attachment; filename=images.gif' . "\r\n" . "\r\n" . preg_quote(base64_encode('<data>'), '~') . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString());
 }
Пример #12
0
 /**
  * Send an email to the team after step failed with error message, screen, and generated html.
  *
  * @AfterStep
  */
 public function dumpInfoAfterFailedStep(AfterStepScope $scope)
 {
     if ($scope->getTestResult()->getResultCode() === StepResult::FAILED && null !== $this->getScenario($scope)) {
         $error = nl2br($scope->getStep()->getText()) . '<br /><br /><b style="color: red">Failed with message : ' . $scope->getTestResult()->getException()->getMessage() . '</b><br />';
         $message = \Swift_Message::newInstance()->setFrom('*****@*****.**')->setTo('*****@*****.**')->setSubject('Error on scenario: ' . $this->getScenario($scope)->getTitle());
         if ($this->minkContext->getSession()->getDriver() instanceof \Behat\Mink\Driver\Selenium2Driver) {
             $screenshot = $this->minkContext->getSession()->getDriver()->getScreenshot();
             $message->attach(\Swift_Attachment::newInstance($screenshot, 'screenshot.png', 'image/png'));
         }
         $error .= '<br /><br />Driver: "' . get_class($this->minkContext->getSession()->getDriver()) . '"';
         $message->attach(\Swift_Attachment::newInstance($this->minkContext->getSession()->getPage()->getHtml(), 'page.html', 'text/html'));
         $message->setBody('<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>' . $error . '</body></html>', 'text/html');
         $transport = \Swift_SmtpTransport::newInstance('smtp.mailgun.org', 587)->setUsername('*****@*****.**')->setPassword($this->getSmtpPassword());
         $mailer = \Swift_Mailer::newInstance($transport);
         $mailer->send($message);
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $lock = new LockHandler('app:sendcoupons');
     if (!$lock->lock()) {
         $output->writeln('The command is already running in another process.');
         return 0;
     }
     $em = $this->getContainer()->get('doctrine')->getManager();
     $repo = $em->getRepository('AppBundle\\Entity\\Customer');
     $customers = $repo->findBy(['isActivated' => true, 'couponsHaveBeenSent' => false], ['datetimeActivation' => 'ASC'], 100);
     foreach ($customers as $customer) {
         $mapped = $this->getContainer()->get('couponmapper')->mapNToCustomer(6, $customer);
         if (!$mapped) {
             $output->writeln('Could not map coupon codes to customer ' . $customer->getId());
             $lock->release();
             return 1;
         }
         $couponcodesData = [];
         foreach ($customer->getCouponcodes() as $couponcode) {
             ob_start();
             @QRcode::png($couponcode->getCode());
             $imageData = ob_get_contents();
             ob_end_clean();
             $couponcodesData[] = base64_encode($imageData);
         }
         $useRemoteFont = true;
         if ($this->getContainer()->get('kernel')->getEnvironment() === 'test') {
             $useRemoteFont = false;
             // This decouples test runs from Internet connectivity
         }
         $pdfData = $this->getContainer()->get('knp_snappy.pdf')->getOutputFromHtml($this->getContainer()->get('templating')->render('AppBundle:coupons:index.html.twig', array('customer' => $customer, 'couponcodesData' => $couponcodesData, 'useRemoteFont' => $useRemoteFont)));
         if ($this->getContainer()->get('kernel')->getEnvironment() === 'dev') {
             file_put_contents('/var/tmp/coupon.pdf', $pdfData);
         }
         $fileLocator = $this->getContainer()->get('file_locator');
         $brandsPdfPath = $fileLocator->locate('@AppBundle/Resources/other/Marken_Selbst_Vertragspartner_2015_09_24.pdf');
         $message = \Swift_Message::newInstance()->setSubject('Ihre Rabattcodes für die Good Buy METRO Sonderaktion')->setFrom('*****@*****.**')->setTo($customer->getEmail())->setBody($this->getContainer()->get('templating')->render('Emails/couponCodes.html.twig', ['customer' => $customer]), 'text/html')->attach(\Swift_Attachment::newInstance($pdfData, 'Goodbye-Metro-Rabattcodes.pdf', 'application/pdf'))->attach(\Swift_Attachment::fromPath($brandsPdfPath, 'application/pdf'));
         $this->getContainer()->get('mailer')->send($message);
         $customer->setCouponsHaveBeenSent(true);
         $em->flush();
         $output->writeln($customer->getEmail());
     }
     $lock->release();
 }
Пример #14
0
 /**
  * {@inheritdoc}
  */
 public function notify(NotificationInterface $notification)
 {
     if (!class_exists('Swift_Message')) {
         throw new \RuntimeException('You need to install swift mailer to use mailgun transport');
     }
     /** @var Email $notification */
     $message = \Swift_Message::newInstance($notification->getSubject())->setFrom($notification->getFrom());
     foreach ($notification->getParts() as $part) {
         $message->attach(\Swift_MimePart::newInstance($part->getContent(), $part->getContentType()));
     }
     foreach ($notification->getAttachments() as $attachment) {
         $message->attach(\Swift_Attachment::newInstance($attachment->getContent(), $attachment->getName(), $attachment->getContentType()));
     }
     $postData = ['o:tag' => $notification->getTags()];
     foreach ($notification->getMetadata() as $key => $value) {
         $postData['v:' . $key] = $value;
     }
     if ($recipientVariables = $notification->getRecipientVariables()) {
         $postData['recipient-variables'] = json_encode($recipientVariables);
     }
     $failed = [];
     $success = [];
     $to = array_merge(array_values($notification->getTo()), array_values($notification->getCc()), array_values($notification->getBcc()));
     if (!empty($to)) {
         foreach (array_chunk($to, 1000) as $to_chunk) {
             $result = new Result('mailgun', $this->getName());
             $data = $postData;
             $data['to'] = $to_chunk;
             $res = $this->mailgun->sendMessage($this->domain, $data, $message->toString());
             if ($res->http_response_code == 200) {
                 $success[] = $res;
             } else {
                 $result->setResult(Result::FAIL);
                 $failed[] = $res;
             }
             $result->setResponse($res);
             $notification->addResult($result);
         }
         if (count($success) === 0) {
             throw new NotificationFailedException("Sending failed for message {$notification->getSubject()}", $failed);
         }
     }
 }
Пример #15
0
 /**
  * Здесь мы получаем уведомления о статусе платежа и отмечаем платеж как успешный (или не отмечаем)
  * Также рассылаем письма и билеты всем, кто был привязан к платежу
  *
  * @Route("/payment/interaction", name="payment_interaction")
  * @Template()
  *
  * @param Request $request
  *
  * @return array
  */
 public function interactionAction(Request $request)
 {
     /** @var Payment $payment */
     $payment = $this->getDoctrine()->getRepository('StfalconPaymentBundle:Payment')->findOneBy(array('id' => $request->get('ik_pm_no')));
     if (!$payment) {
         throw new Exception('Платеж №' . $request->get('ik_pm_no') . ' не найден!');
     }
     // @var InterkassaService $interkassa
     $interkassa = $this->container->get('stfalcon_event.interkassa.service');
     if ($payment->isPending() && 1) {
         //$interkassa->checkPayment($payment, $request)) {
         $payment->markedAsPaid();
         $em = $this->getDoctrine()->getManager();
         $em->flush();
         /** @var Ticket  $ticket */
         foreach ($payment->getTickets() as $ticket) {
             // розсилка квитків
             // @todo тут має смикатись сервіс який розсилає мильники про успішну оплату квитків + пдф в аттачі
             $user = $ticket->getUser();
             $event = $ticket->getEvent();
             $twig = $this->get('twig');
             // @todo ачуметь.. екшн в одному бандлі. вьюшка в іншому
             $successPaymentTemplateContent = $twig->loadTemplate('StfalconEventBundle:Interkassa:success_payment.html.twig')->render(array('event_slug' => $event->getSlug()));
             $mail = new Mail();
             $mail->addEvent($event);
             $mail->setText($successPaymentTemplateContent);
             // Get base template for email
             $emailTemplateContent = $twig->loadTemplate('StfalconEventBundle::email.html.twig');
             $dateFormatter = new \IntlDateFormatter('ru-RU', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, 'd MMMM Y');
             $text = $mail->replace(array('%fullname%' => $user->getFullName(), '%event%' => $event->getName(), '%date%' => $dateFormatter->format($event->getDate()), '%place%' => $event->getPlace()));
             $body = $emailTemplateContent->render(array('text' => $text, 'mail' => $mail, 'add_bottom_padding' => true));
             /** @var $pdfGen \Stfalcon\Bundle\EventBundle\Helper\PdfGeneratorHelper */
             $pdfGen = $this->get('stfalcon_event.pdf_generator.helper');
             $html = $pdfGen->generateHTML($ticket);
             $outputFile = 'ticket-' . $event->getSlug() . '.pdf';
             $message = \Swift_Message::newInstance()->setSubject($event->getName())->setFrom('*****@*****.**', 'Frameworks Days')->setTo($user->getEmail())->setBody($body, 'text/html')->attach(\Swift_Attachment::newInstance($pdfGen->generatePdfFile($html, $outputFile), $outputFile));
             $this->get('mailer')->send($message);
         }
         return new Response('SUCCESS', 200);
     }
     return new Response('FAIL', 400);
 }
Пример #16
0
 /**
  * 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)
 {
     //Settings
     $mailSettings = $this->config->mail;
     $template = $body ? $body : $this->getTemplate($name, $params);
     // Create the message
     $message = Message::newInstance()->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 = Smtp::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;
 }
Пример #17
0
 /**
  * Adds an attachment to the message.
  *
  * @param string $data Binary or string
  * @param string $mimetype Mime type of the attachment (e.g. "text/plain", "application/octet-stream", etc.)
  * @param string|null $filename Name of the attached file (or null if inline disposition is used)
  * @param string $disposition Type of the disposition ("attachment" or "inline")
  * @return \Aimeos\MW\Mail\Message\Iface Message object
  */
 public function addAttachment($data, $mimetype, $filename, $disposition = 'attachment')
 {
     $part = \Swift_Attachment::newInstance($data, $filename, $mimetype);
     $part->setDisposition($disposition);
     $this->object->attach($part);
     return $this;
 }
 /**
  * Invoked immediately before the Message is sent.
  *
  * @param \Swift_Events_SendEvent $sendEvent
  * @param \Swift_Events_SendEvent $sendEvent
  */
 public function beforeSendPerformed(\Swift_Events_SendEvent $sendEvent)
 {
     /** @var \Swift_Message $message */
     $message = $sendEvent->getMessage();
     $this->restoreMessage($message);
     $to = array_keys($message->getTo());
     $address = array_shift($to);
     if ($replacements = $this->getReplacementsFor($address)) {
         foreach ($replacements as $attachment) {
             if (is_array($attachment)) {
                 if (!isset($attachment['type'])) {
                     $attachment['type'] = null;
                 }
                 $attachment = \Swift_Attachment::newInstance($attachment['data'], $attachment['filename'], $attachment['type']);
             }
             $this->attachments[] = $attachment;
             $message->attach($attachment);
         }
     }
 }
Пример #19
0
 public function _attach($data = NULL, $filename = '', $filetype = 'text/html', $contentid = false)
 {
     if (isset($this->theme)) {
         $theme = explode('/', $this->theme);
         $theme = $theme[0];
         $path = $this->path . $theme . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $filename;
         if (file_get_contents($this->path . $theme . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $filename)) {
             $attach = Swift_Attachment::fromPath($path, $filetype);
             if ($contentid) {
                 $attach->getHeaders()->addTextHeader('Content-ID', $contentid);
             }
             $this->mes->attach($attach);
         } elseif ($data !== NULL) {
             $attach = Swift_Attachment::newInstance($data, $filename, $filetype);
             if ($contentid) {
                 $attach->getHeaders()->addTextHeader('Content-ID', $contentid);
             }
             $this->mes->attach($attach);
         }
     }
 }
Пример #20
0
 protected function getTicketMail($ticketFile, $booking, $customer)
 {
     $attach = \Swift_Attachment::newInstance()->setFilename('tickets-' . $booking->id . '.pdf')->setContentType('application/pdf')->setBody($ticketFile);
     $msg = \Swift_Message::newInstance()->setSubject('MTSoc Online Ticket Purchase: Tickets Attached')->setFrom(['*****@*****.**' => 'ICU MTSoc Ticketing System'])->setTo([$customer->email => $booking->name])->setBody($this->getTextEmail($booking, $customer), 'text/plain')->attach($attach);
     return $msg;
 }
 protected function _createAttachment()
 {
     return Swift_Attachment::newInstance();
 }
Пример #22
0
 /**
  * Attach content to be sent as a file.
  *
  * @param   binary  file contents
  * @param   string  file name
  * @param   string  mime type
  * @return  Email
  */
 public function attach_content($data, $file, $mime = NULL)
 {
     if (!$mime) {
         // Get the mime type from the filename
         $mime = File::mime_by_ext(pathinfo($file, PATHINFO_EXTENSION));
     }
     $this->_message->attach(Swift_Attachment::newInstance($data, $file, $mime));
     return $this;
 }
Пример #23
0
 /**
  * Attach a file from a string
  *
  * @param string $strContent  The file content
  * @param string $strFilename The file name
  * @param string $strMime     The MIME type (defaults to "application/octet-stream")
  */
 public function attachFileFromString($strContent, $strFilename, $strMime = 'application/octet-stream')
 {
     $this->objMessage->attach(\Swift_Attachment::newInstance($strContent, $strFilename, $strMime));
 }
Пример #24
0
$doc = $parts[1];
$patch = $_POST['patch'];
if ($patch) {
    require_once 'lib/swift_required.php';
    $msg = $_POST['msg'];
    $nick = $_POST['nick'];
    $to = '*****@*****.**';
    $subject = 'Patch: ' . $doc;
    // TODO: only append document name?
    $message = "By: {$nick}\n\nMessage:\n{$msg}";
    // Create the Transport.
    $transport = Swift_MailTransport::newInstance();
    // Create the Mailer using your created Transport.
    $mailer = Swift_Mailer::newInstance($transport);
    // Create a message.
    $message = Swift_Message::newInstance($subject)->setFrom(array('*****@*****.**' => 'PatchPad'))->setTo(array($to))->setBody($message)->attach(Swift_Attachment::newInstance($patch, 'a.patch', 'text/x-diff'));
    //Send the message
    $result = $mailer->send($message);
    // $result = $mailer->batchSend($message);
    echo $result;
    die;
    // Obsolete:
    //   $headers = "From: patchpad@councilofexmuslims.com";
    //   $success = mail($to, $subject, $message, $headers);
}
// $cache_life in seconds.
// if (!file_exists($cache_file) or (time() - filemtime($cache_file) >= $cache_life))
function fetch_from_web($fname, $clear_cache)
{
    /// Returns true if the file should be fetched from the web.
    return !file_exists($fname) or $clear_cache;
Пример #25
0
 /**
  * Emails a report given a TO address, a subject, and a message
  */
 public static function emailReport()
 {
     if (!isset($_REQUEST['email']) || !filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
         echo json_encode(array('error' => 'Valid email address required'));
         return;
     }
     if (!isset($_REQUEST['url'])) {
         echo json_encode(array('error' => 'Report url required'));
         return;
     }
     if (!isset(PhpReports::$config['mail_settings']['enabled']) || !PhpReports::$config['mail_settings']['enabled']) {
         echo json_encode(array('error' => 'Email is disabled on this server'));
         return;
     }
     if (!isset(PhpReports::$config['mail_settings']['from'])) {
         echo json_encode(array('error' => 'Email settings have not been properly configured on this server'));
         return;
     }
     $from = PhpReports::$config['mail_settings']['from'];
     $subject = $_REQUEST['subject'] ? $_REQUEST['subject'] : 'Database Report';
     $body = $_REQUEST['message'] ? $_REQUEST['message'] : "You've been sent a database report!";
     $email = $_REQUEST['email'];
     $link = $_REQUEST['url'];
     $csv_link = str_replace('report/html/?', 'report/csv/?', $link);
     $table_link = str_replace('report/html/?', 'report/table/?', $link);
     $text_link = str_replace('report/html/?', 'report/text/?', $link);
     // Get the CSV file attachment and the inline HTML table
     $csv = self::urlDownload($csv_link);
     $table = self::urlDownload($table_link);
     $text = self::urlDownload($text_link);
     $email_text = $body . "\n\n" . $text . "\n\nView the report online at {$link}";
     $email_html = "<p>{$body}</p>{$table}<p>View the report online at <a href=\"" . htmlentities($link) . "\">" . htmlentities($link) . "</a></p>";
     // Create the message
     $message = Swift_Message::newInstance()->setSubject($subject)->setFrom($from)->setTo($email)->setBody($email_text)->addPart($email_html, 'text/html');
     $attachment = Swift_Attachment::newInstance()->setFilename('report.csv')->setContentType('text/csv')->setBody($csv);
     $message->attach($attachment);
     // Create the Transport
     $transport = self::getMailTransport();
     $mailer = Swift_Mailer::newInstance($transport);
     try {
         // Send the message
         $result = $mailer->send($message);
     } catch (Exception $e) {
         echo json_encode(array('error' => $e->getMessage()));
         return;
     }
     if ($result) {
         echo json_encode(array('success' => true));
     } else {
         echo json_encode(array('error' => 'Failed to send email to requested recipient'));
     }
 }
Пример #26
0
 /**
  * @inheritdoc
  */
 public function attachContent($content, array $options = [])
 {
     $attachment = \Swift_Attachment::newInstance($content);
     if (!empty($options['fileName'])) {
         $attachment->setFilename($options['fileName']);
     }
     if (!empty($options['contentType'])) {
         $attachment->setContentType($options['contentType']);
     }
     $this->getSwiftMessage()->attach($attachment);
     return $this;
 }
Пример #27
0
 public function setAttachment($attachment, $filename = null, $contentType = null, $rawData = false)
 {
     if ($attachment instanceof Attachment) {
         $this->_attachment = $attachment;
     } else {
         if (!$rawData) {
             $this->_attachment = Attachment::fromPath($attachment);
         } else {
             $this->_attachment = Attachment::newInstance();
             $this->_attachment->setBody($attachment);
         }
         if ($contentType != null) {
             $this->_attachment->setContentType($contentType);
         }
         if ($filename != null) {
             $this->_attachment->setFilename($filename);
         }
     }
     if ($this->_message != null) {
         $this->_message->attach($this->_attachment);
     }
 }
Пример #28
0
 function sendMail($smtp_server, $to, $from, $subject, $body, $cc, $bcc, $attachments = null, $smtp_port = 25, $smtp_username = null, $smtp_password = '', $type = 'text/plain', $transport = 0, $message_id = null, $in_reply_to = null, $inline_images = null, &$complete_mail, $att_version)
 {
     //Load in the files we'll need
     Env::useLibrary('swift');
     try {
         $mail_transport = Swift_SmtpTransport::newInstance($smtp_server, $smtp_port, $transport);
         $smtp_authenticate = $smtp_username != null;
         if ($smtp_authenticate) {
             $mail_transport->setUsername($smtp_username);
             $mail_transport->setPassword(self::ENCRYPT_DECRYPT($smtp_password));
         }
         $mailer = Swift_Mailer::newInstance($mail_transport);
         // init Swift logger
         if (defined('LOG_SWIFT') && LOG_SWIFT > 0) {
             $swift_logger = new Swift_Plugins_Loggers_ArrayLogger();
             $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($swift_logger));
             $swift_logger_level = LOG_SWIFT;
             // 0: no log, 1: log only errors, 2: log everything
         } else {
             $swift_logger_level = 0;
         }
         if (is_string($from)) {
             $pos = strrpos($from, "<");
             if ($pos !== false) {
                 $sender_name = trim(substr($from, 0, $pos));
                 $sender_address = str_replace(array("<", ">"), array("", ""), trim(substr($from, $pos, strlen($from) - 1)));
             } else {
                 $sender_name = "";
                 $sender_address = $from;
             }
             $from = array($sender_address => $sender_name);
         }
         //Create a message
         $message = Swift_Message::newInstance($subject)->setFrom($from)->setContentType($type);
         $to = self::prepareEmailAddresses($to);
         $cc = self::prepareEmailAddresses($cc);
         $bcc = self::prepareEmailAddresses($bcc);
         foreach ($to as $address) {
             $message->addTo(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($cc as $address) {
             $message->addCc(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($bcc as $address) {
             $message->addBcc(array_var($address, 0), array_var($address, 1, ""));
         }
         if ($in_reply_to) {
             if (str_starts_with($in_reply_to, "<")) {
                 $in_reply_to = substr($in_reply_to, 1, -1);
             }
             $validator = new SwiftHeaderValidator();
             if ($validator->validate_id_header_value($in_reply_to)) {
                 $message->getHeaders()->addIdHeader("In-Reply-To", $in_reply_to);
             }
         }
         if ($message_id) {
             if (str_starts_with($message_id, "<")) {
                 $message_id = substr($message_id, 1, -1);
             }
             $message->setId($message_id);
         }
         // add attachments
         if (is_array($attachments)) {
             foreach ($attachments as $att) {
                 if ($att_version < 2) {
                     $swift_att = Swift_Attachment::newInstance($att["data"], $att["name"], $att["type"]);
                 } else {
                     $swift_att = Swift_Attachment::fromPath($att['path'], $att['type']);
                     $swift_att->setFilename($att["name"]);
                 }
                 if (substr($att['name'], -4) == '.eml') {
                     $swift_att->setEncoder(Swift_Encoding::get7BitEncoding());
                     $swift_att->setContentType('message/rfc822');
                 }
                 $message->attach($swift_att);
             }
         }
         // add inline images
         if (is_array($inline_images)) {
             foreach ($inline_images as $image_url => $image_path) {
                 $cid = $message->embed(Swift_Image::fromPath($image_path));
                 $body = str_replace($image_url, $cid, $body);
             }
         }
         self::adjustBody($message, $type, $body);
         $message->setBody($body);
         //Send the message
         $complete_mail = self::retrieve_original_mail_code($message);
         $result = $mailer->send($message);
         if ($swift_logger_level >= 2 || $swift_logger_level > 0 && !$result) {
             file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $swift_logger->dump() . "----------------------------------------------------------------------------", FILE_APPEND);
             $swift_logger->clear();
         }
         return $result;
     } catch (Exception $e) {
         Logger::log("ERROR SENDING EMAIL: " . $e->getTraceAsString(), Logger::ERROR);
         //if there is an error with the connection, let the user know about it
         $mail_error = $e->getMessage();
         $mail_error = stristr($mail_error, 'Log data:', true);
         flash_error(lang('mail not sent') . " '" . $mail_error . "'");
         if ($swift_logger_level > 0) {
             $dump = $swift_logger->dump();
             if ($dump != '') {
                 file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $dump . "----------------------------------------------------------------------------", FILE_APPEND);
                 $swift_logger->clear();
             }
         }
         throw $e;
     }
 }
Пример #29
0
 /**
  * Attach a file
  * Note: Always is preferible get the Message object and work directly with it and with Attachement object
  * 
  * @param string Type of file. Can be 'path' for existent files or 'dynamic' for dynamic content
  * @param string File path, when type = 'path'. The file must exists. Also can be a URL
  * @param string Content type for file (mime type)
  * @param string Set file name in the message
  * @param mixed Content for dynamic content
  * @param string File disposition (inline)
  */
 public function attach_content($type = 'path', $path = '', $content_type = '', $name = '', $content = null, $disposition = '')
 {
     switch ($type) {
         case 'path':
             if (trim($path) == '' || !is_file($path)) {
                 return;
             }
             $att = Swift_Attachment::fromPath($path);
             break;
         case 'dynamic':
             if ($content == null || $content == '') {
                 return;
             }
             $att = Swift_Attachment::newInstance($content);
             break;
     }
     if (trim($name) != '') {
         $att->setFilename($name);
     }
     if (trim($content_type) != '') {
         $att->setContentType($content_type);
     }
     if (trim($disposition) != '') {
         $att->setDisposition($disposition);
     }
     $this->swMessage->attach($att);
 }
Пример #30
0
 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) {
         
     }
     
 }