Author: Chris Corbyn
Inheritance: extends Swift_Mime_MimePart
示例#1
0
 public function testBodySwap()
 {
     $message1 = new Swift_Message('Test');
     $html = new Swift_MimePart('<html></html>', 'text/html');
     $html->getHeaders()->addTextHeader('X-Test-Remove', 'Test-Value');
     $html->getHeaders()->addTextHeader('X-Test-Alter', 'Test-Value');
     $message1->attach($html);
     $source = $message1->toString();
     $message2 = clone $message1;
     $message2->setSubject('Message2');
     foreach ($message2->getChildren() as $child) {
         $child->setBody('Test');
         $child->getHeaders()->removeAll('X-Test-Remove');
         $child->getHeaders()->get('X-Test-Alter')->setValue('Altered');
     }
     $final = $message1->toString();
     if ($source != $final) {
         $this->fail("Difference although object cloned \n [" . $source . "]\n[" . $final . "]\n");
     }
     $final = $message2->toString();
     if ($final == $source) {
         $this->fail('Two body matches although they should differ' . "\n [" . $source . "]\n[" . $final . "]\n");
     }
     $id_1 = $message1->getId();
     $id_2 = $message2->getId();
     $this->assertEquals($id_1, $id_2, 'Message Ids differ');
     $id_2 = $message2->generateId();
     $this->assertNotEquals($id_1, $id_2, 'Message Ids are the same');
 }
示例#2
0
文件: Digest.php 项目: woyifang/forum
 /**
  * Sends the digest
  */
 public function send()
 {
     $lastMonths = new \DateTime();
     $lastMonths->modify('-6 month');
     $parameters = array('modified_at >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => array($lastMonths->getTimestamp()));
     $users = array();
     foreach (Users::find($parameters) as $user) {
         if ($user->email && strpos($user->email, '@') !== false && strpos($user->email, '@users.noreply.github.com') === false) {
             $users[trim($user->email)] = $user->name;
         }
     }
     $fromName = $this->config->mail->fromName;
     $fromEmail = $this->config->mail->fromEmail;
     $url = $this->config->site->url;
     $subject = 'Top Stories from Phosphorum ' . date('d/m/y');
     $lastWeek = new \DateTime();
     $lastWeek->modify('-1 week');
     $order = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - ' . 'IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies + IF(accepted_answer = "Y", 10, 0) DESC';
     $parameters = array('created_at >= ?0 AND deleted != 1 AND categories_id <> 4', 'bind' => array($lastWeek->getTimestamp()), 'order' => $order, 'limit' => 10);
     $e = $this->escaper;
     $content = '<html><head></head><body><p><h1 style="font-size:22px;color:#333;letter-spacing:-0.5px;line-height:1.25;font-weight:normal;padding:16px 0;border-bottom:1px solid #e2e2e2">Top Stories from Phosphorum</h1></p>';
     foreach (Posts::find($parameters) as $post) {
         $user = $post->user;
         if ($user == false) {
             continue;
         }
         $content .= '<p><a style="text-decoration:none;display:block;font-size:20px;color:#333;letter-spacing:-0.5px;line-height:1.25;font-weight:normal;color:#155fad" href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '">' . $e->escapeHtml($post->title) . '</a></p>';
         $content .= '<p><table width="100%"><td><table><tr><td>' . '<img src="https://secure.gravatar.com/avatar/' . $user->gravatar_id . '?s=32&amp;r=pg&amp;d=identicon" width="32" height="32" alt="' . $user->name . ' icon">' . '</td><td><a style="text-decoration:none;color:#155fad" href="' . $url . '/user/' . $user->id . '/' . $user->login . '">' . $user->name . '<br><span style="text-decoration:none;color:#999;text-decoration:none">' . $user->getHumanKarma() . '</span></a></td></tr></table></td><td align="right"><table style="border: 1px solid #dadada;" cellspacing=5>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Created</label><br>' . $post->getHumanCreatedAt() . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Replies</label><br>' . $post->number_replies . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Views</label><br>' . $post->number_views . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Votes</label><br>' . ($post->votes_up - $post->votes_down) . '</td>' . '</tr></table></td></tr></table></p>';
         $content .= $this->markdown->render($e->escapeHtml($post->content));
         $content .= '<p><a style="color:#155fad" href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '">Read more</a></p>';
         $content .= '<hr style="border: 1px solid #dadada">';
     }
     $textContent = strip_tags($content);
     $htmlContent = $content . '<p style="font-size:small;-webkit-text-size-adjust:none;color:#717171;">';
     $htmlContent .= PHP_EOL . 'This email was sent by Phalcon Framework. Change your e-mail preferences <a href="' . $url . '/settings">here</a></p>';
     foreach ($users as $email => $name) {
         try {
             $message = new \Swift_Message('[Phalcon Forum] ' . $subject);
             $message->setTo(array($email => $name));
             $message->setFrom(array($fromEmail => $fromName));
             $bodyMessage = new \Swift_MimePart($htmlContent, 'text/html');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             $bodyMessage = new \Swift_MimePart($textContent, 'text/plain');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             if (!$this->transport) {
                 $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security);
                 $this->transport->setUsername($this->config->smtp->username);
                 $this->transport->setPassword($this->config->smtp->password);
             }
             if (!$this->mailer) {
                 $this->mailer = \Swift_Mailer::newInstance($this->transport);
             }
             $this->mailer->send($message);
         } catch (\Exception $e) {
             echo $e->getMessage(), PHP_EOL;
         }
     }
 }
 public function testSetText()
 {
     $setText = \Closure::bind(function (&$data, $message) {
         return $this->setText($data, $message);
     }, $this->transport, 'Sichikawa\\LaravelSendgridDriver\\Transport\\SendGridTransport');
     $data = [];
     $message = new Message($this->getMessage());
     $message->getSwiftMessage()->setChildren([Swift_MimePart::newInstance('This is a test.')]);
     $setText($data, $message->getSwiftMessage());
     $this->assertEquals('This is a test.', $data['text']);
 }
