public function getMessage() { $message = new Message(); $message->addTo('*****@*****.**', 'ZF DevTeam')->addCc('*****@*****.**')->addBcc('*****@*****.**', 'CR-Team, ZF Project')->addFrom(array('*****@*****.**', 'Matthew' => '*****@*****.**'))->setSender('*****@*****.**', 'Ralph Schindler')->setSubject('Testing Zend\\Mail\\Transport\\Sendmail')->setBody('This is only a test.'); $message->getHeaders()->addHeaders(array('X-Foo-Bar' => 'Matthew')); return $message; }
/** * @param ZendMail\Message $message * @param string $emailAlias * @param array $variables * @return ZendMail\Message * @throws Exception\RuntimeException */ public function sendMail(ZendMail\Message $message, $emailAlias, array $variables = array()) { $plain = $this->renderMessage($emailAlias, Config::TYPE_PLAIN, $variables); $html = $this->renderMessage($emailAlias, Config::TYPE_HTML, $variables); $body = new Mime\Message(); if (!empty($html) && !empty($plain)) { $htmlPart = new Mime\Part($html); $htmlPart->type = 'text/html'; $plainPart = new Mime\Part($plain); $plainPart->type = 'text/plain'; $body->setParts(array($plainPart, $htmlPart)); } elseif (!empty($html)) { $htmlPart = new Mime\Part($html); $htmlPart->type = 'text/html'; $body->setParts(array($htmlPart)); } else { $plainPart = new Mime\Part($plain); $plainPart->type = 'text/plain'; $body->setParts(array($plainPart)); } $from = $this->getConfig()->getFrom($emailAlias); $message->setSubject($this->getSubject($emailAlias, $variables))->setEncoding('UTF-8')->setBody($body)->setFrom($from['email'], $from['name']); if (count($body->getParts()) == 2) { $message->getHeaders()->get('content-type')->setType('multipart/alternative'); } if (null === ($transport = $this->getTransport())) { throw new Exception\RuntimeException('No transport could be alocated'); } $transport->send($message); return $message; }
/** * */ private function generateMessage() { //Reply to if ($this->config["defaults"]["reply_to"] && is_null($this->email->getReplyTo())) { $this->message->addReplyTo($this->config["defaults"]["reply_to"], $this->config["defaults"]["reply_to_name"]); } /* * Produce a list of template vars */ $this->templateVars = array_merge($this->config["template_vars"], $this->email->toArray()); //If not layout, use default if (!$this->email->getHtmlLayoutName()) { $this->email->setHtmlLayoutName($this->config["defaults"]["html_layout_name"]); } /* * If not sender, use default */ if (!is_null($this->email->getFrom())) { $this->message->setFrom($this->email->getFrom(), $this->email->getFromName()); } else { $this->message->setFrom($this->config["defaults"]["from_email"], $this->config["defaults"]["from_name"]); } /* * Force the mailing as header if we have a mailing */ if (!is_null($this->mailing)) { $this->message->getHeaders()->addHeaderLine('X-Mailjet-Campaign', DEBRANOVA_HOST . '-mailing-' . $this->mailing->getId()); } }
/** * Sets the message body * @param \Zend\Mime\Part|\Zend\Mime\Message|string $body Email body * @param string $charset * @return $this Returns this MailService for chaining purposes * @throws InvalidArgumentException * @see \AcMailer\Service\MailServiceInterface::setBody() */ public function setBody($body, $charset = null) { if (is_string($body)) { // Create a Mime\Part and wrap it into a Mime\Message $mimePart = new Mime\Part($body); $mimePart->type = $body != strip_tags($body) ? Mime\Mime::TYPE_HTML : Mime\Mime::TYPE_TEXT; $mimePart->charset = $charset ?: self::DEFAULT_CHARSET; $body = new Mime\Message(); $body->setParts([$mimePart]); } elseif ($body instanceof Mime\Part) { // Overwrite the charset if the Part object if provided if (isset($charset)) { $body->charset = $charset; } // The body is a Mime\Part. Wrap it into a Mime\Message $mimeMessage = new Mime\Message(); $mimeMessage->setParts([$body]); $body = $mimeMessage; } // If the body is not a string or a Mime\Message at this point, it is not a valid argument if (!is_string($body) && !$body instanceof Mime\Message) { throw new InvalidArgumentException(sprintf('Provided body is not valid. It should be one of "%s". %s provided', implode('", "', ['string', 'Zend\\Mime\\Part', 'Zend\\Mime\\Message']), is_object($body) ? get_class($body) : gettype($body))); } // The headers Content-type and Content-transfer-encoding are duplicated every time the body is set. // Removing them before setting the body prevents this error $this->message->getHeaders()->removeHeader('contenttype'); $this->message->getHeaders()->removeHeader('contenttransferencoding'); $this->message->setBody($body); return $this; }
function send($recipients, $type = 'mail') { global $tikilib, $prefs; $logslib = TikiLib::lib('logs'); $this->mail->getHeaders()->removeHeader('to'); foreach ((array) $recipients as $to) { $this->mail->addTo($to); } if ($prefs['zend_mail_handler'] == 'smtp' && $prefs['zend_mail_queue'] == 'y') { $query = "INSERT INTO `tiki_mail_queue` (message) VALUES (?)"; $bindvars = array(serialize($this->mail)); $tikilib->query($query, $bindvars, -1, 0); $title = 'mail'; } else { try { tiki_send_email($this->mail); $title = 'mail'; } catch (Zend\Mail\Exception\ExceptionInterface $e) { $title = 'mail error'; } if ($title == 'mail error' || $prefs['log_mail'] == 'y') { foreach ($recipients as $u) { $logslib->add_log($title, $u . '/' . $this->mail->getSubject()); } } } return $title == 'mail'; }
/** * * @param Message $message * @return ZendMessage */ public static function convert(Message $message) { $mailMessage = new ZendMessage(); $mailMessage->setSubject($message->getSubject()); $mailMessage->setFrom($message->getFrom()); $mailMessage->setTo($message->getTo()); $mailMessage->setCc($message->getCc()); $mailMessage->setBcc($message->getBcc()); $mailMessage->setReplyTo($message->getReplyTo()); $mailMessage->getHeaders()->addHeaders($message->getHeaders()); if ($mailMessage->getSender()) { $mailMessage->setSender($message->getSender()); } if ($message->isMultipart()) { $mimePart = new MimeMessage(); if ($message->getBodyHtml()) { $part = new Part($message->getBodyHtml()); $part->charset = $message->getCharset(); $part->encoding = $message->getEncoding(); $part->type = Mime::TYPE_HTML; $mimePart->addPart($part); } if ($message->getBodyText()) { $part = new Part($message->getBodyText()); $part->charset = $message->getCharset(); $part->encoding = $message->getEncoding(); $part->type = Mime::TYPE_TEXT; $mimePart->addPart($part); } foreach ($message->getAttachments() as $attachment) { $mimePart->addPart($attachment->asMimePart()); } foreach ($message->getParts() as $part) { $mimePart->addPart($part); } $mailMessage->setBody($mimePart); } else { $mailMessage->getHeaders()->addHeaderLine('Content-Type', $message->getContentType()); $mailMessage->setEncoding($message->getEncoding()); $mailMessage->setBody($message->getFilledBody()); } return $mailMessage; }
protected function sendMessage() { $oMessage = new Message(); $oMessage->setEncoding('UTF-8')->addFrom($this->_sFrom)->addTo($this->_sEmailAddress)->setSubject($this->_sSubject)->setBody($this->_oBody); $oHeaders = $oMessage->getHeaders(); $oHeaders->removeHeader('Content-Type'); $oHeaders->addHeaderLine('Content-Type', 'text/html; charset=UTF-8'); $this->_oTransport->send($oMessage); $this->clearAll(); }
/** * Get a blank email message object. * * @return Message */ public function getNewMessage() { $message = new Message(); $message->setEncoding('UTF-8'); $headers = $message->getHeaders(); $ctype = new ContentType(); $ctype->setType('text/plain'); $ctype->addParameter('charset', 'UTF-8'); $headers->addHeader($ctype); return $message; }
/** * @group ZF2-507 */ public function testDefaultDateHeaderEncodingIsAlwaysAscii() { $this->message->setEncoding('utf-8'); $headers = $this->message->getHeaders(); $header = $headers->get('date'); $date = date('r'); $date = substr($date, 0, 16); $test = $header->getFieldValue(); $test = substr($test, 0, 16); $this->assertEquals($date, $test); }
/** * @param ZendMailInterface $mail * * @return Mail\Message */ protected function createMessage(ZendMailInterface $mail) { $message = new Mail\Message(); $message->getHeaders()->addHeaders($mail->getHeaders()); $message->setTo($mail->getTo()); $message->setCc($mail->getCc()); $message->setBcc($mail->getBcc()); $message->setFrom($mail->getFrom()); $message->setReplyTo($mail->getReplyTo()); $message->setSubject($mail->getSubject()); $message->setBody($this->messageCreator->createMessage($mail)); return $message; }
/** * @param string $to * @param string $toName * @param string $subject * @param string $message * @param string $from * @param string $fromName * * @return bool|FlashMessenger */ public function sendMail($to, $toName, $subject, $message, $from, $fromName) { $transport = new SmtpTransport(); $options = new SmtpOptions(['host' => $this->settings->__invoke('mail', 'host'), 'name' => $this->settings->__invoke('mail', 'name'), 'connection_class' => $this->settings->__invoke('mail', 'connection_class'), 'connection_config' => ['username' => $this->settings->__invoke('mail', 'username'), 'password' => $this->settings->__invoke('mail', 'password'), 'ssl' => $this->settings->__invoke('mail', 'ssl')], 'port' => $this->settings->__invoke('mail', 'port')]); $htmlPart = new MimePart($message); $htmlPart->type = 'text/html'; $body = new MimeMessage(); $body->setParts([$htmlPart]); $mail = new Message(); $mail->setFrom($from, $fromName); $mail->addTo($to, $toName); $mail->setSubject($subject); $mail->setEncoding('UTF-8'); $mail->setBody($body); $mail->getHeaders()->addHeaderLine('MIME-Version: 1.0'); $mail->getHeaders()->addHeaderLine('Content-Type', 'text/html; charset=UTF-8'); try { $transport->setOptions($options); $transport->send($mail); return true; } catch (\Exception $e) { return $this->flashMessenger->addMessage('Email not send', 'error'); } }
public function sendMail() { if (false === $this->checkMailValidity()) { throw new \InvalidArgumentException('E-Mail can not be sent as the required fields where not filled in.'); } $mimeBody = new MimeMessage(); if ($this->mailBodyHtml instanceof ViewModel) { $htmlBodyPart = new MimePart($this->createBodyFromViewModel($this->mailBodyHtml)); $htmlBodyPart->charset = $this->mailCharset; $htmlBodyPart->encoding = $this->mailEncoding; $htmlBodyPart->type = 'text/html'; $mimeBody->addPart($htmlBodyPart); } if ($this->mailBodyText instanceof ViewModel) { $textBodyPart = new MimePart($this->createBodyFromViewModel($this->mailBodyText)); $textBodyPart->charset = $this->mailCharset; $textBodyPart->encoding = $this->mailEncoding; $textBodyPart->type = 'text/plain'; $mimeBody->addPart($textBodyPart); } $mailMessage = new MailMessage(); $mailMessage->setBody($mimeBody); $mailMessage->setEncoding($this->mailEncoding); $mailMessage->setFrom($this->mailFrom); $mailMessage->setSender($this->mailFrom); $mailMessage->setTo($this->mailTo); if ($this->mailBcc != '') { $mailMessage->setBcc($this->mailBcc); } if ($this->mailCc != '') { $mailMessage->setCc($this->mailCc); } $mailMessage->setSubject($this->mailSubject); if (2 <= count($mimeBody->getParts())) { $mailMessage->getHeaders()->get('content-type')->setType('multipart/alternative'); } try { $this->transport->send($mailMessage); return true; } catch (\Exception $e) { throw new \Exception($e); } }
public function enviar() { $body = $this->assunto; $htmlPart = new MimePart($body); $htmlPart->type = "text/html"; $textPart = new MimePart($body); $textPart->type = "text/plain"; $body = new MimeMessage(); $body->setParts(array($textPart, $htmlPart)); $message = new Mail\Message(); $message->setFrom($this->rementente); $message->addTo($this->destinatario); $message->setSubject($this->titulo); $message->setEncoding("UTF-8"); $message->setBody($body); $message->getHeaders()->get('content-type')->setType('multipart/alternative'); $transport = new Mail\Transport\Sendmail(); $transport->send($message); }
/** * @param string | \Zend\View\Model\ViewModel | Mime\Part $body * @return $this */ public function setBody($body, $charset = null) { $mimeMessage = new Mime\Message(); $finalBody = null; if (is_string($body)) { // Create a Mime\Part and wrap it into a Mime\Message $mimePart = new Mime\Part($body); $mimePart->type = $body != strip_tags($body) ? Mime\Mime::TYPE_HTML : Mime\Mime::TYPE_TEXT; $mimePart->charset = $charset ?: self::DEFAULT_CHARSET; $mimeMessage->setParts([$mimePart]); $finalBody = $mimeMessage; } elseif ($body instanceof Mime\Part) { // Overwrite the charset if the Part object if provided if (isset($charset)) { $body->charset = $charset; } // The body is a Mime\Part. Wrap it into a Mime\Message $mimeMessage->setParts([$body]); $finalBody = $mimeMessage; } elseif ($body instanceof ViewModel) { $view = new View(); $view->setResponse(new Response()); $view->getEventManager()->attach(new PhpRendererStrategy($this->renderer)); $view->render($body); $content = $view->getResponse()->getContent(); $mimePart = new Mime\Part($content); $mimePart->type = Mime\Mime::TYPE_HTML; $mimePart->charset = $charset ?: self::DEFAULT_CHARSET; $mimeMessage->setParts([$mimePart]); $finalBody = $mimeMessage; } else { throw new InvalidArgumentException(sprintf('Provided body is not valid. It should be one of "%s". %s provided', implode('", "', ['string', 'Zend\\Mime\\Part', 'Zend\\Mime\\Message', 'Zend\\View\\Model\\ViewModel']), is_object($body) ? get_class($body) : gettype($body))); } // The headers Content-type and Content-transfer-encoding are duplicated every time the body is set. // Removing them before setting the body prevents this error $this->message->getHeaders()->removeHeader('contenttype'); $this->message->getHeaders()->removeHeader('contenttransferencoding'); $this->message->setBody($finalBody); return $this; }
public function sendMail($mail) { // Build the message body $mimeParts = array(); foreach ($mail->getParts() as $part) { $mimePart = new MimePart($part->getContent()); $mimePart->type = $part->getType(); $mimeParts[] = $mimePart; } $body = new MimeMessage(); $body->setParts($mimeParts); // Build the message. $message = new Mail\Message(); $message->setBody($body); // Set the participants foreach ($mail->getParticipants() as $participant) { if ($participant->getComposition() == 'to') { $message->addTo($participant->getAddress(), $participant->getName()); } if ($participant->getComposition() == 'cc') { $message->addCc($participant->getAddress(), $participant->getName()); } if ($participant->getComposition() == 'bcc') { $message->addBcc($participant->getAddress(), $participant->getName()); } if ($participant->getComposition() == 'from') { $message->addFrom($participant->getAddress(), $participant->getName()); } } // Set the subject $message->setSubject($mail->getSubject()); $contentType = $mail->getContentType(); if ($contentType) { $message->getHeaders()->get('content-type')->setType($contentType); } // Create the transport and send. $transport = new SmtpTransport(); $transport->setOptions(new SmtpOptions($this->options)); $transport->send($message); }
public function send($email, $subject, $content, $url = null) { $view = new ViewModel(); $view->setTemplate('email/common'); $view->setVariables(array('title' => $subject, 'content' => $content, 'url' => $url)); $viewRender = $this->getServiceLocator()->get('ViewRenderer'); $htmlBody = $viewRender->render($view); $htmlPart = new MimePart($htmlBody); $htmlPart->type = Mime::TYPE_HTML; $body = new MimeMessage(); $body->setParts(array($htmlPart)); $message = new Message(); $message->setEncoding("UTF-8"); $fromEmail = $this->config['transport']['options']['connection_config']['username']; $message->addFrom($fromEmail, "e财会")->addTo($email)->setSubject($subject); $message->setBody($body); // Set UTF-8 charset $headers = $message->getHeaders(); $headers->removeHeader('Content-Type'); $headers->addHeaderLine('Content-Type', 'text/html; charset=UTF-8'); $this->smtp->send($message); }
/** * @return string|null */ public function parseBody() { try { $htmlView = $this->getRenderer()->render($this->email->getHtmlLayoutName(), array_merge(['content' => $this->personaliseMessage($this->email->getMessage())], $this->templateVars)); $textView = $this->getRenderer()->render('plain', array_merge(['content' => $this->personaliseMessage($this->email->getMessage())], $this->templateVars)); } catch (\Twig_Error_Syntax $e) { $htmlView = $textView = sprintf("Something went wrong with the merge. Error message: %s", $e->getMessage()); } $this->htmlView = $htmlView; //Download the embedded files ad attach them to the mailing $htmlView = $this->embedImagesAsAttachment($htmlView); $htmlContent = new MimePart($htmlView); $htmlContent->type = "text/html"; $textContent = new MimePart($textView); $textContent->type = 'text/plain'; $body = new MimeMessage(); $body->setParts(array_merge($this->attachments, [$htmlContent])); foreach ($this->headers as $name => $value) { $this->message->getHeaders()->addHeaderLine($name, trim($value)); } $this->message->getHeaders()->addHeaderLine('content-type', Mime::MULTIPART_RELATED); $this->message->setBody($body); return true; }
public function testSettingNonAsciiEncodingForcesMimeEncodingOfSomeHeaders() { $this->message->addTo('*****@*****.**', 'ZF DevTeam'); $this->message->addFrom('*****@*****.**', "Matthew Weier O'Phinney"); $this->message->addCc('*****@*****.**', 'ZF Contributors List'); $this->message->addBcc('*****@*****.**', 'ZF CR Team'); $this->message->setSubject('This is a subject'); $this->message->setEncoding('UTF-8'); $test = $this->message->getHeaders()->toString(); $expected = '=?UTF-8?Q?ZF=20DevTeam?='; $this->assertContains($expected, $test); $this->assertContains('<*****@*****.**>', $test); $expected = "=?UTF-8?Q?Matthew=20Weier=20O'Phinney?="; $this->assertContains($expected, $test, $test); $this->assertContains('<*****@*****.**>', $test); $expected = '=?UTF-8?Q?ZF=20Contributors=20List?='; $this->assertContains($expected, $test); $this->assertContains('<*****@*****.**>', $test); $expected = '=?UTF-8?Q?ZF=20CR=20Team?='; $this->assertContains($expected, $test); $this->assertContains('<*****@*****.**>', $test); $expected = 'Subject: =?UTF-8?Q?This=20is=20a=20subject?='; $this->assertContains($expected, $test); }
/** * @param null $body * @param null $mimeType * @return Message */ public function compose($body = null, $mimeType = null) { // Supported types are null, ViewModel and string. if (null !== $body && !is_string($body) && !$body instanceof ViewModel) { throw new InvalidArgumentException('Invalid value supplied. Expected null, string or instance of Zend\\View\\Model\\ViewModel.'); } $bodyParts = $this->getMessageBody($body, $mimeType); $message = new Message(); $message->setBody($bodyParts['body']); /* @var ContentType $contentType */ $contentType = $message->getHeaders()->get('content-type'); $contentType->setType($bodyParts['type']); $message->setEncoding('UTF-8'); return $message; }
/** * Prepare the textual representation of headers * * @param \Zend\Mail\Message $message * @return string */ protected function prepareHeaders(Mail\Message $message) { // On Windows, simply return verbatim if ($this->isWindowsOs()) { return $message->getHeaders()->toString(); } // On *nix platforms, strip the "to" header $headers = clone $message->getHeaders(); $headers->removeHeader('To'); $headers->removeHeader('Subject'); return $headers->toString(); }
public function testMsgHandleUidFetch4() { $path1 = './test_data/test_mailbox_' . date('Ymd_His') . '_' . uniqid('', true); $log = new Logger('test_application'); #$log->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG)); $server = new Server('', 0); $server->setLog($log); $server->init(); $storage1 = new DirectoryStorage(); $storage1->setPath($path1); $server->addStorage($storage1); $client = new Client(); $client->setServer($server); $client->setId(1); $client->setStatus('hasAuth', true); $client->msgHandle('6 select INBOX'); $message1 = new Message(); $message1->addFrom('*****@*****.**'); $message1->addTo('*****@*****.**'); $message1->setSubject('my_subject 1'); $message1->setBody('my_body'); $message1Date = new DateTime($message1->getHeaders()->get('Date')->getFieldValue()); $server->addMail($message1, null, array(), true); $message = new Message(); $message->addFrom('*****@*****.**'); $message->addTo('*****@*****.**'); $message->setSubject('my_subject 2'); $message->setBody('my_body'); $server->addMail($message, null, array(), true); $message = new Message(); $message->addFrom('*****@*****.**'); $message->addTo('*****@*****.**'); $message->setSubject('my_subject 3'); $message->setBody('my_body'); $server->addMail($message, null, array(), true); $message = new Message(); $message->addFrom('*****@*****.**'); $message->addTo('*****@*****.**'); $message->setSubject('my_subject 4'); $message->setBody('my_body'); $server->addMail($message, null, array(), true); $rawMsg = ''; $rawMsg .= '15 UID fetch 100001'; $rawMsg .= ' (UID RFC822.SIZE FLAGS BODY.PEEK'; $rawMsg .= '[HEADER.FIELDS ('; $rawMsg .= 'From To Cc Bcc Subject Date Message-ID Priority X-Priority References'; $rawMsg .= ' Newsgroups In-Reply-To Content-Type Reply-To'; $rawMsg .= ')])'; $msg = $client->msgHandle($rawMsg); $expect = ''; $expect .= '* 1 FETCH (UID 100001 RFC822.SIZE 111 FLAGS (\\Recent) BODY[HEADER] {104}' . Client::MSG_SEPARATOR; $expect .= 'From: dev1@fox21.at' . Client::MSG_SEPARATOR; $expect .= 'To: dev2@fox21.at' . Client::MSG_SEPARATOR; $expect .= 'Subject: my_subject 1' . Client::MSG_SEPARATOR; $expect .= 'Date: ' . $message1Date->format(DateTime::RFC1123) . Client::MSG_SEPARATOR; $expect .= '' . Client::MSG_SEPARATOR; $expect .= ')' . Client::MSG_SEPARATOR; $expect .= '15 OK UID FETCH completed' . Client::MSG_SEPARATOR; $this->assertEquals($expect, $msg); }
function sendEmail($to, $subject, $html, $text, $attachments = null) { // HTML part $htmlPart = new Mime\Part($html); $htmlPart->setEncoding(Mime\Mime::ENCODING_QUOTEDPRINTABLE); $htmlPart->setType(Mime\Mime::TYPE_HTML); // Plain text part $textPart = new Mime\Part($text); $textPart->setEncoding(Mime\Mime::ENCODING_QUOTEDPRINTABLE); $textPart->setType(Mime\Mime::TYPE_TEXT); $body = new Mime\Message(); if ($attachments) { // With attachments, we need a multipart/related email. First part // is itself a multipart/alternative message $content = new Mime\Message(); $content->addPart($textPart); $content->addPart($htmlPart); $contentPart = new Mime\Part($content->generateMessage()); $contentPart->setType(Mime\Mime::MULTIPART_ALTERNATIVE); $contentPart->setBoundary($content->getMime()->boundary()); $body->addPart($contentPart); $messageType = Mime\Mime::MULTIPART_RELATED; // Add each attachment foreach ($attachments as $thisAttachment) { $attachment = new Mime\Part($thisAttachment['content']); $attachment->filename = $thisAttachment['filename']; $attachment->type = Mime\Mime::TYPE_OCTETSTREAM; $attachment->encoding = Mime\Mime::ENCODING_BASE64; $attachment->disposition = Mime\Mime::DISPOSITION_ATTACHMENT; $body->addPart($attachment); } } else { // No attachments, just add the two textual parts to the body $body->setParts([$textPart, $htmlPart]); $messageType = Mime\Mime::MULTIPART_ALTERNATIVE; } // attach the body to the message and set the content-type $message = new Message(); $message->addTo($to); $message->setEncoding($this->encoding); $message->addFrom($this->fromEmail, $this->fromName); $message->setSubject($subject); $message->setBody($body); $message->getHeaders()->get('content-type')->setType($messageType); $this->getTransport()->send($message); }
public function testEmptyHeader() { $message = new Message(array()); $this->assertEquals(array(), $message->getHeaders()); $message = new Message(array()); $subject = null; try { $subject = $message->subject; } catch (\Zend\Exception $e) { // ok } if ($subject) { $this->fail('no exception raised while getting header from empty message'); } }
/** * Send an email to any email address * * @param string $from Email address or string: "name <email>" * @param string $to Email address or string: "name <email>" * @param string $subject The subject of the message * @param string $body The message body * @param array $params Optional parameters (none used in this function) * * @return bool * @throws NotificationException * @since 1.7.2 */ function elgg_send_email($from, $to, $subject, $body, array $params = null) { if (!$from) { $msg = "Missing a required parameter, '" . 'from' . "'"; throw new \NotificationException($msg); } if (!$to) { $msg = "Missing a required parameter, '" . 'to' . "'"; throw new \NotificationException($msg); } $headers = array("Content-Type" => "text/plain; charset=UTF-8; format=flowed", "MIME-Version" => "1.0", "Content-Transfer-Encoding" => "8bit"); // return true/false to stop elgg_send_email() from sending $mail_params = array('to' => $to, 'from' => $from, 'subject' => $subject, 'body' => $body, 'headers' => $headers, 'params' => $params); // $mail_params is passed as both params and return value. The former is for backwards // compatibility. The latter is so handlers can now alter the contents/headers of // the email by returning the array $result = _elgg_services()->hooks->trigger('email', 'system', $mail_params, $mail_params); if (!is_array($result)) { // don't need null check: Handlers can't set a hook value to null! return (bool) $result; } // strip name from to and from $to_address = Address::fromString($result['to']); $from_address = Address::fromString($result['from']); $subject = elgg_strip_tags($result['subject']); $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8'); // Sanitise subject by stripping line endings $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject); $subject = trim($subject); $body = elgg_strip_tags($result['body']); $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8'); $body = wordwrap($body); $message = new Message(); $message->setEncoding('UTF-8'); $message->addFrom($from_address); $message->addTo($to_address); $message->setSubject($subject); $message->setBody($body); foreach ($result['headers'] as $headerName => $headerValue) { $message->getHeaders()->addHeaderLine($headerName, $headerValue); } try { _elgg_services()->mailer->send($message); } catch (\Zend\Mail\Exception\RuntimeException $e) { _elgg_services()->logger->error($e->getMessage()); return false; } return true; }
public function send(Email $email, $params = array()) { $message = new Message(); $config = $this->config; $params = $this->params + $params; if ($email->get('from')) { $fromName = null; if (!empty($params['fromName'])) { $fromName = $params['fromName']; } else { $fromName = $config->get('outboundEmailFromName'); } $message->addFrom(trim($email->get('from')), $fromName); } else { if (!empty($params['fromAddress'])) { $fromAddress = $params['fromAddress']; } else { if (!$config->get('outboundEmailFromAddress')) { throw new Error('outboundEmailFromAddress is not specified in config.'); } $fromAddress = $config->get('outboundEmailFromAddress'); } if (!empty($params['fromName'])) { $fromName = $params['fromName']; } else { $fromName = $config->get('outboundEmailFromName'); } $message->addFrom($fromAddress, $fromName); } if (!empty($params['replyToAddress'])) { $replyToName = null; if (!empty($params['replyToName'])) { $replyToName = $params['replyToName']; } $message->setReplyTo($params['replyToAddress'], $replyToName); } $value = $email->get('to'); if ($value) { $arr = explode(';', $value); if (is_array($arr)) { foreach ($arr as $address) { $message->addTo(trim($address)); } } } $value = $email->get('cc'); if ($value) { $arr = explode(';', $value); if (is_array($arr)) { foreach ($arr as $address) { $message->addCC(trim($address)); } } } $value = $email->get('bcc'); if ($value) { $arr = explode(';', $value); if (is_array($arr)) { foreach ($arr as $address) { $message->addBCC(trim($address)); } } } $message->setSubject($email->get('name')); $body = new MimeMessage(); $parts = array(); $bodyPart = new MimePart($email->getBodyPlainForSending()); $bodyPart->type = 'text/plain'; $bodyPart->charset = 'utf-8'; $parts[] = $bodyPart; if ($email->get('isHtml')) { $bodyPart = new MimePart($email->getBodyForSending()); $bodyPart->type = 'text/html'; $bodyPart->charset = 'utf-8'; $parts[] = $bodyPart; } $aCollection = $email->get('attachments'); if (!empty($aCollection)) { foreach ($aCollection as $a) { $fileName = 'data/upload/' . $a->id; $attachment = new MimePart(file_get_contents($fileName)); $attachment->disposition = Mime::DISPOSITION_ATTACHMENT; $attachment->encoding = Mime::ENCODING_BASE64; $attachment->filename = $a->get('name'); if ($a->get('type')) { $attachment->type = $a->get('type'); } $parts[] = $attachment; } } $aCollection = $email->getInlineAttachments(); if (!empty($aCollection)) { foreach ($aCollection as $a) { $fileName = 'data/upload/' . $a->id; $attachment = new MimePart(file_get_contents($fileName)); $attachment->disposition = Mime::DISPOSITION_INLINE; $attachment->encoding = Mime::ENCODING_BASE64; $attachment->id = $a->id; if ($a->get('type')) { $attachment->type = $a->get('type'); } $parts[] = $attachment; } } $body->setParts($parts); $message->setBody($body); if ($email->get('isHtml')) { $message->getHeaders()->get('content-type')->setType('multipart/alternative'); } try { $this->transport->send($message); $headers = $message->getHeaders(); if ($headers->has('messageId')) { $email->set('messageId', $headers->get('messageId')->getId()); } $email->set('status', 'Sent'); $email->set('dateSent', date("Y-m-d H:i:s")); } catch (\Exception $e) { throw new Error($e->getMessage(), 500); } $this->useGlobal(); }
/** * Compose a new message. * * @param mixed $body Accepts instance of ViewModel, string and null. * @param string $mimeType * * @return \Zend\Mail\Message * @throws \SxMail\Exception\InvalidArgumentException */ public function compose($body = null, $mimeType = null) { // Supported types are null, ViewModel and string. if (null !== $body && !is_string($body) && !$body instanceof ViewModel) { throw new InvalidArgumentException('Invalid value supplied. Expected null, string or instance of Zend\\View\\Model\\ViewModel.'); } $body = $this->manipulateBody($body, $mimeType); $message = new Message(); $message->setBody($body); if ($this->config['message']['generate_alternative_body'] && count($body->getParts()) > 1) { $message->getHeaders()->get('content-type')->setType('multipart/alternative'); } $this->applyMessageHeaders($message); $this->applyMessageOptions($message); return $message; }
/** * Create record feedback form and send feedback to correct recipient. * * @return \Zend\View\Model\ViewModel * @throws \Exception */ public function feedbackAction() { $view = $this->createViewModel(); if ($this->formWasSubmitted('submitFeedback')) { $flashMsg = $this->flashMessenger(); $message = $this->params()->fromPost('feedback_message'); $senderEmail = $this->params()->fromPost('from'); $validator = new \Zend\Validator\EmailAddress(); if (!$validator->isValid($senderEmail)) { $flashMsg->setNamespace('error')->addMessage('Email address is invalid'); return $view; } $driver = $this->loadRecord(); $dataSource = $driver->getDataSource(); $dataSources = $this->getServiceLocator()->get('VuFind\\Config')->get('datasources'); $inst = isset($dataSources->{$dataSource}) ? $dataSources->{$dataSource} : null; $recipientEmail = isset($inst->feedbackEmail) ? $inst->feedbackEmail : null; if ($recipientEmail == null) { throw new \Exception('Feedback Module Error:' . 'Recipient Email Unset (see datasources.ini)'); } $emailSubject = $this->translate('feedback_on_record', ['%%record%%' => $driver->getBreadcrumb()]); $serverUrl = $this->getRequest()->getServer('REQUEST_SCHEME'); $serverUrl .= '://' . $this->getRequest()->getServer('HTTP_HOST'); $emailMessage = "\n" . $this->translate('This email was sent from'); $emailMessage .= ": " . $senderEmail . "\n"; $emailMessage .= "------------------------------------------------------------\n"; // Use the record plugin to render the template for the correct driver $recordPlugin = $this->getViewRenderer()->plugin('record'); $emailMessage .= $recordPlugin($driver)->getEmail(); $emailMessage .= "\n\n------------------------------------------------------------\n"; if (!empty($message)) { $emailMessage .= "\n" . $this->translate('Message From Sender') . ":\n"; $emailMessage .= "\n" . $message . "\n\n"; } // This sets up the email to be sent $mail = new Mail\Message(); $mail->setEncoding('UTF-8'); $mail->setBody($emailMessage); $mail->setFrom($senderEmail); $mail->addTo($recipientEmail); try { $mail->setSubject($emailSubject); } catch (\Exception $e) { // Uhh.. PHP bug https://bugs.php.net/bug.php?id=53891 causes trouble // when trying to encode a subject containing non-ascii characters. // Try to convert the subject to ascii.. // TODO: Remove this when PHP works properly.. $emailSubject = iconv('UTF-8', 'ascii//TRANSLIT', $emailSubject); $mail->setSubject($emailSubject); } $headers = $mail->getHeaders(); $headers->removeHeader('Content-Type'); $headers->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8'); $this->getServiceLocator()->get('VuFind\\Mailer')->getTransport()->send($mail); $flashMsg->addSuccessMessage('Thank you for your feedback.'); if ($this->getRequest()->getQuery('layout', 'no') !== 'lightbox' || 'layout/lightbox' != $this->layout()->getTemplate()) { $this->redirectToRecord(''); } } return $view; }
public function sendEmail($template = 'message', $emailOptions = array()) { $emailOptions = array_merge($this->config, $emailOptions); $content = $this->renderEmail($template, $emailOptions); if ($emailOptions['debug']) { $displays = array(); foreach ($emailOptions as $key => $value) { if ($key !== 'message' && $key != 'attachments') { if (!is_object($value)) { $displays[] = $key . ': <strong>' . (is_array($value) ? implode(',', $value) : $value) . '</strong>'; } else { $displays[] = $key . ': <strong>OBJ</strong>'; } } } echo '<div style=" background-color: #444; padding: 50px; box-shadow: 1px 1px 10px rgba(0,0,0,0.8) inset; "> <div style=" width:80%; margin:10px auto; background-color:#ffffff; box-shadow:1px 2px 5px rgba(0,0,0,0.5); padding: 15px; " > ' . implode(' ; ', $displays) . ' </div> <div style=" width:80%; margin:10px auto; background-color:#ffffff; box-shadow:1px 2px 5px rgba(0,0,0,0.5); " >' . $content . '</div>' . (isset($emailOptions['attachments']) && $emailOptions['attachments'] ? '<div style=" width:80%; margin:10px auto; background-color:#ffffff; box-shadow:1px 2px 5px rgba(0,0,0,0.5); padding: 15px; " >Mit Anhang</div>' : '') . '</div>'; } $attachments = isset($emailOptions['attachments']) && $emailOptions['attachments'] && is_array($emailOptions['attachments']) ? $emailOptions['attachments'] : array(); $message = new Message(); $message->addTo($emailOptions['to']); $message->addFrom($emailOptions['from']); $message->setSubject($emailOptions['subject']); if ($emailOptions['bcc']) { $message->addBcc($emailOptions['bcc']); } if ($emailOptions['cc']) { $message->addCc($emailOptions['cc']); } if ($this->html) { // HTML part $htmlPart = new MimePart($content); $htmlPart->encoding = Mime::ENCODING_QUOTEDPRINTABLE; $htmlPart->type = "text/html; charset=UTF-8"; } // Plain text part $textPart = new MimePart(strip_tags($content)); $textPart->encoding = Mime::ENCODING_QUOTEDPRINTABLE; $textPart->type = "text/plain; charset=UTF-8"; $body = new MimeMessage(); if ($attachments) { // With attachments, we need a multipart/related email. First part // is itself a multipart/alternative message $content = new MimeMessage(); $content->addPart($textPart); if ($this->html) { $content->addPart($htmlPart); } $contentPart = new MimePart($content->generateMessage()); $contentPart->type = "multipart/alternative;\n boundary=\"" . $content->getMime()->boundary() . '"'; $body->addPart($contentPart); $messageType = 'multipart/related'; // Add each attachment foreach ($attachments as $thisAttachment) { $attachment = new MimePart($thisAttachment['buffer']); $attachment->filename = $thisAttachment['filename']; $attachment->type = Mime::TYPE_OCTETSTREAM; $attachment->encoding = Mime::ENCODING_BASE64; $attachment->disposition = Mime::DISPOSITION_ATTACHMENT; $body->addPart($attachment); } } else { // No attachments, just add the two textual parts to the body if ($this->html) { $body->setParts(array($textPart, $htmlPart)); $messageType = 'multipart/alternative'; } else { $body->setParts(array($textPart)); $messageType = 'text/plain'; } } // attach the body to the message and set the content-type $message->setBody($body); $message->getHeaders()->get('content-type')->setType($messageType); $message->setEncoding('UTF-8'); if ($emailOptions['send']) { if (isset($emailOptions['smtp']) && $emailOptions['smtp'] == 'google') { $transport = new SmtpTransport(); $options = new SmtpOptions(array('name' => 'casamail.com', 'host' => 'smtp.gmail.com', 'port' => 465, 'connection_class' => 'login', 'connection_config' => array('username' => $emailOptions['smtp_username'], 'password' => $emailOptions['smtp_password'], 'ssl' => 'ssl'))); $transport->setOptions($options); } else { $transport = new SendmailTransport(); } try { $transport->send($message); } catch (\Exception $e) { if (!get_class($transport) == 'Sendmail') { //try with postfix $transport = new SendmailTransport(); $transport->send($message); } } } else { echo '<h1>E-Mail <strong>NOT</strong> sent</h1>'; } return $content; }
/** * sendMail * @param string $subject * @param array $aMail */ public function sendMail($subject = '', $aMail = array()) { $message = new Message(); $message->setEncoding("UTF-8"); $message->setFrom($this->aMailConf['mailFromMail'], $this->aMailConf['mailFromName']); foreach ($aMail as $mail) { //destinatários $message->addTo($mail); } //assunto $message->setSubject($subject); //cria o corpo da mensagem $body = new MimeMessage(); $contentPart = new MimePart($this->content->generateMessage()); $contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $this->content->getMime()->boundary() . '"'; $messageType = 'multipart/related'; //adiciona o html e o txt $body->addPart($contentPart); foreach ($this->aAttachments as $attachment) { $body->addPart($attachment); } //monta o corpo $message->setBody($body); $message->getHeaders()->get('content-type')->setType($messageType); //enviar try { $this->transport->send($message); } catch (\Zend\Mail\Protocol\Exception\RuntimeException $e) { return $e; } return true; }
/** * @param string $tpl * @param array $data * @return Message */ public function getMessage($tpl, array $data) { $mail = new Message(); $mail->setEncoding('UTF-8'); if (isset($data['encoding'])) { $mail->setEncoding($data['encoding']); } if (isset($data['from_address'])) { if (isset($data['from_name'])) { $mail->setFrom($data['from_address'], $data['from_name']); } else { $mail->setFrom($data['from_address']); } } if (isset($data['to'])) { if (isset($data['to_name'])) { $mail->setTo($data['to'], $data['to_name']); } else { $mail->setTo($data['to']); } } if (isset($data['cc'])) { $mail->setCc($data['cc']); } if (isset($data['bcc'])) { $mail->setBcc($data['bcc']); } if (isset($data['subject'])) { $mail->setSubject($data['subject']); } if (isset($data['sender'])) { $mail->setSender($data['sender']); } if (isset($data['replyTo'])) { $mail->setReplyTo($data['replyTo']); } $content = $this->renderMail($tpl, $data); $mail->setBody($content); $mail->getHeaders()->addHeaderLine('Content-Type', 'text/html; charset=UTF-8')->addHeaderLine('Content-Transfer-Encoding', '8bit'); return $mail; }