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);
 }
Beispiel #2
0
 /**
  * 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 executePassword()
 {
     $this->form = new RequestPasswordForm();
     if ($this->getRequest()->isMethod('get')) {
         return;
     }
     $this->form->bind($this->getRequest()->getParameter('form'));
     if (!$this->form->isValid()) {
         return;
     }
     $email = $this->form->getValue('email');
     $password = substr(md5(rand(100000, 999999)), 0, 6);
     $sfGuardUserProfile = sfGuardUserProfilePeer::retrieveByEmail($email);
     $sfGuardUser = $sfGuardUserProfile->getSfGuardUser();
     $sfGuardUser->setPassword($password);
     try {
         $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25);
         $connection->setUsername('*****@*****.**');
         $connection->setPassword('gahve123');
         $mailer = new Swift($connection);
         $message = new Swift_Message('Request Password');
         $mailContext = array('email' => $email, 'password' => $password, 'username' => $sfGuardUser->getUsername(), 'full_name' => $sfGuardUserProfile->getFirstName());
         $message->attach(new Swift_Message_Part($this->getPartial('mail/requestPasswordHtmlBody', $mailContext), 'text/html'));
         $message->attach(new Swift_Message_Part($this->getPartial('mail/requestPasswordTextBody', $mailContext), 'text/plain'));
         $mailer->send($message, $email, '*****@*****.**');
         $mailer->disconnect();
     } catch (Exception $e) {
         $mailer->disconnect();
     }
     $sfGuardUser->save();
     $this->getUser()->setFlash('info', 'A new password is sent to your email.');
     $this->forward('site', 'message');
 }
 protected function execute($arguments = array(), $options = array())
 {
     // initialize the database connection
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
     // add your code here
     $blogs = Doctrine::getTable('Blog');
     $blogs_to_process = $blogs->findByIsThumbnail(0);
     foreach ($blogs_to_process as $blog) {
         $thumbalizr_url = 'http://api.thumbalizr.com?';
         $params = array('url' => $blog->url, 'width' => 300);
         $api_url = $thumbalizr_url . http_build_query($params);
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $api_url);
         curl_setopt($ch, CURLOPT_HEADER, true);
         curl_setopt($ch, CURLOPT_NOBODY, true);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         $res = curl_exec($ch);
         curl_close($ch);
         $res_tab = http_parse_headers($res);
         if (!empty($res_tab['X-Thumbalizr-Status']) && $res_tab['X-Thumbalizr-Status'] == 'OK') {
             // Image is ready let's store the URL!
             $image_data = file_get_contents($api_url);
             $path = sfConfig::get('app_image_path');
             $url = sfConfig::get('app_image_url');
             $image_name = md5($blog->url);
             echo $path . $image_name . "\n";
             file_put_contents($path . $image_name . '.jpg', $image_data);
             $blog->thumbnail_url = $image_name . '.jpg';
             $blog->is_thumbnail = 1;
             $blog->save();
             // Send mail to notify the blo will get into the game!
             try {
                 // Create the mailer and message objects
                 //$mailer = new Swift(new Swift_Connection_NativeMail());
                 //$connection = new Swift_Connection_SMTP('smtp.free.fr');
                 $connection = new Swift_Connection_NativeMail();
                 $mailer = new Swift($connection);
                 $message = new Swift_Message('Welcome!');
                 // Render message parts
                 $mailContext = array('admin_hash' => $blog->getAdmin_hash(), 'blog_url' => $blog->getUrl());
                 $v = $this->getPartial('newBlogMailHtmlBody', $mailContext);
                 $htmlPart = new Swift_Message_Part($v, 'text/html');
                 $message->attach($htmlPart);
                 $message->attach(new Swift_Message_Part($this->getPartial('newBlogMailTextBody', $mailContext), 'text/plain'));
                 $mailTo = $blog->getEmail();
                 $mailFrom = sfConfig::get('app_mail_webmaster');
                 $mailer->send($message, $mailTo, $mailFrom);
                 $mailer->disconnect();
             } catch (Exception $e) {
                 $this->logMessage($e);
             }
         } else {
             //print_r($res_tab);
         }
     }
 }
Beispiel #5
0
 /**
  * {@inheritdoc}
  */
 public function prepare($from, $fromName, array $to, $subject, $body, array $attachments = array(), array $options = array())
 {
     $this->mail = \Swift_Message::newInstance()->setSubject($subject)->setFrom($from)->setBody($body, 'text/html');
     foreach ($to as $receiver) {
         $this->mail->addTo($receiver);
     }
     if (!empty($attachments)) {
         foreach ($attachments as $attachment) {
             $this->mail->attach(\Swift_Attachment::fromPath($attachment));
         }
     }
 }
