public function sendMessage() { $transport = \Swift_SmtpTransport::newInstance($this->mta->address, $this->mta->port); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(); $headers = $message->getHeaders(); $headers->addTextHeader('X-GreenArrow-MailClass', 'SIGMA_NEWEMKTG_DEVEL'); $message->setSubject($this->data->subject); $message->setFrom(array($this->data->fromEmail => $this->data->fromName)); $message->setBody($this->html, 'text/html'); $message->addPart($this->plainText, 'text/plain'); $this->logger->log("Crea contenido del correo para enviar"); foreach ($this->data->target as $to) { $message->setTo($to); $this->logger->log("Preparandose para enviar mensaje a: {$to}"); $recipients = $swift->send($message, $failures); if ($recipients) { \Phalcon\DI::getDefault()->get('logger')->log('Recover Password Message successfully sent!'); } else { throw new Exception('Error while sending message: ' . $failures); } } }
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); }
/** * @param $to * @param $subject * @param $body * @return bool */ public function send($to, $subject, $body) { include_once "vendor/autoload.php"; date_default_timezone_set("Asia/Colombo"); $this->CI->config->load('send_grid'); $username = $this->CI->config->item('send_grid_username'); $password = $this->CI->config->item('send_grid_password'); $smtp_server = $this->CI->config->item('send_grid_smtp_server'); $smtp_server_port = $this->CI->config->item('send_grid_smtp_server_port'); $sending_address = $this->CI->config->item('email_sender_address'); $sending_name = $this->CI->config->item('email_sender_name'); $from = array($sending_address => $sending_name); $to = array($to); $transport = Swift_SmtpTransport::newInstance($smtp_server, $smtp_server_port); $transport->setUsername($username); $transport->setPassword($password); $swift = Swift_Mailer::newInstance($transport); $message = new Swift_Message($subject); $message->setFrom($from); $message->setBody($body, 'text/html'); $message->setTo($to); $message->addPart($body, 'text/plain'); // send message if ($recipients = $swift->send($message, $failures)) { return true; } else { return false; } }
function sendMailConSendGrid($text, $html, $subject, $from, $to) { include_once "lib/php/swift/swift_required.php"; $username = '******'; $password = '******'; // Setup Swift mailer parameters $transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587); $transport->setUsername($username); $transport->setPassword($password); $swift = Swift_Mailer::newInstance($transport); // Create a message (subject) $message = new Swift_Message($subject); // attach the body of the email $message->setFrom($from); $message->setBody($html, 'text/html'); $message->setTo($to); $message->addPart($text, 'text/plain'); // send message $recipients = $swift->send($message, $failures); if ($recipients <= 0) { echo "Something went wrong - "; print_r($failures); $recipients = 0; } return $recipients; }
/** * Creates a swift message from a ParsedMessage, handles defaults * * @param ParsedMessage $parsedMessage * * @return \Swift_Message */ protected function transformMessage(ParsedMessage $parsedMessage) { $message = new \Swift_Message(); if ($from = $parsedMessage->getFrom()) { $message->setFrom($from); } // handle to with defaults if ($to = $parsedMessage->getTo()) { $message->setTo($to); } // handle cc with defaults if ($cc = $parsedMessage->getCc()) { $message->setCc($cc); } // handle bcc with defaults if ($bcc = $parsedMessage->getBcc()) { $message->setBcc($bcc); } // handle reply to with defaults if ($replyTo = $parsedMessage->getReplyTo()) { $message->setReplyTo($replyTo); } // handle subject with default if ($subject = $parsedMessage->getSubject()) { $message->setSubject($subject); } // handle body, no default values here $message->setBody($parsedMessage->getMessageText()); if ($parsedMessage->getMessageHtml()) { $message->addPart($parsedMessage->getMessageHtml(), 'text/html'); } return $message; }
/** * @param string $name * @param array $context * @param callable|null $callback a callback to modify the mail before it is sent. */ public function send($name, array $context = [], callable $callback = null) { $template = $this->twig->loadTemplate($name); $blocks = []; foreach (['from', 'from_name', 'to', 'to_name', 'subject', 'body_txt', 'body_html'] as $blockName) { $rendered = $this->renderBlock($template, $blockName, $context); if ($rendered) { $blocks[$blockName] = $rendered; } } $blocks = array_merge($context, $blocks); $mail = new \Swift_Message(); $mail->setSubject($blocks['subject']); $mail->setFrom(isset($blocks['from_name']) ? [$blocks['from'] => $blocks['from_name']] : $blocks['from']); if (isset($blocks['to'])) { $mail->setTo(isset($blocks['to_name']) ? [$blocks['to'] => $blocks['to_name']] : $blocks['to']); } if (isset($blocks['body_txt']) && isset($blocks['body_html'])) { $mail->setBody($blocks['body_txt']); $mail->addPart($blocks['body_html'], 'text/html'); } elseif (isset($blocks['body_txt'])) { $mail->setBody($blocks['body_txt']); } elseif (isset($blocks['body_html'])) { $mail->setBody($blocks['body_html'], 'text/html'); } if ($callback) { $callback($mail); } $this->mailer->send($mail); }
public function sendEmail($recipient_name, $recipient_email, $subject, $body) { //$subject = 'Hello from Mandrill, PHP!'; $from = array($this::SENDER_EMAIL => $this::SENDER_NAME); $to = array($recipient_email => $recipient_name); //$text = "Mandrill speaks plaintext"; //$html = "<em>Mandrill speaks <strong>HTML</strong></em>"; $transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587); $transport->setUsername($this::MANDRILL_USERNAME); $transport->setPassword($this::MANDRILL_PASSWORD); $swift = Swift_Mailer::newInstance($transport); $message = new Swift_Message($subject); $message->setFrom($from); //$message->setBody($html, 'text/html'); $message->setTo($to); $message->addPart($body, 'text/plain'); $failures = ''; if ($recipients = $swift->send($message, $failures)) { echo 'Message successfully sent!'; return true; } else { echo "There was an error:\n"; print_r($failures); 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; }
public function addPart($body, $contentType = null, $charset = null) { if ($contentType === 'text/html') { $this->_html = (string) $body; } elseif ($contentType === 'text/plain') { $this->_text = (string) $body; } return parent::addPart($body, $contentType, $charset); }
private function preparedMessage($email, $parameters) { $message = new \Swift_Message(); $message->setTo($email); $message->setFrom($this->template->renderBlock('from', $parameters), $this->template->renderBlock('from_name', $parameters)); $message->setSubject($this->template->renderBlock('subject', $parameters)); $message->setBody($this->template->renderBlock('body_text', $parameters)); $message->addPart($this->template->renderBlock('body_html', $parameters), 'text/html'); return $message; }
public function testMultipartHtmlFirst() { $transport = $this->createTransport(); $message = new \Swift_Message('Test Subject', '<p>Foo bar</p>', 'text/html'); $message->addPart('Foo bar', 'text/plain')->addTo('*****@*****.**', 'To Name')->addFrom('*****@*****.**', 'From Name'); $mandrillMessage = $transport->getMandrillMessage($message); $this->assertEquals('Foo bar', $mandrillMessage['text'], 'Multipart email should contain plaintext message'); $this->assertEquals('<p>Foo bar</p>', $mandrillMessage['html'], 'Multipart email should contain HTML message'); $this->assertMessageSendable($message); }
/** * Sends an email * @param \Swift_Message $message An email message * @param string $content The message body in HTML * @return int The number of recipients the message was delivered to */ protected static function sendEmail(\Swift_Message $message, $content) { // Lazy mailer instantiation if (!self::$mailer) { self::$mailer = \Swift_Mailer::newInstance(\Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_SERVER_PORT)); } $message->setBody($content, 'text/html', 'utf-8'); $message->addPart(\Html2Text\Html2Text::convert(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')), 'text/plain', 'utf-8'); return self::$mailer->send($message); }
protected function _mapToSwift(Mail $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->getFrom()); $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); } // determine whether or not we can use SMTP recipients (non header based) if ($mail->useHeaders()) { //send header based email $message->setTo($mail->getFrom()); //here we'll add the recipients list to the headers $headers = $mail->getHeaders(); $headers['to'] = $mail->getTos(); $mail->setHeaders($headers); } else { $recipients = array(); foreach ($mail->getTos() as $recipient) { if (preg_match("/(.*)<(.*)>/", $recipient, $results)) { $recipients[trim($results[2])] = trim($results[1]); } else { $recipients[] = $recipient; } } $message->setTo($recipients); } $attachments = $mail->getAttachments(); //add any attachments that were added if ($attachments) { foreach ($attachments as $attachment) { $message->attach(\Swift_Attachment::fromPath($attachment['file'])); } } //add all the headers $headers = $message->getHeaders(); $headers->addTextHeader('X-SMTPAPI', $mail->getHeadersJson()); return $message; }
public function testTransportSendMultipart() { $container = $this->createContainer(); /** @var MandrillTransport $transport */ $transport = $container->get('swiftmailer.mailer.transport.accord_mandrill'); $message = new \Swift_Message('TEST SUBJECT', '<p>test html body<p>', 'text/html'); $message->setTo('*****@*****.**'); $message->setFrom('*****@*****.**'); $message->addPart('test text body', 'text/plain'); $result = $transport->send($message); $this->assertEquals(1, $result, 'One multipart message should have been sent to Mandrill'); }
function send_breakin_alert($email, $password) { $transporter = new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'); $transporter->setUsername(''); $transporter->setPassword(''); $message = new Swift_Message($transporter); $message->setTo(array($email => $email)); $message->setSubject("Note to Myself - Break-in Attempt"); $message->addPart("Your password has been reset after 3 failed log-in attempts.</br>Your new password is <strong>{$password}</strong>", 'text/html'); $message->setFrom("", ""); $mailer = new Swift_Mailer($transporter); $mailer->send($message); }
/** * Add html and plain text bodies or only plain text if html is empty. * * @param \Swift_Message $message The swiftmailer message * @param MailRenderedInterface $mailRendered The rendered mail */ protected function addBodies(\Swift_Message $message, MailRenderedInterface $mailRendered) { $textPlain = $mailRendered->getBody(); $html = $mailRendered->getHtmlBody(); if (null === $html) { $message->setBody($textPlain, 'text/plain'); return; } $message->setBody($html, 'text/html'); if (null !== $textPlain) { $message->addPart($textPlain, 'text/plain'); } }
/** * send * * @return void */ public function send() { try { $this->message = Swift_Message::newInstance()->setSubject($this->template->getSubject())->setCharset("utf-8"); switch ($this->type) { case self::TYPE_PLAIN: $this->message->setBody($this->template->getPlain(), 'text/plain'); break; case self::TYPE_HTML: $html_body = $this->template->getHtml(); if ($this->hasEmbedImage()) { $html_body = $this->embedImages($html_body); } $this->message->setBody($html_body, 'text/html'); break; case self::TYPE_BOTH: default: $html_body = $this->template->getHtml(); if ($this->hasEmbedImage()) { $html_body = $this->embedImages($html_body); } $this->message->setBody($html_body, 'text/html'); $this->message->addPart($this->template->getPlain(), 'text/plain'); break; } if ($this->getAttribute('reply')) { $this->message->setReplyTo($this->getAttribute('reply')); } $this->message->setFrom($this->getAttribute('from'))->setTo($this->getAttribute('to')); $this->getMailer()->send($this->message); } catch (Exception $exception) { if ($this->getTransport() && $this->getTransport()->isStarted()) { $this->disconnect(); } throw $exception; } }
/** * Send mail to the newly registered member */ public function SendMail() { //Mail1234 //$html = '<html> <body> <p> This is a fake email just for testing purpose </p></body>'; $transport = Swift_SmtpTransport::newInstance('smtp.ipage.com', 465, 'ssl'); $transport->setUsername('*****@*****.**'); $transport->setPassword('Mail1234'); $swift = Swift_Mailer::newInstance($transport); $message = new Swift_Message($this->subject); $message->setFrom($this->from); $message->setBody($this->body, 'text/html'); $message->setTo($this->to); $message->addPart("testing text", 'text/plain'); $swift->send($message, $failures); }
/** * 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); } } }
function SendEmail($to, $subject, $body, $task_id = null) { global $fs, $proj, $user; if (empty($to) || empty($to[0])) { return; } // Do we want to use a remote mail server? if (!empty($fs->prefs['smtp_server'])) { // connection... SSL, TLS or none if ($fs->prefs['email_tls']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls'); } else { if ($fs->prefs['email_ssl']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl'); } else { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']); } } if ($fs->prefs['smtp_user']) { $swiftconn->setUsername($fs->prefs['smtp_user']); } if ($fs->prefs['smtp_pass']) { $swiftconn->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $swiftconn->setTimeout(FS_SMTP_TIMEOUT); } // Use php's built-in mail() function } else { $swiftconn = Swift_MailTransport::newInstance(); } if (defined('FS_MAIL_LOGFILE')) { // FIXME: Swift_LogContainer exists no more??? // See http://swiftmailer.org/docs/plugins.html#logger-plugin // for the new implementation. // $log = Swift_LogContainer::getLog(); // $log->setLogLevel(SWIFT_LOG_EVERYTHING); } // Make plaintext URLs into hyperlinks, but don't disturb existing ones! $htmlbody = preg_replace("/(?<!\")(https?:\\/\\/)([a-zA-Z0-9\\-.]+\\.[a-zA-Z0-9\\-]+([\\/]([a-zA-Z0-9_\\/\\-.?&%=+#])*)*)/", '<a href="$1$2">$2</a>', $body); $htmlbody = str_replace("\n", "<br>", $htmlbody); // Those constants used were introduced in 5.4. if (version_compare(phpversion(), '5.4.0', '<')) { $plainbody = html_entity_decode(strip_tags($body)); } else { $plainbody = html_entity_decode(strip_tags($body), ENT_COMPAT | ENT_HTML401, 'utf-8'); } $swift = Swift_Mailer::newInstance($swiftconn); $message = new Swift_Message($subject); if (isset($fs->prefs['emailNoHTML']) && $fs->prefs['emailNoHTML'] == '1') { $message->setBody($plainbody, 'text/plain'); } else { $message->setBody($htmlbody, 'text/html'); $message->addPart($plainbody, 'text/plain'); } $type = $message->getHeaders()->get('Content-Type'); $type->setParameter('charset', 'utf-8'); $message->getHeaders()->addTextHeader('Precedence', 'list'); $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray'); if ($proj->prefs['notify_reply']) { $message->setReplyTo($proj->prefs['notify_reply']); } if (isset($task_id)) { $hostdata = parse_url($GLOBALS['baseurl']); $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']); // see http://cr.yp.to/immhf/thread.html this does not seems to work though :( $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto); $message->getHeaders()->addTextHeader('References', $inreplyto); } // now accepts string , array or Swift_Address. $message->setTo($to); $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title'])); $swift->send($message); /* FIXME: Swift_LogContainer exists no more??? if(defined('FS_MAIL_LOGFILE')) { if(is_writable(dirname(FS_MAIL_LOGFILE))) { if($fh = fopen(FS_MAIL_LOGFILE, 'ab')) { fwrite($fh, $log->dump(true)); fwrite($fh, php_uname()); fclose($fh); } } } */ return true; }
/** * Send the e-mail * * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The * method takes an unlimited number of recipient addresses. * * @return boolean True if the e-mail was sent successfully */ public function sendTo() { $arrRecipients = $this->compileRecipients(func_get_args()); if (empty($arrRecipients)) { return false; } $this->objMessage->setTo($arrRecipients); $this->objMessage->setCharset($this->strCharset); $this->objMessage->setPriority($this->intPriority); // Default subject if ($this->strSubject == '') { $this->strSubject = 'No subject'; } $this->objMessage->setSubject($this->strSubject); // HTML e-mail if ($this->strHtml != '') { // Embed images if ($this->blnEmbedImages) { if ($this->strImageDir == '') { $this->strImageDir = TL_ROOT . '/'; } $arrMatches = array(); preg_match_all('/(src=|url\\()"([^"]+\\.(jpe?g|png|gif|bmp|tiff?|swf))"/Ui', $this->strHtml, $arrMatches); $strBase = \Environment::get('base'); // Check for internal images foreach (array_unique($arrMatches[2]) as $url) { // Try to remove the base URL $src = str_replace($strBase, '', $url); $src = rawurldecode($src); // see #3713 // Embed the image if the URL is now relative if (!preg_match('@^https?://@', $src) && file_exists($this->strImageDir . $src)) { $cid = $this->objMessage->embed(\Swift_EmbeddedFile::fromPath($this->strImageDir . $src)); $this->strHtml = str_replace(array('src="' . $url . '"', 'url("' . $url . '"'), array('src="' . $cid . '"', 'url("' . $cid . '"'), $this->strHtml); } } } $this->objMessage->setBody($this->strHtml, 'text/html'); } // Text content if ($this->strText != '') { if ($this->strHtml != '') { $this->objMessage->addPart($this->strText, 'text/plain'); } else { $this->objMessage->setBody($this->strText, 'text/plain'); } } // Add the administrator e-mail as default sender if ($this->strSender == '') { list($this->strSenderName, $this->strSender) = $this->splitFriendlyName($GLOBALS['TL_CONFIG']['adminEmail']); } // Sender if ($this->strSenderName != '') { $this->objMessage->setFrom(array($this->strSender => $this->strSenderName)); } else { $this->objMessage->setFrom($this->strSender); } // Send e-mail $intSent = self::$objMailer->send($this->objMessage, $this->arrFailures); // Log failures if (!empty($this->arrFailures)) { log_message('E-mail address rejected: ' . implode(', ', $this->arrFailures), $this->strLogFile); } // Return if no e-mails have been sent if ($intSent < 1) { return false; } $arrCc = $this->objMessage->getCc(); $arrBcc = $this->objMessage->getBcc(); // Add a log entry $strMessage = 'An e-mail has been sent to ' . implode(', ', array_keys($this->objMessage->getTo())); if (!empty($arrCc)) { $strMessage .= ', CC to ' . implode(', ', array_keys($arrCc)); } if (!empty($arrBcc)) { $strMessage .= ', BCC to ' . implode(', ', array_keys($arrBcc)); } log_message($strMessage, $this->strLogFile); return true; }
function addPart($body, $contentType = null, $charset = null) { return $this->_message->addPart($body, $contentType, $charset); }
/** * Creating the message Body Section. * * @return MailInterface The current instance */ protected function buildBody() : MailInterface { null === $this->get('htmlBody') ? $this->swiftMessage->setBody($this->get('textBody'), self::MIME_TEXT) : $this->swiftMessage->setBody($this->get('htmlBody'), self::MIME_HTML); null !== $this->get('htmlBody') && null !== $this->get('textBody') ? $this->swiftMessage->addPart($this->get('textBody'), self::MIME_TEXT) : null; return $this; }
/** * Создаём почту, используя метод addPart */ function useAddPart() { $this->_message->addPart($this->_xml, 'text/xml'); }
/** * Render a swift message with twig blocks * @param $template string template name * @param array $parameters * @param \Swift_Message $message * @return \Swift_Message * @throws InvalidTemplateException If template doesn't have the required blocks */ public function getMessage($template, $parameters = array(), \Swift_Message $message = null) { $text = $this->renderBlock($template, self::FORMAT_TEXT, $parameters); $html = $this->renderBlock($template, self::FORMAT_HTML, $parameters); $subject = $this->renderBlock($template, self::FORMAT_SUBJECT, $parameters); // Throw exception if html/text is empty if (empty($html) && empty($text)) { $blockNames = []; foreach ([self::FORMAT_HTML, self::FORMAT_TEXT] as $format) { $blockNames[] = $this->getBlockName($format); } throw new InvalidTemplateException($template, $blockNames); } // Throw exception if subject is empty if (empty($subject)) { throw new InvalidTemplateException($template, [$this->getBlockName(self::FORMAT_SUBJECT)]); } // Create message if ($message === null) { $message = new \Swift_Message(); } $message->setSubject($subject); // We add html as body when possible to avoid rendering text in email-client if (!empty($html)) { $message->setBody($html, "text/html"); if (!empty($text)) { $message->addPart($text, "text/plain"); } } else { // Fallback to plain text $message->setBody($text); } return $message; }
/** * Add a subject and a body (TEXT, HTML or both, depending on the message * configuration. */ public function buildMessage($parser, \Swift_Message $messageInstance) { $parser->setTemplateDefinition(TemplateHelper::getInstance()->getActiveMailTemplate()); $subject = $parser->fetch(sprintf("string:%s", $this->getSubject())); $htmlMessage = $this->getHtmlMessageBody($parser); $textMessage = $this->getTextMessageBody($parser); $messageInstance->setSubject($subject); // If we do not have an HTML message if (empty($htmlMessage)) { // Message body is the text message $messageInstance->setBody($textMessage, 'text/plain'); } else { // The main body is the HTML messahe $messageInstance->setBody($htmlMessage, 'text/html'); // Use the text as a message part, if we have one. if (!empty($textMessage)) { $messageInstance->addPart($textMessage, 'text/plain'); } } return $messageInstance; }
$from = array('*****@*****.**' => 'IT IGSA'); // Email recipients $to = array('*****@*****.**' => $name, '*****@*****.**' => $name); // // Login credentials // $username = '******'; // $password = '******'; // // // Setup Swift mailer parameters // $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl'); $username = "******"; $password = "******"; $transport = Swift_SmtpTransport::newInstance('smtp-mail.outlook.com', 25, 'tls'); $transport->setUsername($username); $transport->setPassword($password); $swift = Swift_Mailer::newInstance($transport); // Create a message (subject) $message = new Swift_Message($subject); // attach the body of the email $message->setFrom($from); $message->setBody($html, 'text/html'); $message->setTo($to); $message->addPart($text, 'text/plain'); // send message if ($recipients = $swift->send($message, $failures)) { // This will let us know how many users received this message echo 'Message sent out to ' . $recipients . ' users'; } else { echo "Something went wrong - "; print_r($failures); } //header('location:/');
public function testEmbeddedFilesWithMultipartDataCreateMultipartRelatedContentAsAnAlternative() { $message = new Swift_Message(); $message->setCharset('utf-8'); $message->setSubject('test subject'); $message->addPart('plain part', 'text/plain'); $image = new Swift_Image('<image data>', 'image.gif', 'image/gif'); $cid = $message->embed($image); $message->setBody('<img src="' . $cid . '" />', 'text/html'); $message->setTo(array('*****@*****.**' => 'User')); $message->setFrom(array('*****@*****.**' => 'Other')); $message->setSender(array('*****@*****.**' => 'Other')); $id = $message->getId(); $date = preg_quote(date('r', $message->getDate()), '~'); $boundary = $message->getBoundary(); $cidVal = $image->getId(); $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/alternative;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\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" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/related;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\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" . '<img.*?/>' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: image/gif; name=image.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: inline; filename=image.gif' . "\r\n" . 'Content-ID: <' . $cidVal . '>' . "\r\n" . "\r\n" . preg_quote(base64_encode('<image data>'), '~') . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString()); }
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()); }
/** * Send the e-mail * * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The * method takes an unlimited number of recipient addresses. * * @return boolean True if the e-mail was sent successfully */ public function sendTo() { $arrRecipients = $this->compileRecipients(func_get_args()); if (empty($arrRecipients)) { return false; } $this->objMessage->setTo($arrRecipients); $this->objMessage->setCharset($this->strCharset); $this->objMessage->setPriority($this->intPriority); // Default subject if ($this->strSubject == '') { $this->strSubject = 'No subject'; } $this->objMessage->setSubject($this->strSubject); // HTML e-mail if ($this->strHtml != '') { // Embed images if ($this->blnEmbedImages) { if ($this->strImageDir == '') { $this->strImageDir = TL_ROOT . '/'; } $arrCid = array(); $arrMatches = array(); $strBase = \Environment::get('base'); // Thanks to @ofriedrich and @aschempp (see #4562) preg_match_all('/<[a-z][a-z0-9]*\\b[^>]*((src=|background=|url\\()["\']??)(.+\\.(jpe?g|png|gif|bmp|tiff?|swf))(["\' ]??(\\)??))[^>]*>/Ui', $this->strHtml, $arrMatches); // Check for internal images if (!empty($arrMatches) && isset($arrMatches[0])) { for ($i = 0, $c = count($arrMatches[0]); $i < $c; $i++) { $url = $arrMatches[3][$i]; // Try to remove the base URL $src = str_replace($strBase, '', $url); $src = rawurldecode($src); // see #3713 // Embed the image if the URL is now relative if (!preg_match('@^https?://@', $src) && file_exists($this->strImageDir . $src)) { if (!isset($arrCid[$src])) { $arrCid[$src] = $this->objMessage->embed(\Swift_EmbeddedFile::fromPath($this->strImageDir . $src)); } $this->strHtml = str_replace($arrMatches[1][$i] . $arrMatches[3][$i] . $arrMatches[5][$i], $arrMatches[1][$i] . $arrCid[$src] . $arrMatches[5][$i], $this->strHtml); } } } } $this->objMessage->setBody($this->strHtml, 'text/html'); } // Text content if ($this->strText != '') { if ($this->strHtml != '') { $this->objMessage->addPart($this->strText, 'text/plain'); } else { $this->objMessage->setBody($this->strText, 'text/plain'); } } // Add the administrator e-mail as default sender if ($this->strSender == '') { list($this->strSenderName, $this->strSender) = \String::splitFriendlyEmail(\Config::get('adminEmail')); } // Sender if ($this->strSenderName != '') { $this->objMessage->setFrom(array($this->strSender => $this->strSenderName)); } else { $this->objMessage->setFrom($this->strSender); } // Set the return path (see #5004) $this->objMessage->setReturnPath($this->strSender); // Send e-mail $intSent = self::$objMailer->send($this->objMessage, $this->arrFailures); // Log failures if (!empty($this->arrFailures)) { log_message('E-mail address rejected: ' . implode(', ', $this->arrFailures), $this->strLogFile); } // Return if no e-mails have been sent if ($intSent < 1) { return false; } $arrCc = $this->objMessage->getCc(); $arrBcc = $this->objMessage->getBcc(); // Add a log entry $strMessage = 'An e-mail has been sent to ' . implode(', ', array_keys($this->objMessage->getTo())); if (!empty($arrCc)) { $strMessage .= ', CC to ' . implode(', ', array_keys($arrCc)); } if (!empty($arrBcc)) { $strMessage .= ', BCC to ' . implode(', ', array_keys($arrBcc)); } log_message($strMessage, $this->strLogFile); return true; }