/** * в отправленном письме содержится нужный токен * * @depends testEmailSent */ public function testSentEamilContainsRightToken(\Swift_Message $message) { /** @var User $user */ $user = $this->getContainer()->get('fos_user.user_manager')->findUserByEmail('*****@*****.**'); $this->assertContains('token', $message->getBody()); preg_match('@\\?token=([^\\s]+)@', $message->getBody(), $matches); $this->assertCount(2, $matches); $token = $matches[1]; $this->assertEquals($user->getConfirmationToken(), $token); }
public function send(\Swift_Message $message) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_URL, $this->host); //不同于登录SendCloud站点的帐号,您需要登录后台创建发信子帐号,使用子帐号和密码才可以进行邮件的发送。 $from = $message->getFrom(); $to = ''; foreach ($message->getTo() as $_mail => $_toName) { if ($to .= '') { $to .= ';'; } $to .= $_mail; } curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('api_user' => $this->username, 'api_key' => $this->password, 'from' => $this->username, 'fromname' => is_array($from) ? current($from) : $from, 'to' => $to, 'subject' => $message->getSubject(), 'html' => $message->getBody()))); $result = curl_exec($ch); //请求失败 if ($result === false) { throw new \Exception(curl_error($ch)); } curl_close($ch); $ret = json_decode($result); p($result); if ($ret->message != 'success') { throw new \Exception($result); } return $result; }
/** * @Then the email body should not contain :text */ public function theEmailBodyShouldNotContainText($text) { if (null === $this->message) { throw new \RuntimeException('Select an email which has to have been sent first. ' . 'You can use the step: "an email with subject :subject should have been sent (to :email)"'); } $crawler = new Crawler($this->message->getBody()); Assert::assertNotContains($text, $crawler->text()); }
/** * Creates a DmSentMail from a Swift_Message * @param Swift_Message $message * @return DmSentMail */ public function createFromSwiftMessage(Swift_Message $message) { $debug = $message->toString(); if ($attachementPosition = strpos($debug, 'attachment; filename=')) { $debug = substr($debug, 0, $attachementPosition); } return $this->create(array('subject' => $message->getSubject(), 'body' => $message->getBody(), 'from_email' => implode(', ', array_keys((array) $message->getFrom())), 'to_email' => implode(', ', array_keys((array) $message->getTo())), 'cc_email' => implode(', ', array_keys((array) $message->getCC())), 'bcc_email' => implode(', ', array_keys((array) $message->getBCC())), 'reply_to_email' => implode(', ', array_keys((array) $message->getReplyTo())), 'sender_email' => implode(', ', array_keys((array) $message->getSender())), 'debug_string' => $debug)); }
/** * Converts \Swift_Message into associative array * * @param array $search If the mailer requires tokens in another format than Mautic's, pass array of Mautic tokens to replace * @param array $replace If the mailer requires tokens in another format than Mautic's, pass array of replacement tokens * * @return array|\Swift_Message */ protected function messageToArray($search = array(), $replace = array()) { if (!empty($search)) { MailHelper::searchReplaceTokens($search, $replace, $this->message); } $from = $this->message->getFrom(); $fromEmail = current(array_keys($from)); $fromName = $from[$fromEmail]; $message = array('html' => $this->message->getBody(), 'text' => MailHelper::getPlainTextFromMessage($this->message), 'subject' => $this->message->getSubject(), 'from' => array('name' => $fromName, 'email' => $fromEmail)); // Generate the recipients $message['recipients'] = array('to' => array(), 'cc' => array(), 'bcc' => array()); $to = $this->message->getTo(); foreach ($to as $email => $name) { $message['recipients']['to'][$email] = array('email' => $email, 'name' => $name); } $cc = $this->message->getCc(); if (!empty($cc)) { foreach ($cc as $email => $name) { $message['recipients']['cc'][$email] = array('email' => $email, 'name' => $name); } } $bcc = $this->message->getBcc(); if (!empty($bcc)) { foreach ($bcc as $email => $name) { $message['recipients']['bcc'][$email] = array('email' => $email, 'name' => $name); } } $replyTo = $this->message->getReplyTo(); if (!empty($replyTo)) { foreach ($replyTo as $email => $name) { $message['replyTo'] = array('email' => $email, 'name' => $name); } } $returnPath = $this->message->getReturnPath(); if (!empty($returnPath)) { $message['returnPath'] = $returnPath; } // Attachments $children = $this->message->getChildren(); $attachments = array(); foreach ($children as $child) { if ($child instanceof \Swift_Attachment) { $attachments[] = array('type' => $child->getContentType(), 'name' => $child->getFilename(), 'content' => $child->getEncoder()->encodeString($child->getBody())); } } $message['attachments'] = $attachments; return $message; }
/** * @param string $templateName * @param array $templateParams * @param \Swift_Message $expectedMessage * @param string $emailType */ protected function assertSendCalled($templateName, array $templateParams, \Swift_Message $expectedMessage, $emailType = 'txt') { $this->emailTemplate->expects($this->once())->method('getType')->willReturn($emailType); $this->objectRepository->expects($this->once())->method('findOneBy')->with(['name' => $templateName])->willReturn($this->emailTemplate); $this->renderer->expects($this->once())->method('compileMessage')->with($this->emailTemplate, $templateParams)->willReturn([$expectedMessage->getSubject(), $expectedMessage->getBody()]); $to = $expectedMessage->getTo(); $toKeys = array_keys($to); $this->emailHolderHelper->expects($this->once())->method('getEmail')->with($this->isInstanceOf('Oro\\Bundle\\UserBundle\\Entity\\UserInterface'))->willReturn(array_shift($toKeys)); $this->mailer->expects($this->once())->method('send')->with($this->callback(function (\Swift_Message $actualMessage) use($expectedMessage) { $this->assertEquals($expectedMessage->getSubject(), $actualMessage->getSubject()); $this->assertEquals($expectedMessage->getFrom(), $actualMessage->getFrom()); $this->assertEquals($expectedMessage->getTo(), $actualMessage->getTo()); $this->assertEquals($expectedMessage->getBody(), $actualMessage->getBody()); $this->assertEquals($expectedMessage->getContentType(), $actualMessage->getContentType()); return true; })); }
/** * Converts \Swift_Message into associative array. * * @param array $search If the mailer requires tokens in another format than Mautic's, pass array of Mautic tokens to replace * @param array $replace If the mailer requires tokens in another format than Mautic's, pass array of replacement tokens * @param bool|false $binaryAttachments True to convert file attachments to binary * * @return array|\Swift_Message */ protected function messageToArray($search = [], $replace = [], $binaryAttachments = false) { if (!empty($search)) { MailHelper::searchReplaceTokens($search, $replace, $this->message); } $from = $this->message->getFrom(); $fromEmail = current(array_keys($from)); $fromName = $from[$fromEmail]; $message = ['html' => $this->message->getBody(), 'text' => MailHelper::getPlainTextFromMessage($this->message), 'subject' => $this->message->getSubject(), 'from' => ['name' => $fromName, 'email' => $fromEmail]]; // Generate the recipients $message['recipients'] = ['to' => [], 'cc' => [], 'bcc' => []]; $to = $this->message->getTo(); foreach ($to as $email => $name) { $message['recipients']['to'][$email] = ['email' => $email, 'name' => $name]; } $cc = $this->message->getCc(); if (!empty($cc)) { foreach ($cc as $email => $name) { $message['recipients']['cc'][$email] = ['email' => $email, 'name' => $name]; } } $bcc = $this->message->getBcc(); if (!empty($bcc)) { foreach ($bcc as $email => $name) { $message['recipients']['bcc'][$email] = ['email' => $email, 'name' => $name]; } } $replyTo = $this->message->getReplyTo(); if (!empty($replyTo)) { foreach ($replyTo as $email => $name) { $message['replyTo'] = ['email' => $email, 'name' => $name]; } } $returnPath = $this->message->getReturnPath(); if (!empty($returnPath)) { $message['returnPath'] = $returnPath; } // Attachments $children = $this->message->getChildren(); $attachments = []; foreach ($children as $child) { if ($child instanceof \Swift_Attachment) { $attachments[] = ['type' => $child->getContentType(), 'name' => $child->getFilename(), 'content' => $child->getEncoder()->encodeString($child->getBody())]; } } if ($binaryAttachments) { // Convert attachments to binary if applicable $message['attachments'] = $attachments; $fileAttachments = $this->getAttachments(); if (!empty($fileAttachments)) { foreach ($fileAttachments as $attachment) { if (file_exists($attachment['filePath']) && is_readable($attachment['filePath'])) { try { $swiftAttachment = \Swift_Attachment::fromPath($attachment['filePath']); if (!empty($attachment['fileName'])) { $swiftAttachment->setFilename($attachment['fileName']); } if (!empty($attachment['contentType'])) { $swiftAttachment->setContentType($attachment['contentType']); } if (!empty($attachment['inline'])) { $swiftAttachment->setDisposition('inline'); } $message['attachments'][] = ['type' => $swiftAttachment->getContentType(), 'name' => $swiftAttachment->getFilename(), 'content' => $swiftAttachment->getEncoder()->encodeString($swiftAttachment->getBody())]; } catch (\Exception $e) { error_log($e); } } } } } else { $message['binary_attachments'] = $attachments; $message['file_attachments'] = $this->getAttachments(); } $message['headers'] = []; $headers = $this->message->getHeaders()->getAll(); /** @var \Swift_Mime_Header $header */ foreach ($headers as $header) { if ($header->getFieldType() == \Swift_Mime_Header::TYPE_TEXT) { $message['headers'][$header->getFieldName()] = $header->getFieldBodyModel(); } } return $message; }
private function retrieve_original_mail_code(Swift_Message $message) { $complete_mail = ""; try { $complete_mail = $message->toString(); } catch (Swift_IoException $e) { $original_body = $message->getBody(); try { // if io error occurred (images not found tmp folder), try removing images from content to get the content $reduced_body = preg_replace("/<img[^>]*src=[\"']([^\"']*)[\"']/", "", $original_body); $message->setBody($reduced_body); $complete_mail = $message->toString(); $message->setBody($original_body); } catch (Exception $ex) { $complete_mail = $original_body; Logger::log("ERROR SENDING EMAIL: " . $ex->getTraceAsString(), Logger::ERROR); } } return $complete_mail; }
/** * Process inline images. Convert it to embedded attachments and update message body. * * @param \Swift_Message $message * @param EmailModel $model */ protected function processEmbeddedImages(\Swift_Message $message, EmailModel $model) { if ($model->getType() === 'html') { $guesser = ExtensionGuesser::getInstance(); $body = $message->getBody(); $body = preg_replace_callback('/<img(.*)src(\\s*)=(\\s*)["\'](.*)["\']/U', function ($matches) use($message, $guesser, $model) { if (count($matches) === 5) { // 1st match contains any data between '<img' and 'src' parts (e.g. 'width=100') $imgConfig = $matches[1]; // 4th match contains src attribute value $srcData = $matches[4]; if (strpos($srcData, 'data:image') === 0) { list($mime, $content) = explode(';', $srcData); list($encoding, $file) = explode(',', $content); $mime = str_replace('data:', '', $mime); $fileName = sprintf('%s.%s', uniqid(), $guesser->guess($mime)); $swiftAttachment = \Swift_Image::newInstance(ContentDecoder::decode($file, $encoding), $fileName, $mime); /** @var $message \Swift_Message */ $id = $message->embed($swiftAttachment); $attachmentContent = new EmailAttachmentContent(); $attachmentContent->setContent($file); $attachmentContent->setContentTransferEncoding($encoding); $emailAttachment = new EmailAttachment(); $emailAttachment->setEmbeddedContentId($swiftAttachment->getId()); $emailAttachment->setFileName($fileName); $emailAttachment->setContentType($mime); $attachmentContent->setEmailAttachment($emailAttachment); $emailAttachment->setContent($attachmentContent); $emailAttachmentModel = new EmailAttachmentModel(); $emailAttachmentModel->setEmailAttachment($emailAttachment); $model->addAttachment($emailAttachmentModel); return sprintf('<img%ssrc="%s"', $imgConfig, $id); } } }, $body); $message->setBody($body, 'text/html'); } }
/** * Diverts an email from its original destination. Useful for testing things in nearlive * @param Swift_Message $message * @return bool */ protected function divertMessage($message) { $orig_rcpts = implode(', ', array_keys($message->getTo())); $message->setBody("!! OpenEyes Mailer: Original recipients: {$orig_rcpts}\n\n" . $message->getBody()); Yii::log("Diverting message from: {$orig_rcpts}, to: " . implode(', ', $this->divert)); $message->setTo($this->divert); return $this->directlySendMessage($message); }
/** * {@inheritdoc} */ public function getBody() { return $this->message->getBody(); }
/** * Process inline images.. * * @param \Swift_Message $m * The message which inline images are to be added to. * @param array $images * The images which are to be added as inline images to the provided * message. */ protected function embed(\Swift_Message $m, array $images) { // Iterate through each array element. foreach ($images as $image) { if ($image instanceof \stdClass) { // Validate required fields. if (empty($image->uri) || empty($image->filename) || empty($image->filemime) || empty($image->cid)) { continue; } // Keep track of the 'cid' assigned to the embedded image. $cid = NULL; // Get image data. if (valid_url($image->uri, TRUE)) { $content = file_get_contents($image->uri); } else { $content = file_get_contents(drupal_realpath($image->uri)); } $filename = $image->filename; $filemime = $image->filemime; // Embed image. $cid = $m->embed(\Swift_Image::newInstance($content, $filename, $filemime)); // The provided 'cid' needs to be replaced with the 'cid' returned // by the Swift Mailer library. $body = $m->getBody(); $body = preg_replace('/cid.*' . $image->cid . '/', $cid, $body); $m->setBody($body); } } }
/** * {@inheritdoc} */ public function match(\Swift_Message $message) { $subject = $message->getBody(); return strstr($subject, $this->subject) !== false; }
/** * Creates a DmSentMail from a Swift_Message * @param Swift_Message $message * @return DmSentMail */ public function createFromSwiftMessage(Swift_Message $message) { return $this->create(array('subject' => $message->getSubject(), 'body' => $message->getBody(), 'from_email' => implode(', ', array_keys((array) $message->getFrom())), 'to_email' => implode(', ', array_keys((array) $message->getTo())), 'cc_email' => implode(', ', array_keys((array) $message->getCC())), 'bcc_email' => implode(', ', array_keys((array) $message->getBCC())), 'reply_to_email' => $message->getReplyTo(), 'sender_email' => $message->getSender(), 'debug_string' => $message->toString())); }
/** * @param Swift_Message $message * * @return Swift_Message */ protected function createMessage(Swift_Message $message) { $mimeEntity = new Swift_Message('', $message->getBody(), $message->getContentType(), $message->getCharset()); $mimeEntity->setChildren($message->getChildren()); $messageHeaders = $mimeEntity->getHeaders(); $messageHeaders->remove('Message-ID'); $messageHeaders->remove('Date'); $messageHeaders->remove('Subject'); $messageHeaders->remove('MIME-Version'); $messageHeaders->remove('To'); $messageHeaders->remove('From'); return $mimeEntity; }
/** * Search and replace tokens * Adapted from \Swift_Plugins_DecoratorPlugin * * @param array $search * @param array $replace * @param \Swift_Message $message */ public static function searchReplaceTokens($search, $replace, \Swift_Message &$message) { // Body $body = $message->getBody(); $bodyReplaced = str_ireplace($search, $replace, $body, $updated); if ($updated) { $message->setBody($bodyReplaced); } unset($body, $bodyReplaced); // Subject $subject = $message->getSubject(); $bodyReplaced = str_ireplace($search, $replace, $subject, $updated); if ($updated) { $message->setSubject($bodyReplaced); } unset($subject, $bodyReplaced); // Headers /** @var \Swift_Mime_Header $header */ foreach ($message->getHeaders()->getAll() as $header) { $headerBody = $header->getFieldBodyModel(); $updated = false; if (is_array($headerBody)) { $bodyReplaced = array(); foreach ($headerBody as $key => $value) { $count1 = $count2 = 0; $key = is_string($key) ? str_ireplace($search, $replace, $key, $count1) : $key; $value = is_string($value) ? str_ireplace($search, $replace, $value, $count2) : $value; $bodyReplaced[$key] = $value; if ($count1 + $count2) { $updated = true; } } } else { $bodyReplaced = str_ireplace($search, $replace, $headerBody, $updated); } if (!empty($updated)) { $header->setFieldBodyModel($bodyReplaced); } unset($headerBody, $bodyReplaced); } // Parts (plaintext) $children = (array) $message->getChildren(); /** @var \Swift_Mime_MimeEntity $child */ foreach ($children as $child) { $childType = $child->getContentType(); list($type, ) = sscanf($childType, '%[^/]/%s'); if ($type == 'text') { $childBody = $child->getBody(); $bodyReplaced = str_ireplace($search, $replace, $childBody); if ($childBody != $bodyReplaced) { $childBody = strip_tags($bodyReplaced); $child->setBody($childBody); } } unset($childBody, $bodyReplaced); } }
/** * Add embedded HTML images (image dir) * * @access protected * @param Swift_Message $message */ protected function add_html_images(&$message) { $path = Config::$email_directory . '/media/'; if (!file_exists($path)) { return; } $html_body = $message->getBody(); if ($handle = opendir($path)) { while (false !== ($file = readdir($handle))) { if (substr($file, 0, 1) != '.' && strpos($html_body, $file) !== false) { $swift_image = \Swift_Image::newInstance(file_get_contents($path . $file), $file, Util::mime_type($path . $file)); $html_body = str_replace($file, $message->embed($swift_image), $html_body); } } } $message->setBody($html_body); closedir($handle); }