Beispiel #6
0
 /**
  * 邮件发送
  * @return boolean
  */
 public function send_mail($recipient, $mailsubject, $mailbody)
 {
     apf_require_file("Swift.php");
     Swift_ClassLoader::load("Swift_Connection_SMTP");
     $message = new Swift_Message($mailsubject);
     $message->setFrom("安居客<*****@*****.**>");
     $message->attach(new Swift_Message_Part(strip_tags($mailbody), "text/plain", "base64", "utf-8"));
     $message->attach(new Swift_Message_Part($mailbody, "text/html", "base64", "utf-8"));
     foreach ($recipient as $re) {
         Mail_Queue::put('*****@*****.**', $re, $mailsubject, $message, Const_Mail::TYPE_SWIFT, Const_Mail::TYPE_ID_COMMUNITY_SUBSCRIBE);
     }
     return true;
 }
Beispiel #7
0
 /**
  * 邮件发送
  * @param recipient 邮件接收方email
  * @param mailsubject 邮件主题
  * @param mailbody 邮件内容
  * @return boolean
  */
 private function send_mail($recipient, $mailsubject, $mailbody)
 {
     try {
         $message = new Swift_Message($mailsubject);
         $message->setFrom("安居客<" . $this->sender . ">");
         $message->setTo($recipient);
         $message->attach(new Swift_Message_Part(strip_tags($mailbody), "text/plain", "base64", "utf-8"));
         $message->attach(new Swift_Message_Part($mailbody, "text/html", "base64", "utf-8"));
         Mail_Queue::put($this->sender, $recipient, $mailsubject, $message, Const_Mail::TYPE_SWIFT, Const_Mail::TYPE_ID_COMMUNITY_SUBSCRIBE);
         return true;
     } catch (Exception $e) {
         return false;
     }
 }
 protected function _mapToSwift(SendGrid\Email $mail)
 {
     $message = new \Swift_Message($mail->getSubject());
     /*
      * Since we're sending transactional email, we want the message to go to one person at a time, rather
      * than a bulk send on one message. In order to do this, we'll have to send the list of recipients through the headers
      * but Swift still requires a 'to' address. So we'll falsify it with the from address, as it will be 
      * ignored anyway.
      */
     $message->setTo($mail->to);
     $message->setFrom($mail->getFrom(true));
     $message->setCc($mail->getCcs());
     $message->setBcc($mail->getBccs());
     if ($mail->getHtml()) {
         $message->setBody($mail->getHtml(), 'text/html');
         if ($mail->getText()) {
             $message->addPart($mail->getText(), 'text/plain');
         }
     } else {
         $message->setBody($mail->getText(), 'text/plain');
     }
     if ($replyto = $mail->getReplyTo()) {
         $message->setReplyTo($replyto);
     }
     $attachments = $mail->getAttachments();
     //add any attachments that were added
     if ($attachments) {
         foreach ($attachments as $attachment) {
             $message->attach(\Swift_Attachment::fromPath($attachment['file']));
         }
     }
     $message_headers = $message->getHeaders();
     $message_headers->addTextHeader("x-smtpapi", $mail->smtpapi->jsonString());
     return $message;
 }
 /**
  * {@inheritdoc}
  */
 public function send($from, $to, $subject, $body, $replyTo = null, $attachments = [])
 {
     $message = new \Swift_Message($subject, $body);
     // set from and to
     $message->setFrom($from);
     $message->setTo($to);
     // set attachments
     if (count($attachments) > 0) {
         foreach ($attachments as $file) {
             if ($file instanceof \SplFileInfo) {
                 $path = $file->getPathName();
                 $name = $file->getFileName();
                 // if uploadedfile get original name
                 if ($file instanceof UploadedFile) {
                     $name = $file->getClientOriginalName();
                 }
                 $message->attach(\Swift_Attachment::fromPath($path)->setFilename($name));
             }
         }
     }
     // set replyTo
     if ($replyTo != null) {
         $message->setReplyTo($replyTo);
     }
     return $this->mailer->send($message);
 }