示例#4
0
 /**
  * Adds body parts to the message.
  *
  * @param Email $notification
  * @param \Swift_Message $email
  * @param string $boundary
  */
 protected function addParts(Email $notification, \Swift_Message $email, $boundary)
 {
     foreach ($notification->getParts() as $part) {
         $mimePart = \Swift_MimePart::newInstance($part->getContent(), $part->getContentType());
         $mimePart->setBoundary($boundary);
         if ($encoder = $this->getEncoder($part)) {
             $mimePart->setEncoder($encoder);
         }
         $email->attach($mimePart);
     }
 }
 public function testGetContents()
 {
     $getContents = \Closure::bind(function ($message) {
         return $this->getContents($message);
     }, $this->transport, SendgridV3Transport::class);
     $message = new Message($this->getMessage());
     $message->getSwiftMessage()->setChildren([Swift_MimePart::newInstance('This is a test.')]);
     $res = $getContents($message->getSwiftMessage());
     $this->assertEquals('text/plain', array_get($res, '0.type'));
     $this->assertEquals('This is a test.', array_get($res, '0.value'));
     $this->assertEquals('text/html', array_get($res, '1.type'));
     $this->assertEquals('Test body.', array_get($res, '1.value'));
 }
示例#6
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);
         }
     }
 }
 public function setPlain($plain)
 {
     if (!isset($this->plainMimePart)) {
         $this->plainMimePart = \Swift_MimePart::newInstance($plain, 'text/plain');
     } else {
         $this->emailObj->detach($this->plainMimePart);
         $this->plainMimePart->setBody($plain);
     }
     if (!empty($plain)) {
         $this->emailObj->attach($this->plainMimePart);
     }
 }
示例#8
0
 /**
  * Add a MimePart to this Message.
  * @param string|Swift_OutputByteStream $body
  * @param string $contentType
  * @param string $charset
  */
 public function addPart($body, $contentType = null, $charset = null)
 {
     return $this->attach(Swift_MimePart::newInstance($body, $contentType, $charset));
 }
