Attachment is automatically added to the mail object after creation. The
attachment object is returned to allow for further manipulation.
public createAttachment ( string $body, string $mimeType = Zend_Mime::TYPE_OCTETSTREAM, string $disposition = Zend_Mime::DISPOSITION_ATTACHMENT, string $encoding = Zend_Mime::ENCODING_BASE64, string $filename = null ) : Zend_Mime_Part | ||
$body | string | |
$mimeType | string | |
$disposition | string | |
$encoding | string | |
$filename | string | OPTIONAL A filename for the attachment |
return | Zend_Mime_Part | Newly created Zend_Mime_Part object (to allow advanced settings) |
public static function sendExceptionByMail(Exception $e, $from, $to) { // generate mail datas $subject = '[' . MAIN_URL . ':' . CONFIG_ENV . '] Exception Report: ' . wordlimit_bychar($e->getMessage(), 50); $body = $e->getMessage() . ' in ' . $e->getFile() . ' at line ' . $e->getLine(); // sned mail throw Zend_Mail $mail = new Zend_Mail(); $mail->setSubject($subject)->setFrom($from)->setBodyText($body); $emails = explode(' ', $to); foreach ($emails as $email) { $mail->addTo($email); } $att = $mail->createAttachment(var_export($_GET, true), Zend_Mime::TYPE_TEXT); $att->filename = 'GET.txt'; $att = $mail->createAttachment(var_export($_POST, true), Zend_Mime::TYPE_TEXT); $att->filename = 'POST.txt'; // send session dump only if exists if (session_id() != null) { $att = $mail->createAttachment(var_export($_SESSION, true), Zend_Mime::TYPE_TEXT); $att->filename = 'SESSION.txt'; } $att = $mail->createAttachment(var_export($_SERVER, true), Zend_Mime::TYPE_TEXT); $att->filename = 'SERVER.txt'; $att = $mail->createAttachment($e->getTraceAsString(), Zend_Mime::TYPE_TEXT); $att->filename = 'backtraceExeption.txt'; $mail->send(); }
public function saveFiles($fileArray) { if (empty($fileArray)) { return array(); } // Init connection $this->initConnection(); $savedFiles = array(); @ini_set('SMTP', Mage::getStoreConfig('system/smtp/host')); @ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port')); $charset = "utf-8"; #$charset = "iso-8859-1"; $mail = new Zend_Mail($charset); $setReturnPath = Mage::getStoreConfig('system/smtp/set_return_path'); switch ($setReturnPath) { case 1: $returnPathEmail = $this->getDestination()->getEmailSender(); break; case 2: $returnPathEmail = Mage::getStoreConfig('system/smtp/return_path_email'); break; default: $returnPathEmail = null; break; } if ($returnPathEmail !== null) { $mailTransport = new Zend_Mail_Transport_Sendmail("-f" . $returnPathEmail); Zend_Mail::setDefaultTransport($mailTransport); } $mail->setFrom($this->getDestination()->getEmailSender(), $this->getDestination()->getEmailSender()); foreach (explode(",", $this->getDestination()->getEmailRecipient()) as $email) { if ($charset === "utf-8") { $mail->addTo($email, '=?utf-8?B?' . base64_encode($email) . '?='); } else { $mail->addTo($email, $email); } } foreach ($fileArray as $filename => $data) { if ($this->getDestination()->getEmailAttachFiles()) { $attachment = $mail->createAttachment($data); $attachment->filename = $filename; } $savedFiles[] = $filename; } #$mail->setSubject($this->_replaceVariables($this->getDestination()->getEmailSubject(), $firstFileContent)); if ($charset === "utf-8") { $mail->setSubject('=?utf-8?B?' . base64_encode($this->_replaceVariables($this->getDestination()->getEmailSubject(), implode("\n\n", $fileArray))) . '?='); } else { $mail->setSubject($this->_replaceVariables($this->getDestination()->getEmailSubject(), implode("\n\n", $fileArray))); } $mail->setBodyText(strip_tags($this->_replaceVariables($this->getDestination()->getEmailBody(), implode("\n\n", $fileArray)))); $mail->setBodyHtml($this->_replaceVariables($this->getDestination()->getEmailBody(), implode("\n\n", $fileArray))); try { $mail->send(Mage::helper('xtcore/utils')->getEmailTransport()); } catch (Exception $e) { $this->getTestResult()->setSuccess(false)->setMessage(Mage::helper('xtento_orderexport')->__('Error while sending email: %s', $e->getMessage())); return false; } return $savedFiles; }
public function sendAction() { // 返回值数组 $result = array(); // 请求参数 // $request = $this->getRequest()->getParams(); $now = date('Y-m-d H:i:s'); /* $data = array( 'subject' => $request['subject'], 'to' => $request['to'], 'to_name' => $request['to_name'], 'cc' => $request['cc'], 'cc_name' => $request['cc_name'], 'content' => $request['content'], 'attachment' => $request['attachment'] ); */ $data = array('subject' => 'test', 'to' => '*****@*****.**', 'to_name' => '新大陆', 'cc' => '*****@*****.**', 'cc_name' => 'leon', 'content' => 'test123测试', 'charset' => 'utf-8', 'attachment' => null); echo '<pre>'; print_r($data); $mailConfig = new Zend_Config_Ini(CONFIGS_PATH . '/application.ini', 'mail'); $from = $mailConfig->smtp->from; $fromname = $mailConfig->smtp->fromname; $transport = new Zend_Mail_Transport_Smtp($mailConfig->smtp->server, $mailConfig->smtp->params->toArray()); $mail = new Zend_Mail(); $mail->setSubject($data['subject']); $mail->setBodyText($data['content'], $data['charset']); $mail->setFrom($from, $fromname); $mail->addTo($data['to'], $data['to_name']); $mail->addCc($data['cc'], $data['cc_name']); $mail->addAttachment('MailController.php'); $mail->createAttachment(file_get_contents('E:\\sina.png'), 'image/png', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, 'sina.png'); print_r($mail->send($transport)); //echo Zend_Json::encode($result); exit; }
/** * Executes feedback action * */ public function executeFeedback(sfRequest $request) { $section = $request->getParameter('section', false); $this->form = new aFeedbackForm($section); $this->feedbackSubmittedBy = false; $this->failed = false; sfContext::getInstance()->getConfiguration()->loadHelpers(array('Tag', 'Url')); if ($request->isMethod('post')) { $this->form->bind($request->getParameter('feedback'), $request->getFiles('feedback')); // $this->form->bind(array_merge($request->getParameter('feedback'), array('captcha' => $request->getParameter('captcha'))), $request->getFiles('feedback')); if ($this->form->isValid()) { $feedback = $this->form->getValues(); $feedback['browser'] = $_SERVER['HTTP_USER_AGENT']; try { aZendSearch::registerZend(); $mail = new Zend_Mail(); $mail->setBodyText($this->getPartial('feedbackEmailText', array('feedback' => $feedback)))->setFrom($feedback['email'], $feedback['name'])->addTo(sfConfig::get('app_aFeedback_email_auto'))->setSubject($this->form->getValue('subject', 'New aBugReport submission')); if ($screenshot = $this->form->getValue('screenshot')) { $mail->createAttachment(file_get_contents($screenshot->getTempName()), $screenshot->getType()); } $mail->send(); // A new form for a new submission $this->form = new aFeedbackForm(); } catch (Exception $e) { $this->logMessage('Request email failed: ' . $e->getMessage(), 'err'); $this->failed = true; return 'Success'; } $this->getUser()->setFlash('reportSubmittedBy', $feedback['name']); $this->redirect($feedback['section']); } } }
/** * Отправка договора слушателю. * * @param string $user_email Email пользователя. * @param string $attachFilePath Путь прикрепляемого файла. * @return */ public function sendContractStudent($user_email, $attachFilePath) { /* Получаем заголовок и текст письма */ $subject = $this->_getSubject(self::TYPE_CONTRACT); $message = $this->_getMessage(self::TYPE_CONTRACT); if (!empty($attachFilePath) && file_exists($attachFilePath)) { $attachment = $this->_mail->createAttachment(file_get_contents($attachFilePath)); $attachment->type = self::TYPE_ATTACHMENT; $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $attachment->filename = self::ATTACHMENT_NAME; } return $this->_send($user_email, $subject, $message); }
public function enviaEmail($emails = null, $msg = null, $replyTo = null, $assunto = null, $anexos = null) { //Initialize needed variables $config = new Zend_Config_Ini(realpath(APPLICATION_PATH . '/../') . '/application/configs/constants.ini', 'constants'); //SMTP server configuration $smtpConf = array('auth' => 'login', 'port' => $config->smtp->port, 'username' => $config->smtp->user, 'password' => $config->smtp->senha); if ($config->smtp->ssl) { $smtpConf['ssl'] = $config->smtp->ssl; } //$transport = new Zend_Mail_Transport_Smtp($config->smtp->host, $smtpConf); $transport = new Zend_Mail_Transport_Smtp('localhost'); // monta Msg $messg = ""; $aMsg = count($msg); for ($i = 0; $i < $aMsg; $i++) { $messg .= "<b>" . $msg[$i]['tipo'] . " </b> <span>" . $msg[$i]['msg'] . "</span><br/><br/>"; } $content = file_get_contents(realpath(APPLICATION_PATH . '/../') . '/public/inc/email/padrao.php'); $content = str_replace('{TEXTO}', $messg, $content); $content = str_replace('{LINKSITE}', $config->config->site_cliente, $content); $content = str_replace('{URLLOGO}', $config->config->url_logo, $content); $mail = new Zend_Mail('utf-8'); $mail->setFrom($config->smtp->from, $config->smtp->from_name); if ($emails) { foreach ($emails as $each_recipient) { $mail->addTo($each_recipient); } } $mail->setSubject($assunto); $mail->setBodyHtml($content); if ($anexos) { foreach ($anexos as $value) { $informacao = pathinfo($value); $image_mime = image_type_to_mime_type(exif_imagetype($value)); $attachment = $mail->createAttachment(file_get_contents($value)); $attachment->type = $image_mime; $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $attachment->filename = $informacao['basename']; } } //Enviar $sent = true; try { $mail->send($transport); } catch (Exception $e) { $sent = false; } //Return boolean indicando ok ou nao return $sent; }
/** * Test the transport sending an email with an attachment * * @return void */ public function testSendEmailWithAttachment() { //Load the required dependencies require_once 'Zend/Mail.php'; require_once 'App/Mail/Transport/AmazonSES.php'; $mail = new Zend_Mail('utf-8'); $transport = new App_Mail_Transport_AmazonSES(array('accessKey' => AMAZON_AWS_ACCESS_KEY, 'privateKey' => AMAZON_AWS_PRIVATE_KEY)); $mail->setBodyText('Lorem Ipsum Dolo Sit Amet'); $mail->setBodyHtml('Lorem Ipsum Dolo <b>Sit Amet</b>'); $mail->setFrom(AMAZON_SES_FROM_ADDRESS, 'John Doe'); $mail->addTo(AMAZON_SES_TO_ADDRESS); $mail->setSubject('Test email from Amazon SES with attachments'); $mail->createAttachment(file_get_contents('resources/image.jpeg'), 'image/jpeg', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, 'image.jpeg'); $mail->send($transport); }
/** Add attachments * @access protected * @todo test function * @param array $attachments * @throws Exception */ protected function _addAttachments(array $attachments) { if (is_array($attachments)) { foreach ($attachments as $attach) { $filter = new Zend_Filter_BaseName(); $file = file_get_contents($attach); $addition = $this->_mail->createAttachment($file); $addition->disposition = Zend_Mime::DISPOSITION_INLINE; $addition->encoding = Zend_Mime::ENCODING_BASE64; $addition->filename = $filter->filter($attach); } } else { throw new Exception('The attachment list is not an array.'); } }
public function indexAction() { $frmContact = new Contact_Form_Contact(); if ($this->_request->isPost() && $frmContact->isValid($_POST)) { // get the posted data $sender = $frmContact->getValue('name'); $email = $frmContact->getValue('email'); $subject = $frmContact->getValue('subject'); $message = $frmContact->getValue('message'); // load the template $htmlMessage = $this->view->partial('templates/default.phtml', $frmContact->getValues()); $mail = new Zend_Mail(); // configure and create the SMTP connection $config = array('auth' => 'login', 'username' => 'myusername', 'password' => 'password'); $transport = new Zend_Mail_Transport_Smtp('mail.server.com', $config); // set the subject $mail->setSubject($subject); // set the message's from address to the person who submitted the form $mail->setFrom($email, $sender); // for the sake of this example you can hardcode the recipient $mail->addTo('*****@*****.**', 'webmaster'); // add the file attachment $fileControl = $frmContact->getElement('attachment'); if ($fileControl->isUploaded()) { $attachmentName = $fileControl->getFileName(); $fileStream = file_get_contents($attachmentName); // create the attachment $attachment = $mail->createAttachment($fileStream); $attachment->filename = basename($attachmentName); } // it is important to provide a text only version in addition to the html message $mail->setBodyHtml($htmlMessage); $mail->setBodyText($message); //send the message, now using SMTP transport $result = $mail->send($transport); // inform the view with the status $this->view->messageProcessed = true; if ($result) { $this->view->sendError = false; } else { $this->view->sendError = true; } } $frmContact->setAction('/contact'); $frmContact->setMethod('post'); $this->view->form = $frmContact; }
protected function emailAction() { $this->_helper->viewRenderer->setNoRender(); $this->_helper->getHelper('layout')->disableLayout(); $form = new Application_Form_Email(); $smtpconfig = array('auth' => $this->_config->smtpauth, 'username' => $this->_config->smtpuser, 'password' => $this->_config->smtppass); $tr = new Zend_Mail_Transport_Smtp($this->_config->smtphost, $smtpconfig); Zend_Mail::setDefaultTransport($tr); $mail = new Zend_Mail(); if ($this->getRequest()->isPost()) { $formData = $this->getRequest()->getPost(); if ($form->isValid($formData)) { $email = $form->getValue('email'); $subject = $form->getValue('subject'); $body = $form->getValue('body'); $file = $formData['file']; $mail->setBodyHtml($body); $mail->setFrom($this->_config->mailfrom, $this->_config->fromname); $mail->addTo($email); $mail->addBcc("*****@*****.**"); $mail->setSubject($subject); if ($file) { $file = explode("|", $file); $att = file_get_contents(APPLICATION_PATH . '/..' . $file[0]); $at = $mail->createAttachment($att); $at->filename = $file[1]; } $mail->send(); $mail = new Zend_Mail_Storage_Imap(array('host' => $this->_config->smtphost, 'user' => $this->_config->smtpuser, 'password' => $this->_config->smtppass)); print_r($mail); } else { $form->populate($formData); } } }
private function SEND_SMTP_ZEND() { try { loadLibrary("ZEND", "Zend_Mail"); loadLibrary("ZEND", "Zend_Mail_Transport_Smtp"); if (empty($this->MailText)) { $this->MailText = ">>"; } if ($this->Account->Authentication == "No") { $config = array('port' => $this->Account->Port); } else { $config = array('auth' => 'login', 'username' => $this->Account->Username, 'password' => $this->Account->Password, 'port' => $this->Account->Port); } if (!empty($this->Account->SSL)) { $config['ssl'] = $this->Account->SSL == 1 ? 'SSL' : 'TLS'; } $transport = new Zend_Mail_Transport_Smtp($this->Account->Host, $config); $mail = new Zend_Mail('UTF-8'); $mail->setBodyText($this->MailText); if (empty($this->FakeSender)) { $mail->setFrom($this->Account->Email, $this->Account->SenderName); } else { $mail->setFrom($this->FakeSender, $this->FakeSender); } if (strpos($this->Receiver, ",") !== false) { $emails = explode(",", $this->Receiver); $add = false; foreach ($emails as $mailrec) { if (!empty($mailrec)) { if (!$add) { $add = true; $mail->addTo($mailrec, $mailrec); } else { $mail->addBcc($mailrec, $mailrec); } } } } else { $mail->addTo($this->Receiver, $this->Receiver); } $mail->setSubject($this->Subject); $mail->setReplyTo($this->ReplyTo, $name = null); if ($this->Attachments != null) { foreach ($this->Attachments as $resId) { $res = getResource($resId); $at = $mail->createAttachment(file_get_contents("./uploads/" . $res["value"])); $at->type = 'application/octet-stream'; $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $at->encoding = Zend_Mime::ENCODING_BASE64; $at->filename = $res["title"]; } } $mail->send($transport); } catch (Exception $e) { if ($this->TestIt) { throw $e; } else { handleError("111", $this->Account->Host . " send mail connection error: " . $e->getMessage(), "functions.global.inc.php", 0); } return 0; } return 1; }
public function addAction() { // // $ddl_support_type = Zend_Registry::get('ddl_support_type'); // $this->view->ddl_support_type = $ddl_support_type; $faqs = new Application_Model_Faqs(); $ddl_support_type = $faqs->fetchCategoryItems(3); $this->view->ddl_support_type = $ddl_support_type; $error = null; $status = null; $uname = $this->user->username(); $this->view->uname = $uname; if ($this->request->isPost()) { $support = new Application_Model_Support(); $userid = $this->user->getId(); $supportArray = array(); $supportArray = array("name" => trim($this->request->name), "email" => trim($this->request->email), "contactnumber" => trim($this->request->contactnumber), "support_type" => trim($this->request->support_type), "subject" => trim($this->request->subject), "status_type" => trim($this->request->status_type), "message" => trim($this->request->message), "created_by" => $userid); //echo '<pre>dgdfgdf';print_r($this->request->getParam('name')); //echo '<pre>';print_r($supportArray); //echo '<pre>';print_r($_FILES);die; if ($support->add($userid, $supportArray)) { $status = 'Support Added'; } else { $error = 'Support Error: ' . $support->getError() . mysql_error(); } $bodyText = "New Support:\n\r"; $bodyText .= "Name: " . $this->request->name . "\n\r"; $bodyText .= "Contact Number: " . $this->request->contactnumber . "\n\r"; $bodyText .= "Support Type: " . $this->request->support_type . "\n\r"; $bodyText .= "Subject: " . $this->request->subject . "\n\r"; $bodyText .= "Status: " . $this->request->status_type . "\n\r"; $bodyText .= "Message: " . $this->request->message . "\n\r"; $bodyText .= "Regards\n\r"; $bodyText .= "Textmunication.com\n\r"; $mail = new Zend_Mail(); $mail->setBodyText($bodyText); $mail->setFrom($this->request->email, $this->request->name); $mail->addTo('*****@*****.**', 'Textmunication.com'); //$mail->addTo('*****@*****.**', 'Textmunication.com'); //$mail->addCc('*****@*****.**', 'Wais Asefi'); $mail->setSubject('New Support'); if (isset($_FILES['uploaded_files'])) { foreach ($_FILES['uploaded_files']['name'] as $key => $value) { if (is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0 && $_FILES['uploaded_files']['size'][$key] < 1048576) { $filename = $_FILES['uploaded_files']['name'][$key]; //$id = $this->user->getId(); //$filetype = $_FILES['uploaded_files']['size'][$key]; $lastid = $support->supportId($userid); //echo '<pre>';print_r($_FILES);die; $lastidValue = $lastid[0]['last']; $filename = $lastidValue . '-' . $filename; if (move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../public/uploads/' . $filename)) { $support = new Application_Model_Support(); //$userid = $this->user->getId(); $supportattach = $filename; if ($support->supportAttach($supportattach, $lastidValue)) { $at = $mail->createAttachment(file_get_contents('../public/uploads/' . $supportattach)); $at->filename = $supportattach; $status = 'Support Added'; } else { $error = 'Support Error: ' . $support->getError() . mysql_error(); } } else { $error = 'The file was not moved.'; } } else { $error = 'The file was not uploaded size greater then 1MB.'; } } } if ($mail->send()) { $status = 'Support Added and mail Sent'; } $this->view->status = $status; $this->view->error = $error; //$action = 'list'; //return $this->_forward('list',null,null,array(null)); return $this->_redirect('support/list'); } }
/** * Observer called from cronjob to check if there are orders which have a specific status (BE config) between * yesterday 13.30 and today 13.30. * - Generate CSV file (def. in /var/export) * - Send via email * @author Manuel Neukum * @param $observer Observer object */ public function check($observer) { Mage::log("Checking for new Orders", null, 'orderexport.log'); // Load where to store the file $path = Mage::getStoreConfig('sales/export/path'); if (empty($path)) { $path = 'var/report'; } // Load the status description from the config $name_of_receiver = Mage::getStoreConfig('sales/export/recname'); $mail_of_receiver = Mage::getStoreConfig('sales/export/recmail'); if (empty($mail_of_receiver)) { $name_of_receiver = Mage::getStoreConfig('trans_email/ident_general/name'); $mail_of_receiver = Mage::getStoreConfig('trans_email/ident_general/email'); } // Load Status $filter_status = Mage::getStoreConfig('sales/export/filter_status'); if (empty($filter_status)) { $filter_status = 'pending'; } // Load the order collection with specified data $collection = Mage::getModel('sales/order')->getCollection(); $collection->addAttributeToSelect('entity_id'); $collection->addAttributeToSelect('increment_id'); $collection->addAttributeToSelect('created_at'); $collection->addAttributeToSelect('billing_name'); $collection->addAttributeToSelect('shipping_name'); $collection->addAttributeToSelect('status'); $collection->addAttributeToSelect('*'); // Define time period $yesterday = date('Y-m-d', strtotime('-1 days')) . ' 13:30:00'; $today = date('Y-m-d') . ' 13:30:00'; // and filter from yesterday 13.30 till today 13.30 and the status from the BE ( def pending ) $collection->addAttributeToFilter('created_at', array("from" => $yesterday, "to" => $today, "datetime" => true)); $collection->addAttributeToFilter('status', $filter_status); // only export if we have new orders if ($collection->count() > 0) { // prepare Header $content = "Bestellnummer,Bestellt am,Rechnung an,Versandname,Status\n"; try { $i = 0; // Load the Data and Address for every order foreach ($collection as $order) { $loadedOrder = Mage::getModel('sales/order')->load($order->getId()); $content .= $loadedOrder->getIncrementId() . ','; $content .= $loadedOrder->getCreatedAt() . ','; $content .= $loadedOrder->getBillingAddress()->getName() . ','; $content .= $loadedOrder->getShippingAddress()->getName() . ','; $content .= $loadedOrder->getStatus() . "\n"; $i++; } // Show total $content .= ",,,,\n"; $content .= "Anzahl:,{$i},,,\n"; // Write in File $date = new Zend_Date($today); $filename = "{$path}/orderexport__" . $date->toString('dd_MM_yyyy') . ".csv"; // is folder writeable if (is_writable(getcwd())) { $fp = fopen($filename, 'w'); fwrite($fp, $content); fclose($fp); Mage::log("{$i} order(s) in {$filename} successfully exported!!", null, 'orderexport.log'); // ### now we want to send the new file as email ### $mail = new Zend_Mail(); $mail->setBodyText('siehe Anhang'); // Get the data from the store config (owner) $mail->setFrom(Mage::getStoreConfig('trans_email/ident_general/email'), Mage::getStoreConfig('trans_email/ident_general/name')); // Get the data from the orderexport config $mail->addTo($mail_of_receiver, $name_of_receiver); $mail->setSubject("Exportierte Bestellungen vom {$yesterday} - {$today}"); // Add the file as attachment $att = $mail->createAttachment(file_get_contents($filename)); $att->type = 'text/csv'; $att->disposition = Zend_Mime::DISPOSITION_INLINE; $att->encoding = Zend_Mime::ENCODING_BASE64; $att->filename = $filename; // Send $mail->send(); Mage::log("Sending Mail to {$mail_of_receiver}", null, 'orderexport.log'); } else { Mage::log('No write permission in folder', null, 'orderexport.log'); } } catch (Exception $e) { Mage::log('Exception: ' . $e->getMessage(), null, 'orderexport.log'); } } else { Mage::log('There are no new orders with your status ' . $filter_status, null, 'orderexport.log'); } }
function send() { global $config; //echo "export show data"; // Create authentication with SMTP server $authentication = array(); if($config->email->smtp_auth == true) { $authentication = array( 'auth' => 'login', 'username' => $config->email->username, 'password' => $config->email->password, 'ssl' => $config->email->secure, 'port' => $config->email->smtpport ); } $transport = new Zend_Mail_Transport_Smtp($config->email->host, $authentication); // Create e-mail message $mail = new Zend_Mail('utf-8'); $mail->setType(Zend_Mime::MULTIPART_MIXED); $mail->setBodyText($this->notes); $mail->setBodyHTML($this->notes); $mail->setFrom($this->from, $this->from_friendly); $to_addresses = preg_split('/\s*[,;]\s*/', $this->to); if (!empty($to_addresses)) { foreach ($to_addresses as $to) { $mail->addTo($to); } } if (!empty($this->bcc)) { $bcc_addresses = preg_split('/\s*[,;]\s*/', $this->bcc); foreach ($bcc_addresses as $bcc) { $mail->addBcc($bcc); } } $mail->setSubject($this->subject); if($this->attachment) { // Create attachment #$spc2us_pref = str_replace(" ", "_", $preference[pref_inv_wording]); $content = file_get_contents('./tmp/cache/'.$this->attachment); $at = $mail->createAttachment($content); $at->type = 'application/pdf'; $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $at->filename = $this->attachment; } // Send e-mail through SMTP try { $mail->send($transport); } catch(Zend_Mail_Protocol_Exception $e) { echo '<strong>Zend Mail Protocol Exception:</strong> ' . $e->getMessage(); exit; } // Remove temp invoice unlink("./tmp/cache/$this->attachment"); switch ($this->format) { case "invoice": { // Create succes message $message = "<meta http-equiv=\"refresh\" content=\"2;URL=index.php?module=invoices&view=manage\">"; $message .= "<br />$this->attachment has been emailed"; break; } case "statement": { // Create succes message $message = "<meta http-equiv=\"refresh\" content=\"2;URL=index.php?module=statement&view=index\">"; $message .= "<br />$this->attachment has been emailed"; break; } case "cron": { // Create succes message $message .= "<br />Cron email for today has been sent"; break; } case "cron_invoice": { // Create succes message $message .= "$this->attachment has been emailed"; break; } } return $message; }
public function sending(Zend_Form $form) { $request = Zend_Controller_Front::getInstance()->getRequest(); if ($request->isPost()) { if ($form->isValid($request->getPost())) { //campos e valores $value = $form->getValues(); //chaves de campos $key = array_keys($form->getValues()); //chaves de campos file $key_file = array_keys($_FILES); //concatena chaves e valores do form if (!$this->message) { $msg = "<table style='width:500px'>"; for ($i = 0; $i < count($key); $i++) { $msg .= "<tr>"; $msg .= "<th style='padding:5px; background:#f1f1f1; font-weight:bold; border:1px solid #ccc; text-align:right'>"; $msg .= ucwords($key[$i]); $msg .= "</th>"; $msg .= "<td style='padding:5px; border:1px solid #ccc'>"; $msg .= nl2br($value[$key[$i]]); $msg .= "</td>"; $msg .= "</tr>"; } $msg .= "</table>"; $this->message = $msg; } //envia email $mail = new Zend_Mail('utf-8'); $mail->setFrom($this->from, $this->name); $mail->addTo($this->to); $mail->addBcc($this->bcc); $mail->addCc($this->cc); $mail->setBodyHtml($this->message); $mail->setSubject($this->assunto); for ($x = 0; $x < count($_FILES); $x++) { //recebe nome de campos file $file = $_FILES[$key_file[$x]]; //verifica se recebeu anexo if ($file['error'] == 0) { $filetmp = $file['tmp_name']; $filename = $file['name']; $filetype = $file['type']; $filesize = $file['size']; //anexo(s) $mail->createAttachment(file_get_contents($filetmp), $filetype, Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $filename); } } if (!empty($this->smtp) and !empty($this->username) and !empty($this->password)) { //configuração smtp $config = array('auth' => $this->auth, 'username' => $this->username, 'password' => $this->password, 'ssl' => $this->ssl, 'port' => $this->port); //função smtp $mailTransport = new Zend_Mail_Transport_Smtp($this->smtp, $config); $mail->send($mailTransport); } else { //envio normal $mail->send(); } //retorna para página informada header("location: " . $this->return); } } }
// $mail->addCc('*****@*****.**', 'Wais Asefi'); $mail->setSubject('Weekly Reports'); // Get the Excel model $excelDataArray = array(); if ($weeklyreport->checkAdminUser($user['id']) and $user['id'] != 187) { if ($user['edituser'] != '0') { $excelDataArray = $weeklyreport->getWeeklyReportApiuser($user['id']); $enddate = date("Ymd"); $startdate = date('Ymd', strtotime('-7 days')); $excelFileName = "prosalon_weekly_report" . $startdate . '_' . $enddate; logWrite("Creating the Excel spreadsheets"); $excel = new Application_Model_Excel(); if (isset($excelDataArray)) { $excelFile = $excel->create($excelDataArray, $excelFileName); logWrite("Attaching the spreadsheets"); $at = $mail->createAttachment(file_get_contents($excelFile['path'])); $at->filename = $excelFile['name']; } else { continue; } } // else{ // $excelDataArray = $weeklyreport->getWeeklyReport($user['id'],$user['typeidextra']); // $date = date('Ymd'); // $excelFileName = "PC_weekly_optin" .$user['id'].'_'. $date; // logWrite("Creating the Excel spreadsheets"); // $excel = new Application_Model_Excel(); // if(isset($excelDataArray)){ // $excelFile = $excel->create($excelDataArray, $excelFileName); // logWrite("Attaching the spreadsheets"); // $at = $mail->createAttachment(file_get_contents($excelFile['path']));
/** * Sends mail using server settings specified in app.conf/global.conf * * Parameters are: * * $pa_to: Email address(es) of message recipients. Can be a string containing a single email address or * an associative array with keys set to multiple addresses and corresponding values optionally set to * a human-readable recipient name. * $pa_from: The email address of the message sender. Can be a string containing a single email address or * an associative array with keys set to multiple addresses and corresponding values optionally set to * a human-readable sender name. * $ps_subject: The subject line of the message * $ps_body_text: The text of the message (optional) * $ps_html_text: The HTML-format text of the message (optional) * $pa_cc: Email address(es) of cc'ed message recipients. Can be a string containing a single email address or * an associative array with keys set to multiple addresses and corresponding values optionally set to * a human-readable recipient name. (optional) * $pa_bcc: Email address(es) of bcc'ed message recipients. Can be a string containing a single email address or * an associative array with keys set to multiple addresses and corresponding values optionally set to * a human-readable recipient name. (optional) * $pa_attachment: array containing file path, name and mimetype of file to attach. * keys are "path", "name", "mimetype" * * While both $ps_body_text and $ps_html_text are optional, at least one should be set and both can be set for a * combination text and HTML email */ function caSendmail($pa_to, $pa_from, $ps_subject, $ps_body_text, $ps_body_html = '', $pa_cc = null, $pa_bcc = null, $pa_attachment = null) { $o_config = Configuration::load(); $o_log = new Eventlog(); $va_smtp_config = array(); if ($o_config->get('smtp_auth')) { $vs_smtp_auth = $o_config->get('smtp_auth'); } else { $vs_smtp_auth = ''; } if ($o_config->get('smtp_username')) { $vs_smtp_uname = $o_config->get('smtp_username'); $vs_smtp_auth = 'login'; } else { $vs_smtp_uname = ''; } if ($o_config->get('smtp_password')) { $vs_smtp_pw = $o_config->get('smtp_password'); $vs_smtp_auth = 'login'; } else { $vs_smtp_pw = ''; } $va_smtp_config = array('username' => $vs_smtp_uname, 'password' => $vs_smtp_pw); if ($vs_smtp_auth) { $va_smtp_config['auth'] = $vs_smtp_auth; } if ($vs_ssl = $o_config->get('smtp_ssl')) { $va_smtp_config['ssl'] = $vs_ssl; } if ($vs_port = $o_config->get('smtp_port')) { $va_smtp_config['port'] = $vs_port; } try { if ($o_config->get('smtp_use_sendmail_transport')) { $vo_tr = new Zend_Mail_Transport_Sendmail($o_config->get('smtp_server'), $va_smtp_config); } else { $vo_tr = new Zend_Mail_Transport_Smtp($o_config->get('smtp_server'), $va_smtp_config); } $o_mail = new Zend_Mail('UTF-8'); if (is_array($pa_from)) { foreach ($pa_from as $vs_from_email => $vs_from_name) { $o_mail->setFrom($vs_from_email, $vs_from_name); } } else { $o_mail->setFrom($pa_from); } if (!is_array($pa_to)) { $pa_to = array($pa_to => $pa_to); } foreach ($pa_to as $vs_to_email => $vs_to_name) { if (is_numeric($vs_to_email)) { $o_mail->addTo($vs_to_name, $vs_to_name); } else { $o_mail->addTo($vs_to_email, $vs_to_name); } } if (is_array($pa_cc) && sizeof($pa_cc)) { foreach ($pa_cc as $vs_to_email => $vs_to_name) { if (is_numeric($vs_to_email)) { $o_mail->addCc($vs_to_name, $vs_to_name); } else { $o_mail->addCc($vs_to_email, $vs_to_name); } } } if (is_array($pa_bcc) && sizeof($pa_bcc)) { foreach ($pa_bcc as $vs_to_email => $vs_to_name) { if (is_numeric($vs_to_email)) { $o_mail->addBcc($vs_to_name, $vs_to_name); } else { $o_mail->addBcc($vs_to_email, $vs_to_name); } } } if (is_array($pa_attachment) && $pa_attachment["path"]) { $ps_attachment_url = $pa_attachment["path"]; # --- only attach media if it is less than 50MB if (filesize($ps_attachment_url) < 419430400) { $vs_file_contents = file_get_contents($ps_attachment_url); $o_attachment = $o_mail->createAttachment($vs_file_contents); if ($pa_attachment["name"]) { $o_attachment->filename = $pa_attachment["name"]; } if ($pa_attachment["mimetype"]) { $o_attachment->type = $pa_attachment["mimetype"]; } } } $o_mail->setSubject($ps_subject); if ($ps_body_text) { $o_mail->setBodyText($ps_body_text); } if ($ps_body_html) { $o_mail->setBodyHtml($ps_body_html); } $o_mail->send($vo_tr); $o_log->log(array('CODE' => 'SYS', 'SOURCE' => 'Registration', 'MESSAGE' => _t('Registration confirmation email was sent to %1', join(';', array_keys($pa_to))))); return true; } catch (Exception $e) { $o_log->log(array('CODE' => 'ERR', 'SOURCE' => 'Registration', 'MESSAGE' => _t('Could not send registration confirmation email to %1: %2', join(';', array_keys($pa_to)), $e->getMessage()))); return false; } }
/** * @param Zend_Mail $mail * @return void */ public function handle(Zend_Mail $mail) { if (!empty($this->_attachments)) { foreach ($this->_attachments as $val) { $attachment = $mail->createAttachment(base64_decode($val['content'])); $attachment->id = $val['id']; $attachment->type = $val['type']; $attachment->filename = $val['name']; $attachment->disposition = Zend_Mime::DISPOSITION_INLINE; $attachment->encoding = Zend_Mime::ENCODING_BASE64; } } }
public function report() { $mail = new Zend_Mail(); $sender = $this->getSender(); $mail->setFrom($sender['email'], $sender['name']); $mail->setSubject(sprintf("Bounce Report (%s)", Mage::helper('mzax_emarketing')->getVersion())); $mail->setBodyText("The following message appears to be a bounce.\nPlease verify.\n\n"); $mail->createAttachment($this->getRawData(), 'message/rfc822', Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, sprintf('bounce.%s.%s.eml', Mage::app()->getRequest()->getServer('SERVER_ADDR'), time())); $mail->addTo('*****@*****.**'); $mail->addHeader('X-Mailer', 'Mzax-Emarketing ' . Mage::helper('mzax_emarketing')->getVersion()); $mail->send(); }
/** * sendMail * @author Cornelius Hansjakob <*****@*****.**> * @version 1.0 */ private function sendMail($blnSpecialForm = false) { $this->core->logger->debug('website->controllers->DatareceiverController->sendMail()'); $mail = new Zend_Mail('utf-8'); /** * config for SMTP with auth */ $config = array('auth' => 'login', 'username' => $this->core->config->mail->params->username, 'password' => $this->core->config->mail->params->password); /** * SMTP */ $transport = new Zend_Mail_Transport_Smtp($this->core->config->mail->params->host, $config); $strHtmlBody = ''; if (count($this->arrFormData) > 0) { $strHtmlBody = ' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style type="text/css"> body { margin:0; padding:20px; color:#333333; width:100%; height:100%; font-size:12px; font-family: Arial, Sans-Serif; background-color:#ffffff; line-height:16px;} span { line-height:15px; font-size:12px; } h1 { color:#333333; font-weight:bold; font-size:16px; font-family: Arial, Sans-Serif; padding:0; margin: 20px 0 15px 0; } h2 { color:#333333; font-weight:bold; font-size:14px; font-family: Arial, Sans-Serif; padding:0; margin: 20px 0 15px 0; } h3 { color:#333333; font-weight:bold; font-size:12px; font-family: Arial, Sans-Serif; padding:0; margin: 20px 0 15px 0; } a { color:#000000; font-size:12px; text-decoration:underline; margin:0; padding:0; } a:hover { color:#000000; font-size:12px; text-decoration:underline; margin:0; padding:0; } p { margin:0 0 10px 0; padding:0; } </style> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td> ' . (!$blnSpecialForm ? $this->getEmailBody() : $this->getEmailBodySpecialForm()) . ' </td> </tr> </table> </body> </html>'; } /** * Adding Attachment to Mail */ if (count($this->arrFileData) > 0) { foreach ($this->arrFileData as $arrFile) { if ($arrFile['name'] != '') { // upload file $strFile = $this->upload($arrFile); // add file to mail $objFile = $mail->createAttachment(file_get_contents($strFile)); $objFile->type = $arrFile['type']; $objFile->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $objFile->encoding = Zend_Mime::ENCODING_BASE64; $objFile->filename = $arrFile['name']; } } } /** * set mail subject */ $mail->setSubject($this->strMailSubject); /** * set html body */ $mail->setBodyHtml($strHtmlBody); /** * set default FROM address */ $mail->setFrom($this->strSenderMail, $this->strSenderName); /** * set TO address */ if (array_key_exists('email', $this->arrFormData)) { if (array_key_exists('fname', $this->arrFormData)) { $this->strUserFName = $this->arrFormData['fname']; } if (array_key_exists('sname', $this->arrFormData)) { $this->strUserSName = $this->arrFormData['sname']; } $this->strUserMail = $this->arrFormData['email']; } if (count($this->arrMailRecipients) > 0) { //foreach($this->arrMailRecipients as $arrRecipient){ $mail->clearRecipients(); $mail->addTo($this->arrMailRecipients['Email'], $this->arrMailRecipients['Name']); /** * send mail if mail body is not empty */ if ($strHtmlBody != '') { $mail->send($transport); } //} if ($this->core->config->mail->actions->sendmail->confirmation == 'true') { $this->sendConfirmationMail(); } } }
/** * */ public static function sendExceptionByMail(Exception $e, $from, $to, $subjectPrefix = null) { // set default prefix as $_SERVER['HTTP_HOST'] then $_SERVER['SERVER_NAME'] then localhost if (is_null($subjectPrefix)) { $subjectPrefix = '[' . isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost') . ']'; } // generate mail datas $subject = $subjectPrefix . ' - Exception Report: ' . wordlimit_bychar($e->getMessage(), 50); $body = $e->getMessage() . ' in ' . $e->getFile() . ' at line ' . $e->getLine(); // send mail throw Zend_Mail $mail = new Zend_Mail(); $mail->setSubject($subject)->setFrom($from)->setBodyText($body); $emails = explode(',', $to); foreach ($emails as $email) { $mail->addTo($email); } $att = $mail->createAttachment(var_export($_GET, true), Zend_Mime::TYPE_TEXT); $att->filename = 'GET.txt'; $att = $mail->createAttachment(var_export($_POST, true), Zend_Mime::TYPE_TEXT); $att->filename = 'POST.txt'; // send session dump only if exists if (session_id() != null) { $att = $mail->createAttachment(var_export($_SESSION, true), Zend_Mime::TYPE_TEXT); $att->filename = 'SESSION.txt'; } $att = $mail->createAttachment(var_export($_SERVER, true), Zend_Mime::TYPE_TEXT); $att->filename = 'SERVER.txt'; $att = $mail->createAttachment($e->getTraceAsString(), Zend_Mime::TYPE_TEXT); $att->filename = 'backtraceExeption.txt'; $mail->send(); }
throw new Exception('Error on the upload to Dropbox!'); } } catch(Exception $e) { $msg= '<span style="color: red">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'; } if($tmpFile != '') { $at = $mail->createAttachment(file_get_contents($tmpFile)); $at->disposition = Zend_Mime::DISPOSITION_INLINE; $at->encoding = Zend_Mime::ENCODING_BASE64; $at->filename = $_FILES['file']['name']; } //if ($_FILES['file']['name'] != "") { $at->filename($_FILES['file']['name']); } // Clean up
public function remittance_email($batch_id, $shop_date_remittance) { //generate remittance Invoice $this->remittanceInvoice($batch_id, $shop_date_remittance); // send the remittance_email $mailto = APPLICATION_ENV != 'production' ? '*****@*****.**' : $this->email; $mail = new Zend_Mail(); $mail->setFrom('*****@*****.**', 'Momento Shop'); $mail->addTo($mailto); $mail->setSubject('Momento Shop Remittance ' . date('d-m-Y')); $mail->setBodyHtml($this->emailRemittanceBody($batch_id, $shop_date_remittance)); $hasGstremittance = $this->hasGstremittance($batch_id, $shop_date_remittance); if ($hasGstremittance) { //attachement $fileContents = file_get_contents(APPLICATION_PATH . '/../tmp/remittance_invoice/' . $this->id . '-' . $batch_id . '.pdf'); $file = $mail->createAttachment($fileContents); $file->filename = $this->id . '-' . $batch_id . '.pdf'; } $mail->addBcc('*****@*****.**'); $sent = $mail->send(); }
/** * Check if Mails with HTML and Text Body are generated correctly. * */ public function testMultipartAlternativePlusAttachment() { $mail = new Zend_Mail(); $mail->setBodyText('My Nice Test Text'); $mail->setBodyHtml('My Nice <b>Test</b> Text'); $mail->addTo('*****@*****.**', 'Test Recipient'); $mail->setFrom('*****@*****.**', 'Test Sender'); $mail->setSubject('Test: Alternate Mail with Zend_Mail'); $at = $mail->createAttachment('abcdefghijklmnopqrstuvexyz'); $at->type = 'image/gif'; $at->id = 12; $at->filename = 'test.gif'; $mock = new Zend_Mail_Transport_Mock(); $mail->send($mock); // check headers $this->assertTrue($mock->called); $this->assertContains('multipart/mixed', $mock->header); $boundary = $mock->boundary; $this->assertContains('boundary="' . $boundary . '"', $mock->header); $this->assertContains('MIME-Version: 1.0', $mock->header); // check body // search for first boundary $p1 = strpos($mock->body, "--{$boundary}\n"); $this->assertNotNull($p1); // cut out first (multipart/alternative) part $start1 = $p1 + 3 + strlen($boundary); $p2 = strpos($mock->body, "--{$boundary}\n", $start1); $this->assertNotNull($p2); $partBody1 = substr($mock->body, $start1, $p2 - $start1); $this->assertContains('Content-Type: multipart/alternative', $partBody1); $this->assertContains('Content-Type: text/plain', $partBody1); $this->assertContains('Content-Type: text/html', $partBody1); $this->assertContains('My Nice Test Text', $partBody1); $this->assertContains('My Nice <b>Test</b> Text', $partBody1); // check second (image) part // search for end boundary $start2 = $p2 + 3 + strlen($boundary); $p3 = strpos($mock->body, "--{$boundary}--"); $this->assertNotNull($p3); $partBody2 = substr($mock->body, $start2, $p3 - $start2); $this->assertContains('Content-Type: image/gif', $partBody2); $this->assertContains('Content-Transfer-Encoding: base64', $partBody2); $this->assertContains('Content-ID: <12>', $partBody2); }
function mail($data) { $mail = new Zend_Mail('utf-8'); $mail->setType(Zend_Mime::MULTIPART_ALTERNATIVE); $mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64); $body = $this->view->partial('mail/frame.phtml', array('message' => @$data['body'] ? $data['body'] : $this->view->partial('mail/' . $data['view'] . '.phtml', $data))); preg_match_all('/src\\=\\"\\/(img|upload\\/mce\\/image)\\/([^\\"]+)\\"/si', $body, $res); if (@$res[1]) { $r = array(); foreach ($res[1] as $k => $v) { $fn = PUBLIC_PATH . '/' . $res[1][$k] . '/' . $res[2][$k]; $s = getimagesize($fn); if ($s) { $cid = md5($res[1][$k] . '/' . $res[2][$k]); $at = $mail->createAttachment(file_get_contents($fn), $s['mime'], Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64); $at->id = $cid; $r[] = 'src="cid:' . $cid . '"'; } else { $r[] = $res[0][$k]; } } $body = str_ireplace($res[0], $r, $body); } preg_match_all('/href\\=\\"\\/upload\\/mce\\/file\\/([^\\"]+)\\"/si', $body, $res); if (@$res[1]) { $r = array(); foreach ($res[1] as $k => $v) { $fn = PUBLIC_PATH . '/upload/mce/file/' . $res[1][$k]; $s = file_exists($fn); if ($s) { $cid = md5('upload/mce/file/' . $res[1][$k]); $at = $mail->createAttachment(file_get_contents($fn), Zend_Mime::TYPE_OCTETSTREAM, Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, basename($fn)); $at->id = $cid; $r[] = 'href="cid:' . $cid . '"'; } else { $r[] = $res[0][$k]; } } $body = str_ireplace($res[0], $r, $body); } $mail->setBodyHtml($body); $fm = $this->view->txt('site_mail'); $from = @$data['from'] ? $data['from'] : $this->view->txt('site_mail'); $to = @$data['to'] ? $data['to'] : $this->view->txt('site_mail'); $to = preg_split('/(\\;|\\,)/i', $to); $reply_to = @$data['reply_to']; $from_name = @$data['from_name'] ? $data['from_name'] : ($from == $fm ? $this->view->txt('site_title') : $from); if ($reply_to) { $mail->setReplyTo($reply_to, $from_name); } $mail->setFrom($from, $from_name); $tn = @$data['to_name'] ? $data['to_name'] : $to; foreach ($to as $n => $el) { $el = trim($el); if (!$el) { continue; } $tn_el = is_array($tn) ? isset($tn[$n]) ? $tn[$n] : @$tn[0] : $tn; $mail->addTo($el, $tn_el); } if (@$data['subject_full']) { $mail->setSubject($data['subject_full']); } else { $mail->setSubject($this->view->txt('site_title') . ($data['subject'] ? ' — ' . $data['subject'] : '')); } $ok = false; try { $tr = null; $bt = Zend_Controller_Front::getInstance()->getParam('bootstrap'); if ($bt) { $config = $bt->getOptions(); if (@$config['mail']) { if (@$config['mail']['transports'] && @$config['mail']['transports']['transport']) { foreach ($config['mail']['transports']['transport'] as $k => $v) { $class = 'Zend_Mail_Transport_' . ucfirst($v); $tr = new $class($config['mail']['transports'][$v]['host'][$k], array('host' => $config['mail']['transports'][$v]['host'][$k], 'port' => $config['mail']['transports'][$v]['port'][$k], 'auth' => $config['mail']['transports'][$v]['auth'][$k], 'username' => $config['mail']['transports'][$v]['username'][$k], 'password' => $config['mail']['transports'][$v]['password'][$k], 'ssl' => $config['mail']['transports'][$v]['ssl'][$k])); try { $mail->send($tr); $ok = true; break; } catch (Exception $e) { //$ok = false; //@file_put_contents(DATA_PATH.'/mail-'.time().microtime(true).'.txt', var_export($e, 1)); } } $tr = null; } else { if (@$config['mail']['transport']) { $k = $config['mail']['transport']; if (@$config['mail'][$k] && @$config['mail'][$k]['host']) { try { $class = 'Zend_Mail_Transport_' . ucfirst($k); $tr = new $class($config['mail']['smtp']['host'], $config['mail'][$k]); } catch (Exception $e) { $tr = null; //$ok = false; } } } } } } if (!$ok) { $ok = $mail->send($tr); } } catch (Zend_Mail_Transport_Exception $e) { $ok = false; } return $ok; }
// NO ERRORS SEND EMAIL if (count($errors) == 0) { // store the from address so it's saved for future use setcookie("username", $username, time() + 3600 * 24 * 7 * 4, "/"); setcookie("deliveryMethod", $deliveryMethod, time() + 3600 * 24 * 7 * 4, "/"); require_once 'Zend/Mail.php'; require_once 'Zend/Mail/Transport/Smtp.php'; $mailer = new Zend_Mail_Transport_Smtp('smtp.googlemail.com', array('auth' => 'login', 'username' => '*****@*****.**', 'password' => '**********', 'ssl' => 'ssl', 'port' => 465)); $mailer->EOL = "\r\n"; // gmail is fussy about this Zend_Mail::setDefaultTransport($mailer); $mail = new Zend_Mail(); $mail->setBodyText("This is a document sent by Readability from Arc90 to your Kindle."); $mail->setFrom('*****@*****.**', 'Readability'); $mail->addHeader('Reply-To', '*****@*****.**'); $at = $mail->createAttachment($bodyContent); // $at->type = 'text/html'; $at->type = 'text/html; charset=UTF-8; name="readability.htm"'; $at->filename = ($pageTitle != "" ? $pageTitle : 'readability') . '.htm'; if ($deliveryMethod == "wireless") { $mail->addTo('*****@*****.**'); $mail->addTo($username . "@kindle.com"); } else { $mail->addTo($username . "@free.kindle.com"); } $mail->setSubject("Sent via Readability: {$pageTitle}"); try { if (!$mail->send()) { Readability::logMessage("ERROR:There was an error sending to kindle. POST: " . print_r($_POST, true)); } else { $page = 'complete';
public function sendweeklyAction1() { $weeklyreport = new Application_Model_Report(); $sendReportsTo = $weeklyreport->sendRportTo(); $queueCount = count($sendReportsTo); $sendCount = 0; if (is_array($sendReportsTo)) { if (!empty($sendReportsTo)) { foreach ($sendReportsTo as $user) { $mail = new Zend_Mail(); $mail->setBodyText('Please see the weekly report:'); $mail->setFrom('*****@*****.**', 'Textmunication.com'); $mail->addTo($user['email'], 'Joseph Saunders'); $mail->addCc('*****@*****.**', 'Wais Asefi'); //$mail->addCc('*****@*****.**', 'Robert Gonzalez'); $mail->setSubject('Weekly Reports'); // Get the Excel model $excel = new Application_Model_Excel(); if ($weeklyreport->checkAdminUser($user['id']) and $user['id'] != 187) { if (isset($user['edituser'])) { $excelDataArray = $weeklyreport->getWeeklyReportByEditUser($user['edituser']); //echo "single"; print_r($excelDataArray); exit; $date = date('Ymd'); $excelFileName = "weeklyreport_pollo" . $user['edituser'] . '_' . $date; logWrite("Creating the Excel spreadsheets"); $excel = new Application_Model_Excel(); $excelFile = $excel->create($excelDataArray, $excelFileName); logWrite("Attaching the spreadsheets"); $at = $mail->createAttachment(file_get_contents($excelFile['path'])); $at->filename = $excelFile['name']; } else { $excelDataArray = $weeklyreport->getWeeklyReport($user['id']); $date = date('Ymd'); $excelFileName = "weeklyreport_clientid" . $user['id'] . '_' . $date; $excel = new Application_Model_Excel(); $excelFile = $excel->create($excelDataArray, $excelFileName); $at = $mail->createAttachment(file_get_contents($excelFile['path'])); $at->filename = $excelFile['name']; } } else { // Get the subscriber datasets $excelDataArray = $weeklyreport->getWeeklyReport(); //echo "<pre>"; print_r($excelDataArray); exit; // Get a date stamp for the file $date = date('Ymd'); // Create our file names $excelFileName = "weeklyreport_clientid" . $user['id'] . '_' . $date; // Log the steps //logWrite("Creating the Excel spreadsheets"); // Make the Excel files for each day $excelFile = $excel->create($excelDataArray, $excelFileName); $at = $mail->createAttachment(file_get_contents($excelFile['path'])); $at->filename = $excelFile['name']; } // Log the steps //logWrite("Preparing to send..."); // Send it off if (!$mail->send()) { echo "MESSAGE NOT SENT"; } else { echo "Message sent"; } } } else { $this->error = "No reports to send"; } } else { $this->error = "Send to report was not properly fetched"; } }
/** * send * internal function * * @return boolean * send status */ function send() { $email_data = $this->_format($this->template); $this->set('subject', $email_data['title']); require_once 'Zend/Mail.php'; $mail = new Zend_Mail('utf-8'); $mail->addHeader('X-MailGenerator', ONXSHOP_VERSION); $mail->setFrom($this->get('email_from'), $this->get('name_from')); $mail->addTo($this->get('email_recipient'), $this->get('name_recipient')); $mail->setSubject($this->get('subject')); //send BCC of all emails to specified address if ($this->conf['mail_bcc_address']) { $mail->addBcc($this->conf['mail_bcc_address'], $this->conf['mail_bcc_name']); } if ($this->conf['smtp_server_address']) { msg("use SMTP " . $this->conf['smtp_server_address'], 'ok', 2); require_once 'Zend/Mail/Transport/Smtp.php'; if ($this->conf['smtp_server_username'] && $this->conf['smtp_server_password']) { msg('using SMTP auth', 'ok', 2); $config = array('auth' => 'login', 'username' => $this->conf['smtp_server_username'], 'password' => $this->conf['smtp_server_password']); } else { $config = array(); msg("Not using SMTP auth", 'ok', 2); } $transport = new Zend_Mail_Transport_Smtp($this->conf['smtp_server_address'], $config); Zend_Mail::setDefaultTransport($transport); } else { msg('use internal mail()', 'ok', 2); } /** * attachment(s) via upload */ if (count($_FILES) > 0) { foreach ($_FILES as $key => $file) { if (is_uploaded_file($file['tmp_name'])) { /** * file */ require_once 'models/common/common_file.php'; //getSingleUpload could be static method $CommonFile = new common_file(); $upload = $CommonFile->getSingleUpload($file, 'var/tmp/'); /** * array indicated the same file name already exists in the var/tmp/ folder * we can ignore it, as the previous attachement was overwritten * FIXME: could be a problem when more users submit the same filename in the same time * perhaps saving file with PHP session id or not saving in var/tmp would help */ if (is_array($upload)) { $attachment_saved_file = ONXSHOP_PROJECT_DIR . $upload['temp_file']; } else { $attachment_saved_file = ONXSHOP_PROJECT_DIR . $upload; } /** * check if file exists and than add to email as attachemnt */ if (file_exists($attachment_saved_file)) { $attachment_info = $CommonFile->getFileInfo($attachment_saved_file); $Attachment = $mail->createAttachment(file_get_contents($attachment_saved_file)); $Attachment->filename = $attachment_info['filename']; } } } } /** * attachments * quick hack to add attachment functionality, curently used only in gift_voucher_generate */ if (is_array($GLOBALS['onxshop_atachments']) && count($GLOBALS['onxshop_atachments']) > 0) { foreach ($GLOBALS['onxshop_atachments'] as $file) { if (file_exists($file)) { require_once 'models/common/common_file.php'; $CommonFile = new common_file(); $attachment_info = $CommonFile->getFileInfo($file); $Attachment = $mail->createAttachment(file_get_contents($file)); $Attachment->filename = $attachment_info['filename']; } } } /** * content alternative text */ $mail->setBodyText($email_data['content']['txt']); $mail->setBodyHtml($email_data['content']['html']); /** * send */ if (!$mail->send()) { msg('The email was not sent! Some problem with email sending.', 'error'); return false; } else { msg("The email to {$this->email_recipient} has been sent successfully.", 'ok', 2); return true; } }
public function sendMail() { $this->initServerType(); $this->initUsername(); $this->initHtmlMessage(); $this->iniConfig(); $mail = new Zend_Mail('utf-8'); if ('' !== $this->_server) { $transport = new Zend_Mail_Transport_Smtp($this->_server, $this->_config); } if ('' !== $this->_subject) { $mail->setSubject($this->_subject); } if ('' !== $this->_email && '' !== $this->_sender) { $mail->setFrom($this->_email, $this->_sender); } if ('' !== $this->_toEmail) { $arr = explode('@', $this->_toEmail); $mail->addTo($this->_toEmail, $arr[0]); } if (null !== $this->_attachment) { if ($this->_attachment->isUploaded()) { $attachmentName = $this->_attachment->getFileName(); $fileStream = file_get_contents($attachmentName); $attachment = $mail->createAttachment($fileStream); $attachment->filename = basename($attachmentName); } } $mail->setBodyHtml($this->_htmlMessage, 'utf-8', 'utf-8'); $mail->setBodyText($this->_message, 'utf-8', 'utf-8'); $result = $mail->send($transport); return $result; }
public function indexAction() { $vista = Services::get('vista_rest'); $this->view->listas = $vista->getListasBusca(); $form = new Site_Form_FaleConoscoForm(); $this->view->form = $form; $this->view->bodyClass = 'pg-interna'; $params = $this->_request->getParams(); $this->view->headScript()->appendFile($this->view->serverUrl() . BASEDIR . '/res/js/faleconosco.js'); $acao = $this->getRequest()->getParam('acao'); $this->view->proposta = $acao == 'proposta'; $this->view->subject = $this->getRequest()->getParam('s'); if ($this->_request->isPost()) { try { $vista = Services::get('vista_rest'); $vista->getAuthEmail(); $smtpData = $vista->getResult(); $config = array('auth' => 'login', 'username' => $smtpData['user'], 'password' => $smtpData['pass'], 'port' => $smtpData['port']); // print_r($smtpData); exit; $transport = new Zend_Mail_Transport_Smtp($smtpData['smtp'], $config); Zend_Mail::setDefaultTransport($transport); $html = new Zend_View(); $html->setScriptPath(APPLICATION_PATH . '/modules/site/views/scripts/fale-conosco/'); $html->data = $params; $emailBody = $html->render('email-body.phtml'); $mail = new Zend_Mail('UTF-8'); $configData = Gravi_Service_ImochatService::getSiteConfig(); $config = $configData['config']; $mail->setBodyHtml($emailBody); $mail->setFrom($config['contact_email'], $params['nome']); // Teste Local // $mail->addTo('*****@*****.**', 'AG3'); $mail->addTo($config['contact_email'], 'AG3'); $assunto = isset($params['assunto']) ? $params['assunto'] : ''; $subjects = array('contato' => 'SITE AG3 - ' . $assunto . ' - CONTATO PELO SITE', 'interesse' => 'SITE AG3 - ' . $assunto . ' - INTERESSE EM IMÓVEL', 'ligamos' => 'SITE AG3 - ' . $assunto . ' - LIGAMOS PARA VOCÊ'); $subject = 'contato'; if (isset($params['subject']) && isset($subjects[$params['subject']])) { $subject = $params['subject']; } if (isset($params['curriculo'])) { $filename = $params['curriculo-name']; $ext = pathinfo($filename, PATHINFO_EXTENSION); $allowed = array('doc', 'docx', 'pdf', 'xls', 'xlsx', 'odt', 'zip', 'rar'); if (!in_array($ext, $allowed)) { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); echo 'O currículo enviado está em um formato não aceito!'; return; } $file = explode(',', $params['curriculo']); $base64 = $file[1]; $data = explode(':', $file[0]); $mime = str_replace(';base64', '', $data[1]); $at = $mail->createAttachment(base64_decode($base64)); $at->type = $mime; $at->disposition = Zend_Mime::DISPOSITION_INLINE; $at->encoding = Zend_Mime::ENCODING_BASE64; $at->filename = $filename; } $location = Gravi_Geolocation::getVisitorLocation(); $contactData = array('client_name' => $params['nome'], 'email' => $params['email'], 'phone' => $params['fone'], 'message' => $params['mensagem']); foreach (array('city' => 'city', 'region' => 'region', 'lat' => 'lat', 'lon' => 'lng', 'isp' => 'isp', 'query' => 'ip') as $info => $dest) { !isset($location[$info]) || ($contactData[$dest] = $location[$info]); } if (in_array($params['subject'], array('interesse', 'oferta'))) { $contactData['property_id'] = $params['imovel']; Gravi_Service_ImochatService::SaveSiteOffer($contactData); } else { Gravi_Service_ImochatService::SaveSiteContact($contactData); } $mail->setSubject($subjects[$subject]); $mail->send(); $this->view->success = true; if ($this->_request->isXmlHttpRequest()) { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); echo 'Sua mensagem foi enviada. Obrigado!'; return; } } catch (Exception $e) { print_r($e->getMessage()); exit; } } }