Beispiel #10
0
 public function testBodySwap()
 {
     $message1 = new Swift_Message('Test');
     $html = Swift_MimePart::newInstance('<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');
 }
 /**
  * Embed an inline file into the message, such as a Image or MIDI file
  * @param mixed The file contents, Swift_File object or Swift_Message_EmbeddedFile object
  * @param string The content-type of the file, optional
  * @param string The filename to use, optional
  * @param string the Content-ID to use, optional
  * @return string
  */
 public function embedFile($data, $type = "application/octet-stream", $filename = null, $cid = null)
 {
     $ret = false;
     if ($data instanceof Swift_Message_EmbeddedFile) {
         $ret = $this->message->attach($data);
         $this->attachmentIds[] = $ret;
         return $ret;
     } elseif ($data instanceof Swift_File) {
         try {
             $ret = $this->message->attach(new Swift_Message_EmbeddedFile($data, $filename, $type, $cid));
             $this->attachmentIds[] = $ret;
             return $ret;
         } catch (Swift_Message_MimeException $e) {
             $this->setError("An attachment failed to attach:<br />" . $e->getMessage());
             return false;
         } catch (Swift_FileException $e) {
             $this->setError("An attachment failed to attach:<br />" . $e->getMessage());
             return false;
         }
     } else {
         try {
             $ret = $this->message->attach(new Swift_Message_EmbeddedFile($data, $filename, $type, $cid));
             $this->attachmentIds[] = $ret;
             return $ret;
         } catch (Swift_Message_MimeException $e) {
             $this->setError("An attachment failed to attach:<br />" . $e->getMessage());
             return false;
         } catch (Swift_FileException $e) {
             $this->setError("An attachment failed to attach:<br />" . $e->getMessage());
             return false;
         }
     }
 }
Beispiel #12
0
 protected function _swiftMail($to, $from, $subject, $message, $attachments = [], $html = true)
 {
     $mailer = $this->__getSwiftMailer($from);
     if (is_array($to) && isset($to['email'])) {
         if (isset($to['name'])) {
             $to = [$to['email'] => $to['name']];
         } else {
             $to = $to['email'];
         }
     }
     $mail = new \Swift_Message();
     $mail->setSubject($subject)->setFrom($from['email'], $from['name'])->setTo($to);
     if (isset($from['reply-to'])) {
         if (is_array($from['reply-to']) && isset($from['email'])) {
             $mail->setReplyTo($from['reply-to']['email'], $from['reply-to']['name']);
         } else {
             $mail->setReplyTo($from['reply-to']);
         }
     }
     $mail->setBody($message, $html ? 'text/html' : 'text/plain');
     foreach ($attachments as $attachment) {
         $mail->attach(\Swift_Attachment::fromPath($attachment));
     }
     return $mailer->send($mail);
 }
Beispiel #13
0
 public function testNonEmptyFileNameAsAttachement()
 {
     $message = new Swift_Message();
     try {
         $message->attach(Swift_Attachment::fromPath(__FILE__));
     } catch (Exception $e) {
         $this->fail('Path should not be empty');
     }
 }
 public function go()
 {
     try {
         $swift = new Swift($this->getConnection(), null, Swift::ENABLE_LOGGING);
         $this->setSwiftInstance($swift);
         $message = new Swift_Message("Smoke Test 2 - Multipart");
         $message->attach(new Swift_Message_Part("This message was sent in plain text"));
         $message->attach(new Swift_Message_Part("This message was sent in <strong>HTML</strong>", "text/html"));
         $to = new Swift_Address(TestConfiguration::TO_ADDRESS, TestConfiguration::TO_NAME);
         $from = new Swift_Address(TestConfiguration::FROM_ADDRESS, TestConfiguration::FROM_NAME);
         $swift->send($message, $to, $from);
         $this->to = $to->build();
         $this->from = $from->build();
     } catch (Exception $e) {
         $this->failed = true;
         $this->setError($e->getMessage());
     }
     $this->render();
 }