示例#9
0
文件: Digest.php 项目: phalcon/forum
 /**
  * Sends the digest
  */
 public function send()
 {
     $lastMonths = new \DateTime();
     $lastMonths->modify('-6 month');
     $parameters = ['modified_at >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => [$lastMonths->getTimestamp()]];
     $users = [];
     foreach (Users::find($parameters) as $user) {
         if ($user->email && strpos($user->email, '@') !== false && strpos($user->email, '@users.noreply.github.com') === false) {
             $users[trim($user->email)] = $user->name;
         }
     }
     $view = new View();
     $view->setViewsDir($this->config->application->viewsDir);
     $fromName = $this->config->mail->fromName;
     $fromEmail = $this->config->mail->fromEmail;
     $url = rtrim($this->config->site->url, '/');
     $subject = sprintf('Top Stories from Phosphorum %s', date('d/m/y'));
     $view->setVar('title', $subject);
     $lastWeek = new \DateTime();
     $lastWeek->modify('-1 week');
     $order = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - ' . 'IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies + IF(accepted_answer = "Y", 10, 0) DESC';
     $parameters = ['created_at >= ?0 AND deleted != 1 AND categories_id <> 4', 'bind' => [$lastWeek->getTimestamp()], 'order' => $order, 'limit' => 10];
     $e = $this->escaper;
     /** @var \Phalcon\Logger\AdapterInterface $logger */
     $logger = $this->getDI()->get('logger', ['mail']);
     $stories = [];
     foreach (Posts::find($parameters) as $i => $post) {
         $user = $post->user;
         if ($user == false) {
             continue;
         }
         $this->gravatar->setSize(32);
         $stories[$i]['user_name'] = $user->name;
         $stories[$i]['user_avatar'] = $this->gravatar->getAvatar($user->email);
         $stories[$i]['user_url'] = "{$url}/user/{$user->id}/{$user->login}";
         $stories[$i]['user_karma'] = $user->getHumanKarma();
         $stories[$i]['post_title'] = $e->escapeHtml($post->title);
         $stories[$i]['post_created'] = $post->getHumanCreatedAt();
         $stories[$i]['post_replies'] = (int) $post->number_replies;
         $stories[$i]['post_views'] = (int) $post->number_views;
         $stories[$i]['post_votes'] = $post->votes_up - $post->votes_down;
         $stories[$i]['post_content'] = $this->markdown->render($e->escapeHtml($post->content));
         $stories[$i]['post_url'] = "{$url}/discussion/{$post->id}/{$post->slug}";
     }
     if (empty($stories)) {
         return;
     }
     $view->setVar('stories', $stories);
     $view->setVar('notice', sprintf('This email was sent by %s mail sender. Change your e-mail preferences <a href="%s/settings">here</a>', $this->config->site->name, $url));
     $content = $view->render('mail/digest.phtml');
     $textContent = preg_replace('#<a[^>]+href="([^"]+)"[^>]*>([^<]+)<\\/a>#', '$2:' . "\n" . '$1', $content);
     $textContent = str_replace('<span class="foot-line"></span>', "--\n", $textContent);
     $textContent = trim(strip_tags($textContent));
     $textContent = str_replace('&nbsp;', ' ', $textContent);
     $textContent = preg_replace('#\\t+#', '', $textContent);
     $textContent = preg_replace('# {2,}#', ' ', $textContent);
     $textContent = preg_split('#(\\r|\\n)#', $textContent);
     $textContent = join("\n\n", array_filter($textContent, function ($line) {
         return '' !== trim($line);
     }));
     $textContent = preg_replace('#^[ \\t]+#m', '', $textContent);
     foreach ($users as $email => $name) {
         try {
             $message = new \Swift_Message("[{$this->config->site->name} Forum] " . $subject);
             $message->setTo([$email => $name]);
             $message->setFrom([$fromEmail => $fromName]);
             $bodyMessage = new \Swift_MimePart($content, 'text/html');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             $bodyMessage = new \Swift_MimePart($textContent, 'text/plain');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             if (!$this->transport) {
                 $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security);
                 $this->transport->setUsername($this->config->smtp->username);
                 $this->transport->setPassword($this->config->smtp->password);
             }
             if (!$this->mailer) {
                 $this->mailer = \Swift_Mailer::newInstance($this->transport);
             }
             $failedRecipients = [];
             $this->mailer->send($message, $failedRecipients);
             if (empty($failedRecipients)) {
                 $logger->info("Sent an email to {$email}");
             } else {
                 $logger->error("Unable to sent an email to " . join(', ', $failedRecipients));
             }
         } catch (\Exception $e) {
             $logger->error($e->getMessage());
             throw new \Exception($e->getMessage(), $e->getCode(), $e);
         }
     }
 }
 protected function _createMimePart()
 {
     Swift_DependencyContainer::getInstance()->register('properties.charset')->asValue(null);
     return Swift_MimePart::newInstance();
 }
