/** * Create activity from Swift Message * @param \Swift_Message $message * @return EmailActivity */ protected function createActivity(\Swift_Message $message) { // Creation du doc de trace d'activité avec les données basiques $from_email = $message->getHeaders()->get('From')->getFieldBody(); $to_email = $message->getHeaders()->get('To')->getFieldBody(); $message_id = $message->getHeaders()->get('Message-ID')->getId(); $subject = $message->getSubject(); $activity = new $this->activity_class(); $activity->setFromEmail($from_email); $activity->setToEmail($to_email); $activity->setSubject($subject); $activity->setMessageId($message_id); // Récupération du document associé aux relations from_user et to_user $meta = $this->dm->getClassMetadata($this->activity_class); $class = $meta->getAssociationTargetClass('from_user'); $repo = $this->dm->getRepository($class); $user = $repo->findOneByEmail($activity->getFromEmail()); if (!is_null($user)) { $activity->setFromUser($user); } $class = $meta->getAssociationTargetClass('to_user'); $repo = $this->dm->getRepository($class); $user = $repo->findOneByEmail($activity->getToEmail()); if (!is_null($user)) { $activity->setToUser($user); } return $activity; }
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; }
/** * 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)); }
protected function renderMessageInformation(Swift_Message $message) { static $i = 0; $i++; $to = null === $message->getTo() ? '' : implode(', ', array_keys($message->getTo())); $html = array(); $html[] = sprintf('<h3>%s (to: %s) %s</h3>', $message->getSubject(), $to, $this->getToggler('sfWebDebugMailTemplate' . $i)); $html[] = '<div id="sfWebDebugMailTemplate' . $i . '" style="display:' . (1 == $i ? 'block' : 'none') . '">'; $html[] = '<pre>' . htmlentities($message->toString(), ENT_QUOTES, $message->getCharset()) . '</pre>'; $html[] = '</div>'; return implode("\n", $html); }
public function send(\Swift_Message $message, $tplName, array $tplParams = array()) { if (!$message->getFrom()) { $message->setFrom($this->mailerParams['from']); } if (!$message->getReturnPath()) { $message->setReturnPath($this->mailerParams['return_path']); } $html = $this->templating->render($tplName, $tplParams); $message->setBody($html, 'text/html')->addPart($this->html2text->convert($html), 'text/plain'); if (!$message->getSubject()) { $message->setSubject((new Crawler($html))->filter('head title')->text()); } $this->mailer->send($message); }
/** * 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; })); }
/** * 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); } }
/** * Creates an EmailSpool based on a Swift_Message. * Can optionally relate the EmailSpool to a model_id and model_name by passing an CActiveRecord into $model. * @param Swift_Message $swiftMessage * @param CActiveRecord|null $model * @return EmailSpool */ public function getEmailSpool($swiftMessage, $model = null) { $emailSpool = new EmailSpool(); $emailSpool->created = time(); $emailSpool->status = 'pending'; $emailSpool->subject = $swiftMessage->getSubject(); $emailSpool->message = $emailSpool->pack($swiftMessage); $emailSpool->to_address = json_encode($swiftMessage->getTo()); $emailSpool->from_address = json_encode($swiftMessage->getFrom()); if ($model) { $emailSpool->model_name = get_class($model); $emailSpool->model_id = is_array($model->getPrimaryKey()) ? implode('-', $model->getPrimaryKey()) : $model->getPrimaryKey(); } return $emailSpool; }
/** * {@inheritdoc} */ public function match(\Swift_Message $message) { $subject = $message->getSubject(); return strstr($subject, $this->subject) !== false; }
/** * 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; }
/** * PHPWS_Email has a built-in simple logging function. This replicates * the functionality of that function for SwiftMail. */ public static function logSwiftmailMessage(Swift_Message $message) { $id = 'id:' . $message->getId(); $from = 'from:' . $message->getSender(); $to = 'to:' . implode(',', array_keys($message->getTo())); // Optional fields, If the message has them, implode the arrays to simple strings. $cc = $message->getCc() != null ? 'cc:' . implode(',', array_keys($message->getCc())) : ''; $bcc = $message->getBcc() != null ? 'bcc:' . implode(',', array_keys($message->getBcc())) : ''; $replyto = $message->getReplyTo() != null ? 'reply-to:' . implode(',', array_keys($message->getReplyTo())) : ''; $subject = 'subject:' . $message->getSubject(); $module = 'module:' . PHPWS_Core::getCurrentModule(); $user = '******' . (Current_User::isLogged() ? Current_User::getUsername() : ''); PHPWS_Core::log("{$id} {$module} {$user} {$subject} {$from} {$to} {$cc} {$bcc} {$replyto}", 'phpws-mail.log', 'mail'); }
/** * {@inheritdoc} */ public function getSubject() { return $this->message->getSubject(); }
/** * 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())); }