Beispiel #15
0
 protected function sentMail($mailSubject, $mailBody)
 {
     if ($this->mailSwitch == true && !empty($this->mailAddress)) {
         $mailto = $this->mailAddress;
         apf_require_file("Swift.php");
         Swift_ClassLoader::load("Swift_Connection_SMTP");
         $smtpuser = APF::get_instance()->get_config("SmtpUser");
         $smtpemailto = $mailto;
         $message = new Swift_Message($mailSubject);
         $message->setFrom("安居客<" . $smtpuser . ">");
         $message->setTo($smtpemailto);
         $message->attach(new Swift_Message_Part(strip_tags($mailBody), "text/plain", "base64", "utf-8"));
         $message->attach(new Swift_Message_Part($mailBody, "text/html", "base64", "utf-8"));
         foreach ($smtpemailto as $to) {
             if (!empty($to)) {
                 @Mail_Queue::put($smtpuser, $to, $mailSubject, $message, Const_Mail::TYPE_SWIFT, Const_Mail::TYPE_ID_COMMUNITY_SUBSCRIBE);
             }
         }
     }
 }
Beispiel #16
0
 private function showError($subject)
 {
     $id_lang = intval($this->_order->id_lang);
     $to = $this->_customer->email;
     $toName = $this->_customer->firstname . ' ' . $this->_customer->lastname;
     $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME') . '] ' . $subject);
     $data = array('{lastname}' => $this->_customer->lastname, '{firstname}' => $this->_customer->firstname, '{shop_url}' => 'http://' . Tools::getHttpHost(false, true) . __PS_BASE_URI__, '{shop_name}' => Configuration::get('PS_SHOP_NAME'), '{shop_logo}' => file_exists(_PS_IMG_DIR_ . 'logo.jpg') ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . 'logo.jpg'))) : '', '{id_order}' => intval($this->_order->id));
     Mail::Send($id_lang, 'payment_error', $subject, $data, $to, $toName);
     // redirect to error with message
     Tools::redirectLink(__PS_BASE_URI__ . 'modules/fondy/result-error.php?message=' . urlencode($subject));
 }
Beispiel #17
0
 public function executeNew(sfWebRequest $request)
 {
     // Display the form
     $this->form = new ContestForm();
     if ($this->getRequest()->isMethod('post')) {
         $this->form->bind($request->getParameter('contest'));
         if ($this->form->isValid()) {
             $contest = new contest();
             $contest->setEmail($this->form->getValue('email'));
             $contest->setUrl($this->form->getValue('url'));
             $contest->setAdmin_hash(md5(time() . $this->form->getValue('url') . $this->form->getValue('email')));
             $contest->setPublic_hash(md5(time() . $this->form->getValue('email') . $this->form->getValue('url')));
             $contest->save();
             // Send mail with secret URL
             try {
                 // Create the mailer and message objects
                 //$mailer = new Swift(new Swift_Connection_NativeMail());
                 //$connection = new Swift_Connection_SMTP('smtp.free.fr');
                 $connection = new Swift_Connection_NativeMail();
                 $mailer = new Swift($connection);
                 $message = new Swift_Message('Welcome!');
                 // Render message parts
                 $mailContext = array('admin_hash' => $contest->getAdmin_hash(), 'contest_url' => $contest->getUrl());
                 $v = $this->getPartial('newcontestMailHtmlBody', $mailContext);
                 $htmlPart = new Swift_Message_Part($v, 'text/html');
                 $message->attach($htmlPart);
                 $message->attach(new Swift_Message_Part($this->getPartial('newcontestMailTextBody', $mailContext), 'text/plain'));
                 $mailTo = $contest->getEmail();
                 $mailFrom = sfConfig::get('app_mail_webmaster');
                 $mailer->send($message, $mailTo, $mailFrom);
                 $mailer->disconnect();
             } catch (Exception $e) {
                 $this->logMessage($e);
             }
             //redirect to the thank you page
             $this->redirect('contest/thankyou');
         }
     } else {
         return sfView::SUCCESS;
     }
 }
 public function executeSignUp($request)
 {
     $this->form = new SignUpForm();
     if ($request->isMethod('get')) {
         return;
     }
     $this->form->bind($request->getParameter('form'));
     if (!$this->form->isValid()) {
         return;
     }
     $sfGuardUser = new sfGuardUser();
     $sfGuardUser->setUsername($this->form->getValue('username'));
     $sfGuardUser->setPassword($this->form->getValue('password'));
     $sfGuardUser->setIsActive(false);
     $sfGuardUser->save();
     $sfGuardUserProfile = new sfGuardUserProfile();
     $sfGuardUserProfile->setSfGuardUser($sfGuardUser);
     $sfGuardUserProfile->setEmail($this->form->getValue('email'));
     $sfGuardUserProfile->setFirstName($this->form->getValue('first_name'));
     $sfGuardUserProfile->setLastName($this->form->getValue('last_name'));
     $sfGuardUserProfile->setGender($this->form->getValue('gender'));
     $sfGuardUserProfile->setBirthday($this->form->getValue('birthday'));
     $sfGuardUserProfile->setWebpage($this->form->getValue('webpage'));
     $sfGuardUserProfile->save();
     try {
         $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25);
         $connection->setUsername('*****@*****.**');
         $connection->setPassword('gahve123');
         $mailer = new Swift($connection);
         $message = new Swift_Message('Account Confirmation');
         $mailContext = array('email' => $sfGuardUserProfile->getEmail(), 'full_name' => $sfGuardUserProfile->getFullName(), 'activation_key' => $sfGuardUserProfile->getActivationKey());
         $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpHtmlBody', $mailContext), 'text/html'));
         $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpTextBody', $mailContext), 'text/plain'));
         $mailer->send($message, $sfGuardUserProfile->getEmail(), '*****@*****.**');
         $mailer->disconnect();
     } catch (Exception $e) {
         $mailer->disconnect();
     }
     $this->getUser()->setFlash('info', 'A confirmation email has been sent to your email address.');
     $this->forward('site', 'message');
 }