示例#11
0
 public function send(Notifications $notification)
 {
     if ($notification->sent == 'Y') {
         return;
     }
     $post = $notification->post;
     $user = $notification->user;
     if ($notification->type != 'P') {
         $reply = $notification->reply;
     } else {
         $reply = true;
     }
     $from = $this->config->mail->fromEmail;
     $url = $this->config->site->url;
     if ($post && $user && $reply) {
         if ($user->email && $user->notifications != 'N' && strpos($user->email, '@users.noreply.github.com') === false) {
             try {
                 $message = new \Swift_Message('[Phalcon Forum] ' . $post->title);
                 $message->setTo(array($user->email => $user->name));
                 $message->addReplyTo('reply-i' . $post->id . '-' . time() . '@phosphorum.com');
                 if ($notification->type == 'P') {
                     $originalContent = $post->content;
                     $htmlContent = $this->markdown->render($post->content);
                     $message->setFrom(array($from => $post->user->name));
                 } else {
                     $reply = $notification->reply;
                     $originalContent = $reply->content;
                     $htmlContent = $this->markdown->render($reply->content);
                     $message->setFrom(array($from => $reply->user->name));
                 }
                 if (trim($originalContent)) {
                     $textContent = nl2br($originalContent);
                     $htmlContent .= '<p style="font-size:small;-webkit-text-size-adjust:none;color:#717171;">';
                     if ($notification->type == 'P') {
                         $htmlContent .= '&mdash;<br>Reply to this email directly or view the complete thread on ' . PHP_EOL . '<a href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '">Phosphorum</a>. ';
                     } else {
                         $htmlContent .= '&mdash;<br>Reply to this email directly or view the complete thread on ' . PHP_EOL . '<a href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '#C' . $reply->id . '">Phosphorum</a>. ';
                     }
                     $htmlContent .= PHP_EOL . 'Change your e-mail preferences <a href="' . $url . '/settings">here</a></p>';
                     $bodyMessage = new \Swift_MimePart($htmlContent, 'text/html');
                     $bodyMessage->setCharset('UTF-8');
                     $message->attach($bodyMessage);
                     $bodyMessage = new \Swift_MimePart($textContent, 'text/plain');
                     $bodyMessage->setCharset('UTF-8');
                     $message->attach($bodyMessage);
                     if (!$this->transport) {
                         $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security);
                         $this->transport->setUsername($this->config->smtp->username);
                         $this->transport->setPassword($this->config->smtp->password);
                     }
                     if (!$this->mailer) {
                         $this->mailer = \Swift_Mailer::newInstance($this->transport);
                     }
                     $this->mailer->send($message);
                 }
             } catch (\Exception $e) {
                 echo $e->getMessage(), PHP_EOL;
             }
         }
     }
     $notification->sent = 'Y';
     if ($notification->save() == false) {
         foreach ($notification->getMessages() as $message) {
             echo $message->getMessage(), PHP_EOL;
         }
     }
 }
示例#12
0
 /**
  * Add a MimePart to this Message.
  * @param string|Swift_OutputByteStream $body
  * @param string                        $contentType
  * @param string                        $charset
  */
 public function addPart($body, $contentType = null, $charset = null)
 {
     $part = Swift_MimePart::newInstance($body, $contentType, $charset);
     $part->setEncoder($this->getEncoder());
     return $this->attach($part);
 }