function send() { $headers = array('From' => $this->from, 'To' => $this->to, 'Subject' => $this->subject); $mime = new Mail_mime(array('eol' => "\n")); $mime->setHTMLBody($this->html); foreach ($this->images as $image) { $sucess[] = $mime->addHTMLImage($image, "image/png"); } $smtp = Mail::factory('smtp', array('host' => $this->host, 'auth' => true, 'username' => $this->u, 'password' => $this->p)); $body = $mime->get(); $headers = $mime->headers($headers); $mail = $smtp->send($this->to, $headers, $body); if (PEAR::isError($mail)) { //echo("<p>" . $mail->getMessage() . "</p>"); return false; } return true; }
/** * Send the ecard. */ public function send($id) { $item = ORM::factory("item", $id); access::required("view", $item); if (!ecard::can_send_ecard()) { access::forbidden(); } $form = ecard::get_send_form($item); try { $valid = $form->validate(); } catch (ORM_Validation_Exception $e) { // Translate ORM validation errors into form error messages foreach ($e->validation->errors() as $key => $error) { $form->edit_item->inputs[$key]->add_error($error, 1); } $valid = false; } if ($valid) { $v = new View("ecard_email.html"); $v->item = $item; $v->subject = module::get_var("ecard", "subject"); $to_name = $form->send_ecard->to_name->value; $from_name = $form->send_ecard->from_name->value; $bcc = module::get_var("ecard", "bcc"); $v->message = t(module::get_var("ecard", "message"), array("toname" => $to_name, "fromname" => $from_name)); $v->custom_message = $form->send_ecard->text->value; $v->image = $item->name; $to = $form->send_ecard->inputs["to_email"]->value; $from = $form->send_ecard->inputs["from_email"]->value; $headers = array("from" => $from_name . "<" . $from . ">", "to" => $to, "subject" => module::get_var("ecard", "subject")); require_once MODPATH . "ecard/lib/mime.php"; $mime = new Mail_mime("\n"); $mime->setHTMLBody($v->render()); $mime->addHTMLImage($item->resize_path(), $item->mime_type, $item->name); $body = $mime->get(array('html_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'text_encoding' => '8bit', 'head_charset' => 'UTF-8')); self::_notify($headers['to'], $headers['from'], $headers['subject'], $item, $body, $mime->headers(), $bcc); message::success("eCard successfully sent"); json::reply(array("result" => "success")); } else { json::reply(array("result" => "error", "html" => (string) $form)); } }
// Generate image attach $graphs = json_decode($message_tags_html['ENTITY_GRAPHS_ARRAY'], TRUE); //print_vars($graphs); if (is_array($graphs) && count($graphs)) { $message_tags_html['ENTITY_GRAPHS'] = ''; // Reinit graphs html foreach ($graphs as $key => $graph) { $cid = $graph['type'] . $key; // Unencode data uri tag to file content list($gmime, $base64) = explode(';', $graph['data'], 2); $gmime = substr($gmime, 5); $base64 = substr($base64, 7); //print_vars(substr($graph['data'], 0, 20)); //print_vars($gmime); //print_vars(substr($base64, 0, 20)); $mime->addHTMLImage(base64_decode($base64), $gmime, $cid . '.png', FALSE, $cid); $message_tags_html['ENTITY_GRAPHS'] .= '<h4>' . $graph['type'] . '</h4>'; $message_tags_html['ENTITY_GRAPHS'] .= '<a href="' . $graph['url'] . '"><img src="cid:' . $cid . '"></a><br />'; } } //print_vars($message_tags_html); $message['html'] = simple_template('email_html', $message_tags_html, array('is_file' => TRUE)); unset($message_tags_html); foreach ($message as $part => $part_body) { switch ($part) { case 'text': case 'txt': case 'plain': $part_body .= "\n\nE-mail sent to: {$rcpts}\n"; $part_body .= "E-mail sent at: {$time_sent}\n\n"; $part_body .= "-- \n" . OBSERVIUM_PRODUCT_LONG . ' ' . OBSERVIUM_VERSION . "\n" . OBSERVIUM_URL . "\n";
private function sendMimeEmail($toAddr, $emailBody, $destinationType) { $crlf = "\r\n"; $hdrs = array('From' => '*****@*****.**', 'Subject' => 'Hot Lead - stlbridalpros'); $mime = new Mail_mime($crlf); if ($destinationType == DESTINATIONTYPE::MMSTEXT || $destinationType == DESTINATIONTYPE::SMSTEXT) { $mime->setTXTBody($emailBody); } if ($destinationType == DESTINATIONTYPE::EMAIL) { $mime->addHTMLImage("images/stlbridalprosLogo_200x180.jpg", "image/jpeg"); $cid = $mime->_html_images[count($mime->_html_images) - 1]['cid']; $html = '<html><style>.colored{color:#aa0000;}#header{text-align:center;margin-bottom:20px;font-weight:bold;font-size:18px}#headerText{margin-left:15px;}</style><body><div id="header"><img src="cid:' . $cid . '"><span id="headerText"><p>St. Louis Bridal Pros<p><p>Hot Lead</p></span></div>' . $emailBody . '</body></html>'; $mime->setHTMLBody($html); } $body = $mime->get(); $hdrs = $mime->headers($hdrs); $mail =& Mail::factory('mail'); $mail->send($toAddr, $hdrs, $body); }
/** * Положить письмо в очередь * * @param string $recipient * @param string $from * @param string $subject * @param string $message * @param string HTML-сообщение * * Чтобы отправить сообщение в формате HTML, нужно указать параметр html_message. * При этом параметр message должен содержать сообщение в plain text или может быть пустым * * Чтобы отправить plain text, параметр html_message нужно оставить пустым. */ function nc_mail2queue($recipient, $from, $subject, $message, $html_message = "", $attachment_type = "") { require_once "Mail/Queue.php"; $db_options = array('type' => 'ezsql', 'mail_table' => 'Mail_Queue'); $mail_options = array('driver' => 'mail'); $mail_queue = new Mail_Queue($db_options, $mail_options); $hdrs = array('From' => $from, 'Subject' => nc_base64_encode_header($subject)); $mime = new Mail_mime("\n"); if ($attachment_type) { $nc_core = nc_Core::get_object(); $db = $nc_core->db; $type_escaped = $db->escape($attachment_type); $sql = "SELECT `Filename`, `Path`, `Content_Type`, `Extension` FROM `Mail_Attachment` WHERE `Type` = '{$type_escaped}'"; $attachments = (array) $db->get_results($sql, ARRAY_A); while (preg_match('/\\%FILE_([-_a-z0-9]+)/i', $html_message, $match)) { $filename = $match[1]; $file = false; foreach ($attachments as $index => $attachment) { if (strtolower($attachment['Filename']) == strtolower($filename)) { $file = $attachment; unset($attachments[$index]); break; } } $replace = ''; if ($file) { $absolute_path = $nc_core->DOCUMENT_ROOT . $file['Path']; $replace = 'file_' . $filename . '.' . $file['Extension']; $mime->addHTMLImage(@file_get_contents($absolute_path), $file['Content_Type'], $replace, false); } $html_message = preg_replace('/\\%FILE_' . preg_quote($filename) . '/', $replace, $html_message); } foreach ($attachments as $attachment) { $absolute_path = $nc_core->DOCUMENT_ROOT . $attachment['Path']; $mime->addAttachment($absolute_path, $attachment['Content_Type'], $attachment['Filename'] . '.' . $attachment['Extension']); } } if ($message) { $mime->setTXTBody($message); } if ($html_message) { $mime->setHTMLBody($html_message); } $body = $mime->get(array('text_encoding' => '8bit', 'html_charset' => MAIN_EMAIL_ENCODING, 'text_charset' => MAIN_EMAIL_ENCODING, 'head_charset' => MAIN_EMAIL_ENCODING)); $hdrs = $mime->headers($hdrs); $mail_queue->put($from, $recipient, $hdrs, $body); }
function send_quarantine_email($email, $filter, $quarantined) { global $html, $html_table, $html_content, $text, $text_content; // Setup variables to prevent warnings $h1 = ""; $t1 = ""; // Build the quarantine list for this recipient foreach ($quarantined as $qitem) { // HTML Version $h1 .= sprintf($html_content, $qitem['datetime'], $qitem['to'], $qitem['from'], $qitem['subject'], $qitem['reason'], '<a href="' . QUARANTINE_REPORT_HOSTURL . '/viewmail.php?id=' . $qitem['id'] . '">View</a>'); // Text Version $t1 .= sprintf($text_content, strip_tags($qitem['datetime']), $qitem['to'], $qitem['from'], $qitem['subject'], $qitem['reason'], '<a href="' . QUARANTINE_REPORT_HOSTURL . '/viewmail.php?id=' . $qitem['id'] . '">View</a>'); } // HTML $h2 = sprintf($html_table, $h1); $html_report = sprintf($html, $filter, QUARANTINE_REPORT_DAYS, count($quarantined), QUARANTINE_DAYS_TO_KEEP, $h2); if (DEBUG) { echo $html_report; } // Text $text_report = sprintf($text, $filter, QUARANTINE_REPORT_DAYS, count($quarantined), QUARANTINE_DAYS_TO_KEEP, $t1); if (DEBUG) { echo "<pre>{$text_report}</pre>\n"; } // Send e-mail $mime = new Mail_mime("\n"); $hdrs = array('From' => QUARANTINE_REPORT_FROM_NAME . ' <' . QUARANTINE_FROM_ADDR . '>', 'To' => $email, 'Subject' => QUARANTINE_REPORT_SUBJECT, 'Date' => date("r")); $mime->addHTMLImage(MAILWATCH_HOME . '/images/mailwatch-logo.png', 'image/png', 'mailwatch-logo.png', true); $mime->setTXTBody($text_report); $mime->setHTMLBody($html_report); $body = $mime->get(); $hdrs = $mime->headers($hdrs); $mail_param = array('host' => QUARANTINE_MAIL_HOST); $mail =& Mail::factory('smtp', $mail_param); $mail->send($email, $hdrs, $body); dbg(" ==== Sent e-mail to {$email}"); }
/** * Send mail * * @return boolean */ public function send() { if (!strlen($this->_transferMethod)) { throw new Gpf_Exception('Mail Transfer Method not set!'); } if (!strlen($this->_recipients)) { throw new Gpf_Exception($this->_("Recipients empty")); } if (!($method = $this->createMethod($this->_transferMethod, $this->_transferParams))) { throw new Gpf_Exception("Cannot instantiate mail method: " . $this->_transferMethod); } $mail = new Mail_mime("\n"); $mail->_build_params['html_charset'] = 'UTF-8'; $mail->_build_params['text_charset'] = 'UTF-8'; $mail->_build_params['head_charset'] = 'UTF-8'; if (defined('MAIL_HEADER_ENCODING_BASE64')) { $mail->_build_params['head_encoding'] = 'base64'; } if (strlen($this->_htmlbody)) { $mail->setHTMLBody($this->_htmlbody); if (strlen($this->_txtbody)) { $mail->setTXTBody($this->_txtbody); } else { $mail->setTXTBody(Gpf_Mail_Html2Text::convert($this->_htmlbody)); } } else { if (strlen($this->_txtbody)) { $mail->setTXTBody($this->_txtbody); } else { throw new Gpf_Exception($this->_("Body of mail not specified")); } } foreach ($this->_attachments as $attachment) { if (is_array($attachment)) { if (strlen($attachment['content'])) { $ret = $mail->addAttachment($attachment['content'], $attachment['filetype'], $attachment['filename'], false); } else { $ret = $mail->addAttachment($attachment['filename'], $attachment['filetype'], $attachment['filename'], true); } } else { throw new Gpf_Exception('Unknown attachment type'); } if (PEAR::isError($ret)) { throw new Gpf_Exception("Adding attachment error: " . $ret->getMessage()); } } foreach ($this->_images as $image) { if (strlen($image['content'])) { $ret = $mail->addHTMLImage($image['content'], $this->getImageContentType($image['filename']), $image['filename'], false); } else { $ret = $mail->addHTMLImage($image['filename'], $this->getImageContentType($image['filename']), $image['filename'], true); } if (PEAR::isError($ret)) { throw new Gpf_Exception("Adding image error: " . $ret->getMessage()); } } if (!$this->initHeaders()) { throw new Gpf_Exception($this->_('Failed to init mail headers')); } if (!$method instanceof Mail) { throw new Gpf_Exception($this->_('Email transfer method error')); } $body = $mail->get(); $ret = $method->send($this->_recipients, $mail->headers($this->_headers), $body); if (PEAR::isError($ret)) { throw new Gpf_Exception($ret->getMessage()); } return true; }
$errstatus = false; if ($mailerstatus) { //Email Customization $subject = ""; //Email Subject $text = 'Wishes from University Health Centre'; //email Text $subject = 'Birthday Wishes : Many more Happy Returns...'; //email headers $headers = array('From' => $email_From, 'Subject' => $subject); $crlf = "\r\n"; $mime = new Mail_mime($crlf); //get mime mail object in order to set headers $cid = ""; //content id for the images $mime->addHTMLImage("../img/templates/email/bdemail12.jpg", "image/jpg"); //here's the butt-ugly bit where we grab the content id $cid = $mime->_html_images[count($mime->_html_images) - 1]['cid']; $html = ' <html> <head> <title>Birthday wishes </title> </head> <body> <img src="cid:' . $cid . '" /> </body> </html> '; //html content in order to Email students $mime->setTXTBody($text); $mime->setHTMLBody($html);
function send($to, $subject, $message, $options = null) { global $ost, $cfg; //Get the goodies require_once PEAR_DIR . 'Mail.php'; // PEAR Mail package require_once PEAR_DIR . 'Mail/mime.php'; // PEAR Mail_Mime packge //do some cleanup $to = preg_replace("/(\r\n|\r|\n)/s", '', trim($to)); $subject = preg_replace("/(\r\n|\r|\n)/s", '', trim($subject)); /* Message ID - generated for each outgoing email */ $messageId = sprintf('<%s-%s-%s>', substr(md5('mail' . SECRET_SALT), -9), Misc::randCode(9), $this->getEmail() ? $this->getEmail()->getEmail() : '@osTicketMailer'); $headers = array('From' => $this->getFromAddress(), 'To' => $to, 'Subject' => $subject, 'Date' => date('D, d M Y H:i:s O'), 'Message-ID' => $messageId, 'X-Mailer' => 'osTicket Mailer'); // Add in the options passed to the constructor $options = ($options ?: array()) + $this->options; if (isset($options['nobounce']) && $options['nobounce']) { $headers['Return-Path'] = '<>'; } elseif ($this->getEmail() instanceof Email) { $headers['Return-Path'] = $this->getEmail()->getEmail(); } //Bulk. if (isset($options['bulk']) && $options['bulk']) { $headers += array('Precedence' => 'bulk'); } //Auto-reply - mark as autoreply and supress all auto-replies if (isset($options['autoreply']) && $options['autoreply']) { $headers += array('Precedence' => 'auto_reply', 'X-Autoreply' => 'yes', 'X-Auto-Response-Suppress' => 'DR, RN, OOF, AutoReply', 'Auto-Submitted' => 'auto-replied'); } //Notice (sort of automated - but we don't want auto-replies back if (isset($options['notice']) && $options['notice']) { $headers += array('X-Auto-Response-Suppress' => 'OOF, AutoReply', 'Auto-Submitted' => 'auto-generated'); } if ($options) { if (isset($options['inreplyto']) && $options['inreplyto']) { $headers += array('In-Reply-To' => $options['inreplyto']); } if (isset($options['references']) && $options['references']) { if (is_array($options['references'])) { $headers += array('References' => implode(' ', $options['references'])); } else { $headers += array('References' => $options['references']); } } } // The Suhosin patch will muck up the line endings in some // cases // // References: // https://github.com/osTicket/osTicket-1.8/issues/202 // http://pear.php.net/bugs/bug.php?id=12032 // http://us2.php.net/manual/en/function.mail.php#97680 if ((extension_loaded('suhosin') || defined("SUHOSIN_PATCH")) && !$this->getSMTPInfo()) { $mime = new Mail_mime("\n"); } else { // Use defaults $mime = new Mail_mime(); } // If the message is not explicitly declared to be a text message, // then assume that it needs html processing to create a valid text // body $isHtml = true; $mid_token = isset($options['thread']) ? $options['thread']->asMessageId($to) : ''; if (!(isset($options['text']) && $options['text'])) { if ($cfg && $cfg->stripQuotedReply() && ($tag = $cfg->getReplySeparator()) && (!isset($options['reply-tag']) || $options['reply-tag'])) { $message = "<div style=\"display:none\"\n data-mid=\"{$mid_token}\">{$tag}<br/><br/></div>{$message}"; } $txtbody = rtrim(Format::html2text($message, 90, false)) . ($mid_token ? "\nRef-Mid: {$mid_token}\n" : ''); $mime->setTXTBody($txtbody); } else { $mime->setTXTBody($message); $isHtml = false; } if ($isHtml && $cfg && $cfg->isHtmlThreadEnabled()) { // Pick a domain compatible with pear Mail_Mime $matches = array(); if (preg_match('#(@[0-9a-zA-Z\\-\\.]+)#', $this->getFromAddress(), $matches)) { $domain = $matches[1]; } else { $domain = '@localhost'; } // Format content-ids with the domain, and add the inline images // to the email attachment list $self = $this; $message = preg_replace_callback('/cid:([\\w.-]{32})/', function ($match) use($domain, $mime, $self) { if (!($file = AttachmentFile::lookup($match[1]))) { return $match[0]; } $mime->addHTMLImage($file->getData(), $file->getType(), $file->getName(), false, $match[1] . $domain); // Don't re-attach the image below unset($self->attachments[$file->getId()]); return $match[0] . $domain; }, $message); // Add an HTML body $mime->setHTMLBody($message); } //XXX: Attachments if ($attachments = $this->getAttachments()) { foreach ($attachments as $attachment) { if ($attachment['file_id'] && ($file = AttachmentFile::lookup($attachment['file_id']))) { $mime->addAttachment($file->getData(), $file->getType(), $file->getName(), false); } } } //Desired encodings... $encodings = array('head_encoding' => 'quoted-printable', 'text_encoding' => 'base64', 'html_encoding' => 'base64', 'html_charset' => 'utf-8', 'text_charset' => 'utf-8', 'head_charset' => 'utf-8'); //encode the body $body = $mime->get($encodings); //encode the headers. $headers = $mime->headers($headers, true); // Cache smtp connections made during this request static $smtp_connections = array(); if ($smtp = $this->getSMTPInfo()) { //Send via SMTP $key = sprintf("%s:%s:%s", $smtp['host'], $smtp['port'], $smtp['username']); if (!isset($smtp_connections[$key])) { $mail = mail::factory('smtp', array('host' => $smtp['host'], 'port' => $smtp['port'], 'auth' => $smtp['auth'], 'username' => $smtp['username'], 'password' => $smtp['password'], 'timeout' => 20, 'debug' => false, 'persist' => true)); if ($mail->connect()) { $smtp_connections[$key] = $mail; } } else { // Use persistent connection $mail = $smtp_connections[$key]; } $result = $mail->send($to, $headers, $body); if (!PEAR::isError($result)) { return $messageId; } // Force reconnect on next ->send() unset($smtp_connections[$key]); $alert = sprintf("Unable to email via SMTP:%s:%d [%s]\n\n%s\n", $smtp['host'], $smtp['port'], $smtp['username'], $result->getMessage()); $this->logError($alert); } //No SMTP or it failed....use php's native mail function. $mail = mail::factory('mail'); return PEAR::isError($mail->send($to, $headers, $body)) ? false : $messageId; }
private function _do_emaillearn($uids, $spam) { $rcmail = rcube::get_instance(); $identity_arr = $rcmail->user->get_identity(); $from = $identity_arr['email']; if ($spam) { $mailto = $rcmail->config->get('markasjunk2_email_spam'); } else { $mailto = $rcmail->config->get('markasjunk2_email_ham'); } $mailto = str_replace('%u', $_SESSION['username'], $mailto); $mailto = str_replace('%l', $rcmail->user->get_username('local'), $mailto); $mailto = str_replace('%d', $rcmail->user->get_username('domain'), $mailto); $mailto = str_replace('%i', $from, $mailto); if (!$mailto) { return; } $message_charset = $rcmail->output->get_charset(); // chose transfer encoding $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15'); $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit'; $temp_dir = realpath($rcmail->config->get('temp_dir')); $subject = $rcmail->config->get('markasjunk2_email_subject'); $subject = str_replace('%u', $_SESSION['username'], $subject); $subject = str_replace('%t', $spam ? 'spam' : 'ham', $subject); $subject = str_replace('%l', $rcmail->user->get_username('local'), $subject); $subject = str_replace('%d', $rcmail->user->get_username('domain'), $subject); // compose headers array $headers = array(); $headers['Date'] = date('r'); $headers['From'] = format_email_recipient($identity_arr['email'], $identity_arr['name']); $headers['To'] = $mailto; $headers['Subject'] = $subject; foreach ($uids as $uid) { $MESSAGE = new rcube_message($uid); // set message charset as default if (!empty($MESSAGE->headers->charset)) { $rcmail->storage->set_charset($MESSAGE->headers->charset); } $MAIL_MIME = new Mail_mime($rcmail->config->header_delimiter()); if ($rcmail->config->get('markasjunk2_email_attach', false)) { $tmpPath = tempnam($temp_dir, 'rcmMarkASJunk2'); // send mail as attachment $MAIL_MIME->setTXTBody(($spam ? 'Spam' : 'Ham') . ' report from ' . $rcmail->config->get('product_name'), false, true); $raw_message = $rcmail->storage->get_raw_body($uid); $subject = $MESSAGE->get_header('subject'); if (isset($subject) && $subject != "") { $disp_name = $subject . ".eml"; } else { $disp_name = "message_rfc822.eml"; } if (file_put_contents($tmpPath, $raw_message)) { $MAIL_MIME->addAttachment($tmpPath, "message/rfc822", $disp_name, true, $transfer_encoding, 'attachment', '', '', '', $rcmail->config->get('mime_param_folding') ? 'quoted-printable' : NULL, $rcmail->config->get('mime_param_folding') == 2 ? 'quoted-printable' : NULL, '', RCUBE_CHARSET); } // encoding settings for mail composing $MAIL_MIME->setParam('text_encoding', $transfer_encoding); $MAIL_MIME->setParam('html_encoding', 'quoted-printable'); $MAIL_MIME->setParam('head_encoding', 'quoted-printable'); $MAIL_MIME->setParam('head_charset', $message_charset); $MAIL_MIME->setParam('html_charset', $message_charset); $MAIL_MIME->setParam('text_charset', $message_charset); // pass headers to message object $MAIL_MIME->headers($headers); } else { $headers['Resent-From'] = $headers['From']; $headers['Resent-Date'] = $headers['Date']; $headers['Date'] = $MESSAGE->headers->date; $headers['From'] = $MESSAGE->headers->from; $headers['Subject'] = $MESSAGE->headers->subject; $MAIL_MIME->headers($headers); if ($MESSAGE->has_html_part()) { $body = $MESSAGE->first_html_part(); $MAIL_MIME->setHTMLBody($body); } $body = $MESSAGE->first_text_part(); $MAIL_MIME->setTXTBody($body, false, true); foreach ($MESSAGE->attachments as $attachment) { $MAIL_MIME->addAttachment($MESSAGE->get_part_body($attachment->mime_id, true), $attachment->mimetype, $attachment->filename, false, $attachment->encoding, $attachment->disposition, '', $attachment->charset); } foreach ($MESSAGE->mime_parts as $attachment) { if (!empty($attachment->content_id)) { // covert CID to Mail_MIME format $attachment->content_id = str_replace('<', '', $attachment->content_id); $attachment->content_id = str_replace('>', '', $attachment->content_id); if (empty($attachment->filename)) { $attachment->filename = $attachment->content_id; } $message_body = $MAIL_MIME->getHTMLBody(); $dispurl = 'cid:' . $attachment->content_id; $message_body = str_replace($dispurl, $attachment->filename, $message_body); $MAIL_MIME->setHTMLBody($message_body); $MAIL_MIME->addHTMLImage($MESSAGE->get_part_body($attachment->mime_id, true), $attachment->mimetype, $attachment->filename, false); } } // encoding settings for mail composing $MAIL_MIME->setParam('head_encoding', $MESSAGE->headers->encoding); $MAIL_MIME->setParam('head_charset', $MESSAGE->headers->charset); foreach ($MESSAGE->mime_parts as $mime_id => $part) { $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary); if ($mimetype == 'text/html') { $MAIL_MIME->setParam('text_encoding', $part->encoding); $MAIL_MIME->setParam('html_charset', $part->charset); } else { if ($mimetype == 'text/plain') { $MAIL_MIME->setParam('html_encoding', $part->encoding); $MAIL_MIME->setParam('text_charset', $part->charset); } } } } $rcmail->deliver_message($MAIL_MIME, $from, $mailto, $smtp_error, $body_file); // clean up if (file_exists($tmpPath)) { unlink($tmpPath); } if ($rcmail->config->get('markasjunk2_debug')) { if ($spam) { rcube::write_log('markasjunk2', $uid . ' SPAM ' . $mailto . ' (' . $subject . ')'); } else { rcube::write_log('markasjunk2', $uid . ' HAM ' . $mailto . ' (' . $subject . ')'); } if ($smtp_error['vars']) { rcube::write_log('markasjunk2', $smtp_error['vars']); } } } }
$vendor = $vpc->findVendorWithEmail($username); if (!is_null($vendor)) { $isAdmin = $vendor->isAdmin(); } } if ($isAdmin) { include_once 'vendorsClass.php'; include_once 'Mail.php'; require_once '/home/dvaqpvvw/php/Mail/mime.php'; $vC = new vendorsClass(); $admins = $vC->getAdmins(); $vendor = $vC->getVendorByID($_REQUEST['vendorID']); $crlf = "\r\n"; $hdrs = array('From' => '*****@*****.**', 'Subject' => 'Welcome to St. Louis Bridal Professionals'); $mime = new Mail_mime($crlf); $mime->addHTMLImage("images/stlbridalprosLogo_200x180.jpg", "image/jpeg"); $logo_cid = $mime->_html_images[count($mime->_html_images) - 1]['cid']; $mime->addHTMLImage("images/adminLogin.gif", "image/gif"); $loginButton_cid = $mime->_html_images[count($mime->_html_images) - 1]['cid']; $emailBody = "<p>Welcome to <b>St. Louis Bridal Professionals</b>!</p>"; $emailBody .= "<p> A profile has been created for you, but you must fill in the information before your information will be made available on the website.</p>"; $emailBody .= '<p><a href="http://www.stlbridalpros.com/vendorLogin.php">Click here login and finish your profile.</a></p>'; $emailBody .= '<p>Keep your login details for reference:</p>'; $emailBody .= '<p><b>Email: </b>' . $vendor->email . '</p>'; $emailBody .= '<p><b>Password: </b>' . $vendor->password . '</p>'; $emailBody .= '<p>You can login from the main website (<a href="http://www.stlbridalpros.com">www.stlbridalpros.com</a>) by clicking this image: <img id="loginButton" src="cid:' . $loginButton_cid . '"/> found at the bottom of the page.</p>'; $emailBody .= '<br/><br/><p>We look forward to having you be a part of this group!</p>'; $emailBody .= '<p>If you have problems contact: '; $adminCount = 0; $adminContactMsg = ""; foreach ($admins as $admin) {
function correo($to, $subject, $body, $tipo = 'txt', $adjuntos = array(), $embededimage = array()) { $CI =& get_instance(); if (!@(include_once 'Mail.php')) { $error = 'Problemas al cargar la clase Mail, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte técnico'; return false; } if (!@(include_once 'Mail/mime.php')) { $error = 'Problemas al cargar la clase Mail_mime, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte técnico'; return false; } $CI->config->load('notifica'); $message = new Mail_mime(); $from = $CI->config->item('mail_smtp_from'); $host = $CI->config->item('mail_smtp_host'); $port = $CI->config->item('mail_smtp_port'); $user = $CI->config->item('mail_smtp_usr'); $pass = $CI->config->item('mail_smtp_pwd'); $extraheaders = array('From' => $from, 'To' => $to, 'Subject' => $subject); if (count($embededimage) > 0) { foreach ($embededimage as $adj) { $message->addHTMLImage($adj[0], $adj[1], $adj[2], $adj[3], $adj[4]); } } if (is_array($adjuntos)) { foreach ($adjuntos as $adj) { $message->addAttachment($adj); } } $parr = array('host' => $host, 'port' => $port, 'auth' => true, 'username' => $user, 'password' => $pass); if ($tipo == 'html') { $hbody = '<html><head><title></title>'; $hbody .= '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />'; $hbody .= '</head>'; $hbody .= '<body>'; $hbody .= $body; $hbody .= '</body></html>'; $message->setHTMLBody($hbody); } else { $message->setTXTBody($body); } $sbody = $message->get(); $headers = $message->headers($extraheaders); $smtp = Mail::factory('smtp', $parr); $mail = $smtp->send($to, $headers, $sbody); if (PEAR::isError($mail)) { $CI->error = $mail->getMessage(); return false; } else { return true; } }
function send($to, $subject, $message, $options = null) { global $ost, $cfg; //Get the goodies require_once PEAR_DIR . 'Mail.php'; // PEAR Mail package require_once PEAR_DIR . 'Mail/mime.php'; // PEAR Mail_Mime packge $messageId = $this->getMessageId($to, $options); if (is_object($to) && is_callable(array($to, 'getEmail'))) { // Add personal name if available if (is_callable(array($to, 'getName'))) { $to = sprintf('"%s" <%s>', $to->getName()->getOriginal(), $to->getEmail()); } else { $to = $to->getEmail(); } } //do some cleanup $to = preg_replace("/(\r\n|\r|\n)/s", '', trim($to)); $subject = preg_replace("/(\r\n|\r|\n)/s", '', trim($subject)); $headers = array('From' => $this->getFromAddress(), 'To' => $to, 'Subject' => $subject, 'Date' => date('D, d M Y H:i:s O'), 'Message-ID' => $messageId, 'X-Mailer' => 'osTicket Mailer'); // Add in the options passed to the constructor $options = ($options ?: array()) + $this->options; if (isset($options['nobounce']) && $options['nobounce']) { $headers['Return-Path'] = '<>'; } elseif ($this->getEmail() instanceof Email) { $headers['Return-Path'] = $this->getEmail()->getEmail(); } //Bulk. if (isset($options['bulk']) && $options['bulk']) { $headers += array('Precedence' => 'bulk'); } //Auto-reply - mark as autoreply and supress all auto-replies if (isset($options['autoreply']) && $options['autoreply']) { $headers += array('Precedence' => 'auto_reply', 'X-Autoreply' => 'yes', 'X-Auto-Response-Suppress' => 'DR, RN, OOF, AutoReply', 'Auto-Submitted' => 'auto-replied'); } //Notice (sort of automated - but we don't want auto-replies back if (isset($options['notice']) && $options['notice']) { $headers += array('X-Auto-Response-Suppress' => 'OOF, AutoReply', 'Auto-Submitted' => 'auto-generated'); } if ($options) { if (isset($options['inreplyto']) && $options['inreplyto']) { $headers += array('In-Reply-To' => $options['inreplyto']); } if (isset($options['references']) && $options['references']) { if (is_array($options['references'])) { $headers += array('References' => implode(' ', $options['references'])); } else { $headers += array('References' => $options['references']); } } } // Make the best effort to add In-Reply-To and References headers $reply_tag = $mid_token = ''; if (isset($options['thread']) && $options['thread'] instanceof ThreadEntry) { if ($irt = $options['thread']->getEmailMessageId()) { // This is an response from an email, like and autoresponse. // Web posts will not have a email message-id $headers += array('In-Reply-To' => $irt, 'References' => $options['thread']->getEmailReferences()); } elseif ($parent = $options['thread']->getParent()) { // Use the parent item as the email information source. This // will apply for staff replies $headers += array('In-Reply-To' => $parent->getEmailMessageId(), 'References' => $parent->getEmailReferences()); } // Configure the reply tag and embedded message id token $mid_token = $options['thread']->asMessageId($to); if ($cfg && $cfg->stripQuotedReply() && (!isset($options['reply-tag']) || $options['reply-tag'])) { $reply_tag = $cfg->getReplySeparator() . '<br/><br/>'; } } // Use general failsafe default initially $eol = "\n"; // MAIL_EOL setting can be defined in `ost-config.php` if (defined('MAIL_EOL') && is_string(MAIL_EOL)) { $eol = MAIL_EOL; } $mime = new Mail_mime($eol); // If the message is not explicitly declared to be a text message, // then assume that it needs html processing to create a valid text // body $isHtml = true; if (!(isset($options['text']) && $options['text'])) { if ($reply_tag || $mid_token) { $message = "<div style=\"display:none\"\n class=\"mid-{$mid_token}\">{$reply_tag}</div>{$message}"; } $txtbody = rtrim(Format::html2text($message, 90, false)) . ($mid_token ? "\nRef-Mid: {$mid_token}\n" : ''); $mime->setTXTBody($txtbody); } else { $mime->setTXTBody($message); $isHtml = false; } if ($isHtml && $cfg && $cfg->isHtmlThreadEnabled()) { // Pick a domain compatible with pear Mail_Mime $matches = array(); if (preg_match('#(@[0-9a-zA-Z\\-\\.]+)#', $this->getFromAddress(), $matches)) { $domain = $matches[1]; } else { $domain = '@localhost'; } // Format content-ids with the domain, and add the inline images // to the email attachment list $self = $this; $message = preg_replace_callback('/cid:([\\w.-]{32})/', function ($match) use($domain, $mime, $self) { if (!($file = AttachmentFile::lookup($match[1]))) { return $match[0]; } $mime->addHTMLImage($file->getData(), $file->getType(), $file->getName(), false, $match[1] . $domain); // Don't re-attach the image below unset($self->attachments[$file->getId()]); return $match[0] . $domain; }, $message); // Add an HTML body $mime->setHTMLBody($message); } //XXX: Attachments if ($attachments = $this->getAttachments()) { foreach ($attachments as $attachment) { if ($attachment['file_id'] && ($file = AttachmentFile::lookup($attachment['file_id']))) { $mime->addAttachment($file->getData(), $file->getType(), $file->getName(), false); } } } //Desired encodings... $encodings = array('head_encoding' => 'quoted-printable', 'text_encoding' => 'base64', 'html_encoding' => 'base64', 'html_charset' => 'utf-8', 'text_charset' => 'utf-8', 'head_charset' => 'utf-8'); //encode the body $body = $mime->get($encodings); //encode the headers. $headers = $mime->headers($headers, true); // Cache smtp connections made during this request static $smtp_connections = array(); if ($smtp = $this->getSMTPInfo()) { //Send via SMTP $key = sprintf("%s:%s:%s", $smtp['host'], $smtp['port'], $smtp['username']); if (!isset($smtp_connections[$key])) { $mail = mail::factory('smtp', array('host' => $smtp['host'], 'port' => $smtp['port'], 'auth' => $smtp['auth'], 'username' => $smtp['username'], 'password' => $smtp['password'], 'timeout' => 20, 'debug' => false, 'persist' => true)); if ($mail->connect()) { $smtp_connections[$key] = $mail; } } else { // Use persistent connection $mail = $smtp_connections[$key]; } $result = $mail->send($to, $headers, $body); if (!PEAR::isError($result)) { return $messageId; } // Force reconnect on next ->send() unset($smtp_connections[$key]); $alert = sprintf(__("Unable to email via SMTP:%1\$s:%2\$d [%3\$s]\n\n%4\$s\n"), $smtp['host'], $smtp['port'], $smtp['username'], $result->getMessage()); $this->logError($alert); } //No SMTP or it failed....use php's native mail function. $mail = mail::factory('mail'); return PEAR::isError($mail->send($to, $headers, $body)) ? false : $messageId; }
/** * TAG_TODO: написать очень, очень подробный комментарий сюда * */ function send_email($mailer, $from, $to, $subject, $body, $headers = array(), $attachments = array(), $server_params = null) { logthis('[send_email] : sending email "' . $subject . '" from "' . $from . '" to "' . $to . '"'); // extract emails if (!preg_match('~[a-zA-Z0-9.\\-]+@[a-zA-Z0-9.\\-]+~', $to, $mail_addresses)) { logthis('[send_email] : no addresses found!', ZLogger::LOG_LEVEL_ERROR); return false; } // $to may contain such structure: Julia (julia@example.com). Round brackets should be replaced with angle brackets $to = preg_replace('~[\\<\\[\\(]*([a-zA-Z0-9.\\-]+@[a-zA-Z0-9.\\-]+)[\\>\\]\\)]*~', '<$1>', $to); // encoding data for mail_mime $encoding_parameters = array('head_encoding' => 'base64', 'text_encoding' => 'base64', 'html_encoding' => 'base64', 'head_charset' => 'utf-8', 'text_charset' => 'utf-8', 'html_charset' => 'utf-8'); // add some important headers $headers_primary = array('From' => $from, 'To' => $to, 'Subject' => $subject); $headers = array_merge($headers_primary, $headers); // create mail body generator $mime = new Mail_mime($encoding_parameters); // by default, no text part $mime->setTXTBody(''); $alarm = 0; // replace image links with attached images if ($image_count = preg_match_all('~<img[^>]+src="(?!cid:)([^"]+)"[^>]*>~', $body, $img_data)) { for ($img_index = 0; $img_index < $image_count; $img_index++) { // generate new CID $cid = strtolower(str_replace('-', '', create_guid())); // image full CID, must contain sender domain to be displayed inline instead as attachment $cid_full = $cid . '@' . preg_replace('~[^@]*@~', '', $from); // add image $mime->addHTMLImage($img_data[1][$img_index], get_file_mime_type($img_data[1][$img_index]), '', true, $cid); // replace local image link to inline $new_image_link = str_replace($img_data[1][$img_index], 'cid:' . $cid_full, $img_data[0][$img_index]); // new image link $body = str_replace($img_data[0][$img_index], $new_image_link, $body); } } // ok, HTML part is ready now $mime->setHTMLBody($body); // add attachments foreach ($attachments as $attachment) { $attachment_filename = $attachment['filename']; $attachment_realname = $attachment['realname']; $mime->addAttachment($attachment_filename, get_file_mime_type($attachment_filename), $attachment_realname, true, 'base64', 'attachment', '', '', '', 'base64', 'utf-8', '', 'utf-8'); } // generate final headers $headers_ready = $mime->headers($headers); // get full message body $body_ready = $mime->get(); // now send $mail_result = $mailer->send($mail_addresses, $headers_ready, $body_ready); // free mem as messages are big unset($mime); // log result if ($mail_result === true) { logthis('[send_email] : ok'); } else { logthis('[send_email] : failed mailing to ' . $to . ' : ' . $mail_result->getMessage(), ZLogger::LOG_LEVEL_ERROR); } return $mail_result; }
/** * ---------------- Global Tools --------------- */ function toData() { $templateFile = $this->template; $args = (array) $this->contents; $content = clone $this->page; foreach ($args as $k => $v) { $content->{$k} = $v; } $content->msgid = empty($content->msgid) ? md5(time() . rand()) : $content->msgid; $ff = HTML_FlexyFramework::get(); $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set'; if (isset($ff->Pman['HTTP_HOST'])) { $http_host = $ff->Pman['HTTP_HOST']; } $content->HTTP_HOST = $http_host; // this should be done by having multiple template sources...!!! require_once 'HTML/Template/Flexy.php'; $tmp_opts = array('site_prefix' => false); if (!empty($this->templateDir)) { $tmp_opts['templateDir'] = $this->templateDir; } $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy; if (!empty($fopts['DB_DataObject_translator'])) { $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator']; } if (!empty($fopts['locale'])) { $tmp_opts['locale'] = $fopts['locale']; } // local opt's overwrite if (!empty($this->locale)) { $tmp_opts['locale'] = $this->locale; } $htmlbody = false; $html_tmp_opts = $tmp_opts; $htmltemplate = new HTML_Template_Flexy($html_tmp_opts); if (is_string($htmltemplate->resolvePath('mail/' . $templateFile . '.body.html'))) { // then we have a multi-part email... if (!empty($this->html_locale)) { $html_tmp_opts['locale'] = $this->html_locale; } $htmltemplate = new HTML_Template_Flexy($html_tmp_opts); $htmltemplate->compile('mail/' . $templateFile . '.body.html'); $htmlbody = $htmltemplate->bufferedOutputObject($content); $this->htmlbody = $htmlbody; // for the html body, we may want to convert the attachments to images. // var_dump($htmlbody);exit; if ($this->replaceImages) { $htmlbody = $this->htmlbodytoCID($htmlbody); } if ($this->css_embed) { $htmlbody = $this->htmlbodyCssEmbed($htmlbody); } } $tmp_opts['nonHTML'] = true; //print_R($tmp_opts); // $tmp_opts['force'] = true; $template = new HTML_Template_Flexy($tmp_opts); $template->compile('mail/' . $templateFile . '.txt'); /* use variables from this object to ouput data. */ $mailtext = $template->bufferedOutputObject($content); //print_r($mailtext);exit; //echo "<PRE>";print_R($mailtext); /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */ require_once 'Mail/mimeDecode.php'; require_once 'Mail.php'; $decoder = new Mail_mimeDecode($mailtext); $parts = $decoder->getSendArray(); if (PEAR::isError($parts)) { return $parts; //echo "PROBLEM: {$parts->message}"; //exit; } $isMime = false; require_once 'Mail/mime.php'; $mime = new Mail_mime(array('eol' => "\n", 'html_charset' => 'utf-8', 'text_charset' => 'utf-8', 'head_charset' => 'utf-8')); // clean up the headers... $parts[1]['Message-Id'] = '<' . $content->msgid . '@' . $content->HTTP_HOST . '>'; if ($htmlbody !== false) { // got a html headers... if (isset($parts[1]['Content-Type'])) { unset($parts[1]['Content-Type']); } $mime->setTXTBody($parts[2]); $mime->setHTMLBody($htmlbody); // var_dump($mime);exit; foreach ($this->images as $cid => $cdata) { $mime->addHTMLImage($cdata['file'], $cdata['mimetype'], $cid . '.' . $cdata['ext'], true, $cdata['contentid']); } $isMime = true; } if (!empty($this->attachments)) { //if got a attachments $header = $mime->headers($parts[1]); if (isset($parts[1]['Content-Type'])) { unset($parts[1]['Content-Type']); } if (!$isMime) { if (preg_match('/text\\/html/', $header['Content-Type'])) { $mime->setHTMLBody($parts[2]); $mime->setTXTBody('This message is in HTML only'); } else { $mime->setTXTBody($parts[2]); $mime->setHTMLBody('<PRE>' . htmlspecialchars($parts[2]) . '</PRE>'); } } foreach ($this->attachments as $attch) { $mime->addAttachment($attch['file'], $attch['mimetype'], !empty($attch['name']) ? $attch['name'] : '', true); } $isMime = true; } if ($isMime) { $parts[2] = $mime->get(); $parts[1] = $mime->headers($parts[1]); } $ret = array('recipents' => $parts[0], 'headers' => $parts[1], 'body' => $parts[2], 'mailer' => $this); if ($this->rcpts !== false) { $ret['recipents'] = $this->rcpts; } // if 'to' is empty, then add the recipents in there... (must be an array? if (!empty($ret['recipents']) && is_array($ret['recipents']) && (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) { $ret['headers']['To'] = implode(',', $ret['recipents']); } // add bcc if necessary.. if (!empty($this->bcc)) { $ret['bcc'] = $this->bcc; } return $ret; }
function SendHTMLEmail($body_number = 1, $email, $from, $subject, $greeting, $title, $surname) { include 'Mail.php'; include 'Mail/mime.php'; // edit these values to match your database information // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'quotient_live'); /** MySQL database username */ define('DB_USER', 'quotient_live'); /** MySQL database password */ //define('DB_PASSWORD', 'quotient123A'); define('DB_PASSWORD', 'balances123A!'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); $server = DB_HOST; $user = DB_USER; $password = DB_PASSWORD; $db = DB_NAME; $con = mysql_connect($server, $user, $password); mysql_select_db($db, $con); // example query $result = mysql_query("SELECT wp.*,\n(SELECT meta_value FROM wp_postmeta pm WHERE meta_key = 'clinicaltrialinfo_dates' AND pm.post_id = wp.id ) AS dates,\n(SELECT meta_value FROM wp_postmeta pm WHERE meta_key = 'clinicaltrialinfo_payment' AND pm.post_id = wp.id ) AS payment,\n(SELECT meta_value FROM wp_postmeta pm WHERE meta_key = 'clinicaltrialinfo_short_description' AND pm.post_id = wp.id ) AS description\nFROM wp_posts wp WHERE post_type = 'clinicaltrial' AND post_status = 'publish';"); $postList = ''; // show all posts by author 1 (admin) while ($row = mysql_fetch_array($result)) { if ($row['post_status'] == "publish") { $postList .= "" . $row['post_title'] . " <br />"; $postList .= "" . $row['dates'] . " <br />"; $postList .= "" . $row['payment'] . " <br />"; $postList .= "" . $row['description'] . " <br />"; } } mysql_close($con); $mime = new Mail_mime("\n"); $hdrs = array('From' => "{$from}", 'Subject' => "{$subject}"); $message = file_get_contents('emails/emailbody_' . $body_number . '.html'); $message = str_replace("{greeting}", ucwords($greeting), $message); $message = str_replace("{title}", ucwords($title), $message); $message = str_replace("{surname}", ucwords($surname), $message); $message = str_replace("{list}", $postList, $message); $mime->setHTMLBody($message); $message = file_get_contents('emails/emailbody_' . $body_number . '.txt'); $message = str_replace("{greeting}", ucwords($greeting), $message); $message = str_replace("{title}", ucwords($title), $message); $message = str_replace("{surname}", ucwords($surname), $message); $message = str_replace("{list}", $postList, $message); $mime->setTXTBody(strip_tags("{$message}")); $attachment = file_get_contents('images/base.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'base.jpg', false, 1); $attachment = file_get_contents('images/bottomline.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'bottomline.jpg', false, 2); $attachment = file_get_contents('images/header.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'header.jpg', false, 3); $attachment = file_get_contents('images/qc.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'qc.jpg', false, 4); $attachment = file_get_contents('images/strapline.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'strapline.jpg', false, 5); $attachment = file_get_contents('images/topline.jpg'); $mime->addHTMLImage($attachment, 'img/jpg', 'topline.jpg', false, 6); // do not ever try to call these lines in reverse order $body = $mime->get(); $hdrs = $mime->headers($hdrs); $mail =& Mail::factory('mail'); $result = $mail->send($email, $hdrs, $body); if ($result) { // echo "email ok\n"; } else { // echo "email failed\n"; } }
function _sendmail($to, $subject, $body, $type = 'text') { if (!@(include_once 'Mail.php')) { $this->error = 'Problemas al cargar la clase Mail, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte técnico'; return false; } if (!@(include_once 'Mail/mime.php')) { $this->error = 'Problemas al cargar la clase Mail_mime, probablemente sea necesario instalarla desde PEAR, comuniquese con soporte técnico'; return false; } $message = new Mail_mime(); $from = $this->config->item('mail_smtp_from'); $host = $this->config->item('mail_smtp_host'); $port = $this->config->item('mail_smtp_port'); $user = $this->config->item('mail_smtp_usr'); $pass = $this->config->item('mail_smtp_pwd'); $extraheaders = array('From' => $from, 'To' => $to, 'Subject' => $subject, 'Content-type' => "text/html; charset=UTF-8\r\n\r\n"); foreach ($this->embededimage as $adj) { $message->addHTMLImage($adj[0], $adj[1], $adj[2], $adj[3], $adj[4]); } if (is_array($this->adjuntos)) { foreach ($this->adjuntos as $adj) { $message->addAttachment($adj); } } $parr = array('host' => $host, 'port' => $port, 'auth' => true, 'username' => $user, 'password' => $pass); if ($type == 'html') { $message->setHTMLBody($body); } else { $message->setTXTBody($body); } $mimeparams = array(); $mimeparams['text_encoding'] = '8bit'; $mimeparams['text_charset'] = 'UTF-8'; $mimeparams['html_charset'] = 'UTF-8'; $mimeparams['head_charset'] = 'UTF-8'; $sbody = $message->get($mimeparams); $headers = $message->headers($extraheaders); $smtp = Mail::factory('smtp', $parr); $mail = $smtp->send($to, $headers, $sbody); if (PEAR::isError($mail)) { $this->error = $mail->getMessage(); return false; } else { return true; } }
/** * Send the ecard. */ public function send($id) { $item = ORM::factory("item", $id); access::required("view", $item); if (!ecard::can_send_ecard()) { access::forbidden(); } $form = ecard::get_send_form($item); try { $valid = $form->validate(); } catch (ORM_Validation_Exception $e) { // Translate ORM validation errors into form error messages foreach ($e->validation->errors() as $key => $error) { $form->edit_item->inputs[$key]->add_error($error, 1); } $valid = false; } if ($valid) { $to_array = explode(",", $form->send_ecard->inputs["to_email"]->value); foreach ($to_array as $to) { $v = new View("ecard_email.html"); $v->item = $item; $v->subject = module::get_var("ecard", "subject"); $from_name = $form->send_ecard->from_name->value; $bcc = module::get_var("ecard", "bcc"); if ($form->send_ecard->send_to_self->checked == true) { $cc = $form->send_ecard->inputs["from_email"]->value; } $v->message = t(module::get_var("ecard", "message"), array("fromname" => $from_name)); $v->custom_message = $form->send_ecard->text->value; $v->image = $item->name; $from = $form->send_ecard->inputs["from_email"]->value; $headers = array("from" => $from_name . "<" . $from . ">", "to" => $to, "subject" => module::get_var("ecard", "subject")); require_once MODPATH . "ecard/lib/mime.php"; $mime = new Mail_mime("\n"); $mime->setHTMLBody($v->render()); if ($form->send_ecard->send_fresh->checked == true) { $tmpfile = tempnam(TMPPATH, "clean"); if ($form->send_ecard->send_thumbnail->checked == true) { $options = array("width" => module::get_var("gallery", "thumb_size"), "height" => module::get_var("gallery", "thumb_size"), "master" => Image::AUTO); gallery_graphics::resize($item->file_path(), $tmpfile, $options); $mime->addHTMLImage($tmpfile, $item->mime_type, $item->name); } else { $options = array("width" => module::get_var("gallery", "resize_size"), "height" => module::get_var("gallery", "resize_size"), "master" => Image::AUTO); gallery_graphics::resize($item->file_path(), $tmpfile, $options); $mime->addHTMLImage($tmpfile, $item->mime_type, $item->name); } } else { if ($form->send_ecard->send_thumbnail->checked == true) { $mime->addHTMLImage($item->thumb_path(), $item->mime_type, $item->name); } else { $mime->addHTMLImage($item->resize_path(), $item->mime_type, $item->name); } } $body = $mime->get(array('html_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'text_encoding' => '8bit', 'head_charset' => 'UTF-8')); self::_notify($headers['to'], $headers['from'], $headers['subject'], $item, $body, $mime->headers(), $bcc, $cc); } unlink($tmpfile); message::success("eCard successfully sent"); json::reply(array("result" => "success")); } else { json::reply(array("result" => "error", "html" => (string) $form)); } }
function send($mailid, $admin_user) { if (!check_admin_user($admin_user)) { return false; } if (!($info = load_mail_info($mailid))) { echo "Cannot load list information for message {$mailid}"; return false; } $subject = $info[0]; $listid = $info[1]; $status = $info[2]; $sent = $info[3]; $from_name = 'Pyramid MLM'; $from_address = 'return@address'; $query = "select email from sub_lists where listid = {$listid}"; $result = mysql_query($query); if (!$result) { echo $query; return false; } else { if (mysql_num_rows($result) == 0) { echo "There is nobody subscribed to list number {$listid}"; return false; } else { // include PEAR mail classes include 'Mail.php'; include 'Mail/mime.php'; // instantiate MIME class and pass it the carriage return/line feed // character used on this system $message = new Mail_mime("\r\n"); // read in the text version of the newsletter $textfilename = "archive/{$listid}/{$mailid}/text.txt"; $tfp = fopen($textfilename, "r"); $text = fread($tfp, filesize($textfilename)); fclose($tfp); // read in the HTML version of the newsletter $htmlfilename = "archive/{$listid}/{$mailid}/index.html"; $hfp = fopen($htmlfilename, "r"); $html = fread($hfp, filesize($htmlfilename)); fclose($hfp); // add HTML and text to the mimemail object $message->setTXTBody($text); $message->setHTMLBody($html); // get the list of images that relate to this message $query = "select path, mimetype from images where mailid = {$mailid}"; if (db_connect()) { $result = mysql_query($query); if (!$result) { echo '<p>Unable to get image list from database.'; return false; } $num = mysql_numrows($result); for ($i = 0; $i < $num; $i++) { //load each image from disk $imgfilename = "archive/{$listid}/{$mailid}/" . mysql_result($result, $i, 0); $imgtype = mysql_result($result, $i, 1); // add each image to the object $message->addHTMLImage($imgfilename, $imgtype, $imgfilename, true); } } // create message body $body = $message->get(); // create message headers $from = '"' . get_real_name($admin_user) . '" <' . $admin_user . '>'; $hdrarray = array('From' => $from, 'Subject' => $subject); $hdrs = $message->headers($hdrarray); // create the actual sending object $sender =& Mail::factory('mail'); if ($status == 'STORED') { // send the HTML message to the administrator $sender->send($admin_user, $hdrs, $body); // send the plain text version of the message to administrator mail($admin_user, $subject, $text, 'From: "' . get_real_name($admin_user) . '" <' . $admin_user . ">"); echo "Mail sent to {$admin_user}"; // mark newsletter as tested $query = "update mail set status = 'TESTED' where mailid = {$mailid}"; if (db_connect()) { $result = mysql_query($query); } echo '<p>Press send again to send mail to whole list.<center>'; display_button('send', "&id={$mailid}"); echo '</center>'; } else { if ($status == 'TESTED') { //send to whole list $query = "select subscribers.realname, sub_lists.email, \r\n subscribers.mimetype \r\n from sub_lists, subscribers \r\n where listid = {$listid} and \r\n sub_lists.email = subscribers.email"; if (!db_connect()) { return false; } $result = mysql_query($query); if (!$result) { echo '<p>Error getting subscriber list'; } $count = 0; // for each subscriber while ($subscriber = mysql_fetch_row($result)) { if ($subscriber[2] == 'H') { //send HTML version to people who want it $sender->send($subscriber[1], $hdrs, $body); } else { //send text version to people who don't want HTML mail mail($subscriber[1], $subject, $text, 'From: "' . get_real_name($admin_user) . '" <' . $admin_user . ">"); } $count++; } $query = "update mail set status = 'SENT', sent = now() \r\n where mailid = {$mailid}"; if (db_connect()) { $result = mysql_query($query); } echo "<p>A total of {$count} messages were sent."; } else { if ($status == 'SENT') { echo '<p>This mail has already been sent.'; } } } } } }
/** * Remove attachments from a message */ function remove_attachments() { $rcmail = rcmail::get_instance(); $imap = $rcmail->storage; $MESSAGE = new rcube_message(get_input_value('_uid', RCUBE_INPUT_GET)); $headers = $this->_parse_headers($imap->get_raw_headers($MESSAGE->uid)); // set message charset as default if (!empty($MESSAGE->headers->charset)) { $imap->set_charset($MESSAGE->headers->charset); } // Remove old MIME headers unset($headers['MIME-Version']); unset($headers['Content-Type']); $MAIL_MIME = new Mail_mime($rcmail->config->header_delimiter()); $MAIL_MIME->headers($headers); if ($MESSAGE->has_html_part()) { $body = $MESSAGE->first_html_part(); $MAIL_MIME->setHTMLBody($body); } $body = $MESSAGE->first_text_part(); $MAIL_MIME->setTXTBody($body, false, true); foreach ($MESSAGE->attachments as $attachment) { if ($attachment->mime_id != get_input_value('_part', RCUBE_INPUT_GET) && get_input_value('_part', RCUBE_INPUT_GET) != '-1') { $MAIL_MIME->addAttachment($MESSAGE->get_part_content($attachment->mime_id), $attachment->mimetype, $attachment->filename, false, $attachment->encoding, $attachment->disposition, '', $attachment->charset); } } foreach ($MESSAGE->mime_parts as $attachment) { if (!empty($attachment->content_id)) { // covert CID to Mail_MIME format $attachment->content_id = str_replace('<', '', $attachment->content_id); $attachment->content_id = str_replace('>', '', $attachment->content_id); if (empty($attachment->filename)) { $attachment->filename = $attachment->content_id; } $MESSAGE_body = $MAIL_MIME->getHTMLBody(); $dispurl = 'cid:' . $attachment->content_id; $MESSAGE_body = str_replace($dispurl, $attachment->filename, $MESSAGE_body); $MAIL_MIME->setHTMLBody($MESSAGE_body); $MAIL_MIME->addHTMLImage($MESSAGE->get_part_content($attachment->mime_id), $attachment->mimetype, $attachment->filename, false); } } // encoding settings for mail composing $MAIL_MIME->setParam('head_encoding', $MESSAGE->headers->encoding); $MAIL_MIME->setParam('head_charset', $MESSAGE->headers->charset); foreach ($MESSAGE->mime_parts as $mime_id => $part) { $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary); if ($mimetype == 'text/html') { $MAIL_MIME->setParam('text_encoding', $part->encoding); $MAIL_MIME->setParam('html_charset', $part->charset); } else { if ($mimetype == 'text/plain') { $MAIL_MIME->setParam('html_encoding', $part->encoding); $MAIL_MIME->setParam('text_charset', $part->charset); } } } $saved = $imap->save_message($_SESSION['mbox'], $MAIL_MIME->getMessage()); //write_log("debug","saved=".$saved); if ($saved) { $imap->delete_message($MESSAGE->uid); // Assume the one we just added has the highest UID //dsoares $uids = $imap->conn->fetchUIDs($imap->mod_mailbox($_SESSION['mbox'])); //dsoares $uid = end($uids); $uid = $saved; //dsoares // set flags foreach ($MESSAGE->headers->flags as $flag) { $imap->set_flag($uid, strtoupper($flag), $_SESSION['mbox']); } $this->api->output->command('display_message', $this->gettext('attachmentremoved'), 'confirmation'); $this->api->output->command('removeattachments_reload', $uid); } else { $this->api->output->command('display_message', $this->gettext('removefailed'), 'error'); } $this->api->output->send(); }