Beispiel #19
0
 /**
  * @param Attachment $attachment
  * @return $this
  */
 public function attach(Attachment $attachment)
 {
     $mailAttachment = \Swift_Attachment::fromPath($attachment->getFile());
     if ($attachment->getFilename() !== null) {
         $mailAttachment->setFilename($attachment->getFilename());
     }
     if ($attachment->getMimeType() !== null) {
         $mailAttachment->setContentType($attachment->getMimeType());
     }
     $this->message->attach($mailAttachment);
     return $this;
 }
 /**
  * 发送邮件
  * @param $mailSubject 标题
  * @param $mailBody 内容
  * @param array $mailTo 接受人,数组
  * @return bool
  */
 public function sendMail($mailSubject, $mailBody, $mailTo = array())
 {
     if (empty($mailSubject) || empty($mailBody) || empty($mailTo)) {
         return false;
     }
     apf_require_file("Swift.php");
     Swift_ClassLoader::load("Swift_Connection_SMTP");
     $smtpuser = APF::get_instance()->get_config("SmtpUser");
     $smtpemailto = $mailTo;
     $message = new Swift_Message($mailSubject);
     $message->setFrom("安居客<" . $smtpuser . ">");
     $message->setTo($smtpemailto);
     $message->attach(new Swift_Message_Part(strip_tags($mailBody), "text/plain", "base64", "utf-8"));
     $message->attach(new Swift_Message_Part($mailBody, "text/html", "base64", "utf-8"));
     foreach ($smtpemailto as $to) {
         if (!empty($to)) {
             @Mail_Queue::put($smtpuser, $to, $mailSubject, $message, Const_Mail::TYPE_SWIFT, Const_Mail::TYPE_ID_COMMUNITY_SUBSCRIBE);
         }
     }
     return true;
 }
 /**
  * Example of sending a multipart email using SMTP
  *
  */
 public function executeThankYou()
 {
     // Create our connection, in this case an SMTP connection
     $conn = new Swift_Connection_SMTP(sfConfig::get('mod_sfswiftmailer_smtp_host'));
     // Need auth for SMTP
     $conn->setUsername(sfConfig::get('mod_sfswiftmailer_smtp_user'));
     $conn->setPassword(sfConfig::get('mod_sfswiftmailer_smtp_pass'));
     $mailer = new Swift($conn);
     // Get our message bodies
     $htmlBody = $this->getPresentationFor('sfSwiftMailer', 'thankYouHtml');
     $textBody = $this->getPresentationFor('sfSwiftMailer', 'thankYouText');
     //Create a message
     $message = new Swift_Message("The Subject");
     //Add some "parts"
     $message->attach(new Swift_Message_Part($textBody));
     $message->attach(new Swift_Message_Part($htmlBody, "text/html"));
     // Send out our mailer
     $mailer->send($message, '*****@*****.**', '*****@*****.**');
     $mailer->disconnect();
     return sfView::SUCCESS;
 }
 public function go()
 {
     try {
         Swift_ClassLoader::load("Swift_Cache_Disk");
         Swift_Cache_Disk::setSavePath(TestConfiguration::WRITABLE_PATH);
         Swift_CacheFactory::setClassName("Swift_Cache_Disk");
         $swift = new Swift($this->getConnection(), null, Swift::ENABLE_LOGGING);
         $this->setSwiftInstance($swift);
         $message = new Swift_Message("Smoke Test 3 - Attachment");
         $message->attach(new Swift_Message_Part("This message contains an attachment"));
         $message->attach(new Swift_Message_Part("This message contains an <em>attachment</em>", "text/html"));
         $message->attach(new Swift_Message_Attachment(new Swift_File(dirname(__FILE__) . "/../files/cv.pdf"), "Authors_CV.pdf", "application/pdf"));
         $to = new Swift_Address(TestConfiguration::TO_ADDRESS, TestConfiguration::TO_NAME);
         $from = new Swift_Address(TestConfiguration::FROM_ADDRESS, TestConfiguration::FROM_NAME);
         $swift->send($message, $to, $from);
         $this->to = $to->build();
         $this->from = $from->build();
     } catch (Exception $e) {
         $this->failed = true;
         $this->setError($e->getMessage());
     }
     $this->render();
 }
 public function go()
 {
     try {
         Swift_ClassLoader::load("Swift_Cache_Disk");
         Swift_Cache_Disk::setSavePath(TestConfiguration::WRITABLE_PATH);
         Swift_CacheFactory::setClassName("Swift_Cache_Disk");
         $swift = new Swift($this->getConnection(), null, Swift::ENABLE_LOGGING);
         $this->setSwiftInstance($swift);
         $message = new Swift_Message("Smoke Test 5 - Embedded Image");
         $part = new Swift_Message_Part("\n        Here is an embedded image: <br />\n        <img src=\"" . $message->attach(new Swift_Message_Image(new Swift_File(dirname(__FILE__) . "/../files/manchester.jpeg"))) . "\" alt=\"image\" /><br />And here is the rest of the message.", "text/html");
         $message->attach($part);
         $message->attach(new Swift_Message_Part("You are viewing this message in plain text.  Switch to HTML mode to see the image.", "text/plain"));
         $to = new Swift_Address(TestConfiguration::TO_ADDRESS, TestConfiguration::TO_NAME);
         $from = new Swift_Address(TestConfiguration::FROM_ADDRESS, TestConfiguration::FROM_NAME);
         $swift->send($message, $to, $from);
         $this->to = $to->build();
         $this->from = $from->build();
     } catch (Exception $e) {
         $this->failed = true;
         $this->setError($e->getMessage());
     }
     $this->render();
 }
Beispiel #24
0
 /**
  * Embed an inline file into the message, such as a Image or MIDI file
  * @param mixed The file contents, Swift_File object or Swift_Message_EmbeddedFile object
  * @param string The content-type of the file, optional
  * @param string The filename to use, optional
  * @param string the Content-ID to use, optional
  * @return string
  */
 function embedFile($data, $type = "application/octet-stream", $filename = null, $cid = null)
 {
     $ret = false;
     if (is_a($data, "Swift_Message_EmbeddedFile")) {
         $ret = $this->message->attach($data);
         $this->attachmentIds[] = $ret;
         return $ret;
     } elseif (is_a($data, "Swift_File")) {
         Swift_Errors::expect($e1, "Swift_Message_MimeException");
         Swift_Errors::expect($e2, "Swift_FileException");
         $ret = $this->message->attach(new Swift_Message_EmbeddedFile($data, $filename, $type, $cid));
         if (!$e1 && !$e2) {
             $this->attachmentIds[] = $ret;
         }
         if (!$e1 && !$e2) {
             return $ret;
         }
         if ($e1) {
             $this->setError("An attachment failed to attach:<br />" . $e1->getMessage());
             return false;
         }
         Swift_Errors::clear("Swift_Message_MimeException");
         if ($e2) {
             $this->setError("An attachment failed to attach:<br />" . $e2->getMessage());
             return false;
         }
         Swift_Errors::clear("Swift_FileException");
     } else {
         Swift_Errors::expect($e1, "Swift_Message_MimeException");
         Swift_Errors::expect($e2, "Swift_FileException");
         $ret = $this->message->attach(new Swift_Message_EmbeddedFile($data, $filename, $type, $cid));
         if (!$e1 && !$e2) {
             $this->attachmentIds[] = $ret;
         }
         if (!$e1 && !$e2) {
             return $ret;
         }
         if ($e1) {
             $this->setError("An attachment failed to attach:<br />" . $e1->getMessage());
             return false;
         }
         Swift_Errors::clear("Swift_Message_MimeException");
         if ($e2) {
             $this->setError("An attachment failed to attach:<br />" . $e2->getMessage());
             return false;
         }
         Swift_Errors::clear("Swift_FileException");
     }
 }
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $db = Doctrine_Manager::connection();
     //get scheduled emails
     $q = LsDoctrineQuery::create()->from('ScheduledEmail se')->where('se.is_sent = ?', false)->limit($options['limit'])->orderBy('se.id');
     foreach ($q->execute() as $email) {
         $mailer = new Swift(new Swift_Connection_NativeMail());
         if ($email->body_html) {
             $message = new Swift_Message($email->subject);
             $message->attach(new Swift_Message_Part($email->body_text));
             $message->attach(new Swift_Message_Part($email->body_html, 'text/html'));
         } else {
             $message = new Swift_Message($email->subject, $email->body_text, 'text/plain');
         }
         $from_address = new Swift_Address($email->from_email, $email->from_name);
         $to_address = new Swift_Address($email->to_email, $email->to_name);
         if ($sent = $mailer->send($message, $to_address, $from_address)) {
             $email->is_sent = true;
             $email->save();
             echo "Successfully sent scheduled email #" . $email->id . "\n";
             echo "  From: " . $email->from_email . "\n";
             echo "  To: " . $email->to_email . "\n";
             echo "  Subject: " . $email->subject . "\n";
             echo "\n";
         } else {
             echo "Error sending scheduled email #" . $email->id . "\n";
             echo "\n";
         }
         $mailer->disconnect();
     }
     //DONE
     LsCli::beep();
 }
Beispiel #26
0
 /**
  * Prepare and attach the given attachment.
  *
  * @param  \Swift_Attachment  $attachment
  * @param  array  $options
  * @return $this
  */
 protected function prepAttachment($attachment, $options = array())
 {
     // First we will check for a MIME type on the message, which instructs the
     // mail client on what type of attachment the file is so that it may be
     // downloaded correctly by the user. The MIME option is not required.
     if (isset($options['mime'])) {
         $attachment->setContentType($options['mime']);
     }
     // If an alternative name was given as an option, we will set that on this
     // attachment so that it will be downloaded with the desired names from
     // the developer, otherwise the default file names will get assigned.
     if (isset($options['as'])) {
         $attachment->setFilename($options['as']);
     }
     $this->swift->attach($attachment);
     return $this;
 }
Beispiel #27
0
 /**
  * @param $to
  * @param $from
  * @param $subject
  * @param $message
  * @param $attachaments
  * @param $html
  * @return int
  */
 public function send($to, $from, $subject, $message, $attachaments, $html)
 {
     $mail = new \Swift_Message();
     $mail->setSubject($subject)->setFrom($from['email'], $from['name'])->setReplyTo($from['reply-to']['email'], $from['reply-to']['name'])->setBody($message, $html ? 'text/html' : 'text/plain');
     if (is_array($to)) {
         foreach ($to as $add => $name) {
             if (is_int($add)) {
                 $mail->setTo($name);
             } else {
                 $mail->setTo([$add => $name]);
             }
         }
     }
     foreach ($attachaments as $attachment) {
         $mail->attach(\Swift_Attachment::fromPath($attachment));
     }
     return $this->mailer->send($mail);
 }
Beispiel #28
0
    /**
     * Send mail.
     *
     * @param array  $from               From address array('*****@*****.**' => 'John Doe').
     * @param array  $to                 To address '*****@*****.**' or array('*****@*****.**' => 'A name').
     * @param string $subject            Subject.
     * @param string $body               Content body.
     * @param array  $contentType        Content type for body, default 'text/plain'.
     * @param array  $cc                 CC to, array('*****@*****.**', '*****@*****.**' => 'A name').
     * @param array  $bcc                BCC to, array('*****@*****.**', '*****@*****.**' => 'A name').
     * @param array  $replyTo            Reply to, array('*****@*****.**', '*****@*****.**' => 'A name').
     * @param mixed  $altBody            Alternate body.
     * @param string $altBodyContentType Alternate content type default 'text/html'.
     * @param array  $header             Associative array of headers array('header1' => 'value1', 'header2' => 'value2').
     * @param array  &$failedRecipients  Array.
     * @param string $charset            Null means leave at default.
     * @param array  $attachments        Array of files.
     *
     * @return integet
     */
    function send(array $from, array $to, $subject, $body, $contentType = 'text/plain', array $cc=null, array $bcc=null, array $replyTo=null, $altBody = null, $altBodyContentType = 'text/html', array $header = array(), &$failedRecipients = array(), $charset=null, array $attachments=array())
    {
        $message = new Swift_Message($subject, $body, $contentType);
        $message->setTo($to);
        $message->setFrom($from);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                $message->attach(Swift_Attachment::fromPath($attachment));
            }
        }
        
        if ($cc) {
            $message->setCc($cc);
        }

        if ($bcc) {
            $message->setBcc($bcc);
        }

        if ($replyTo) {
            $message->setReplyTo($replyTo);
        }

        if ($charset) {
            $message->setCharset($charset);
        }

        if ($altBody) {
            $message->addPart($altBody, $altBodyContentType);
        }

        if ($headers) {
            $headers = $message->getHeaders();
            foreach ($headers as $key => $value) {
                $headers->addTextHeader($key, $value);
            }
        }

        if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'normal') {
            return $this->mailer->send($message, $failedRecipients);
        } else if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'single_recipient') {
            return $this->mailer->sendBatch($message, $failedRecipients);
        }
    }
Beispiel #29
0
 protected function sendCustomerMail(OrganisationInvoice $invoice)
 {
     $users = ModelUser::getByOrganisationId($this->organisation->id, UserRole::TYPE_OWNER);
     if ($users->hasRows()) {
         foreach ($users as $user) {
             $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs');
             $swift = \Swift_Mailer::newInstance($transport);
             $message = new \Swift_Message(lang('New invoice available for ' . $this->organisation->name));
             $currency = ModelSettings::getInstance()->data->default_currency_character;
             $message->setFrom(env('MAIL_FROM'));
             $message->setSender(env('MAIL_FROM'));
             $message->setReplyTo(env('MAIL_FROM'));
             $message->setBody("Dear {$user->data->name}!\n\nAttached is the latest invoice from NinjaImg.\n\nThe amount for invoice {$invoice->invoice_id} is {$invoice->amount_total}{$currency} with payment date {$invoice->due_date}.\n\nYou can always view your invoices at your controlpanel on ninjaimg.com.\n\nThanks for supporting our service, we really appreciate it!\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team", 'text/plain');
             $message->setTo($user->username);
             $attachment = new \Swift_Attachment(file_get_contents($invoice->path), basename($invoice->path), File::getMime($invoice->path));
             $message->attach($attachment);
             $swift->send($message);
         }
     }
 }
Beispiel #30
-2
 public function testHTMLPartAppearsLastEvenWhenAttachmentsAdded()
 {
     $message = new Swift_Message();
     $message->setCharset('utf-8');
     $message->setSubject('test subject');
     $message->addPart('plain part', 'text/plain');
     $attachment = new Swift_Attachment('<data>', 'image.gif', 'image/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($message->getDate()->format('r'), '~');
     $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: image/gif; name=image.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: attachment; filename=image.gif' . "\r\n" . "\r\n" . preg_quote(base64_encode('<data>'), '~') . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString());
 }