function sendmail($subject, $mailcontent, $receiver, $receivername, $attachment = "") { if (strpos($_SERVER['HTTP_HOST'], "localhost")) { return false; } $mail = new phpmailer(); $mail->IsSMTP(); $mail->Host = "mail.pepool.com"; $mail->Port = 2525; $mail->SMTPAuth = true; $mail->Username = "******"; // Write SMTP username in "" $mail->Password = "******"; $mail->Mailer = "smtp"; $mail->IsHTML(true); $mail->ClearAddresses(); $mail->From = "*****@*****.**"; $mail->FromName = "pepool"; $mail->Subject = $subject; $mail->Body = $mailcontent; $mail->AddAddress($receiver, $receivername); if ($attachment != '') { $mail->AddAttachment($attachment); } $suc = $mail->Send(); return $suc > 0; }
function envmail($email, $subject, $msg, $from, $fromname = "Opala Clube Franca") { require_once "class.phpmailer.php"; $mail = new phpmailer(); $mail->ClearAddresses(); $mail->ClearAllRecipients(); $mail->ClearAddresses(); $mail->ClearCustomHeaders(); $mail->IsSMTP(); // $mail->IsSendmail(); $mail->From = $from; $mail->FromName = $fromname; // $mail->Hostname = "smtp.gmail.com"; // $mail->Host = "smtp.gmail.com"; $mail->SMTPSecure = "ssl"; $mail->Hostname = "smtp.opalaclubefranca.com.br"; $mail->Host = "smtp.opalaclubefranca.com.br"; // $mail->SMTPDebug = 2; $mail->Username = "******"; $mail->Password = "******"; $mail->SMTPAuth = true; $mail->Port = 465; $mail->Timeout = 120; $body = $msg; $text_body = $msg; $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $body; $mail->AltBody = $text_body; if (is_array($email)) { foreach ($email as $em) { $mail->AddAddress($em, ""); } } else { $mail->AddAddress($email, ""); } /* echo '<tr><td>To '.$email.'</td></tr>'."\n"; echo '<tr><td>Assunto '.$subject.'</td></tr>'."\n"; echo '<tr><td>Mensagem '.$msg.'</td></tr>'."\n"; echo '<tr><td>From '.$from.'</td></tr>'."\n"; */ $exito = $mail->Send(); $v = 0; // echo "<tr><td>ErrorInfo " . $mail->ErrorInfo . "<br></td></tr>"; while (!$exito && $v < 5 && $mail->ErrorInfo != "SMTP Error: Data not accepted.") { sleep(2); $exito = $mail->Send(); echo "<tr><td>ErrorInfo " . $mail->ErrorInfo . "<br></td></tr>"; $v = $v + 1; } if (!$exito) { echo "<tr><td>There has been a mail error sending to " . $mail->ErrorInfo . "<br></td></tr>"; } $mail->ClearAddresses(); $mail->ClearAttachments(); return $mail->ErrorInfo; }
function send($newsletter_id) { global $db; $owpDBTable = owpDBGetTables(); $send_mail = new phpmailer(); $send_mail->From = OWP_EMAIL_ADDRESS; $send_mail->FromName = OWP_NAME; $send_mail->Subject = $this->title; $sql = "SELECT admin_gender, admin_firstname, admin_lastname,\n admin_email_address \n FROM " . $owpDBTable['administrators'] . " \n WHERE admin_newsletter = '1'"; $mail_values = $db->Execute($sql); while ($mail = $mail_values->fields) { $send_mail->Body = $this->content; $send_mail->AddAddress($mail['admin_email_address'], $mail['admin_firstname'] . ' ' . $mail['admin_lastname']); $send_mail->Send(); // Clear all addresses and attachments for next loop $send_mail->ClearAddresses(); $send_mail->ClearAttachments(); $mail_values->MoveNext(); } $today = date("Y-m-d H:i:s"); $db->Execute("UPDATE " . $owpDBTable['newsletters'] . " \n SET date_sent = " . $db->DBTimeStamp($today) . ",\n status = '1' \n WHERE newsletters_id = '" . owpDBInput($newsletter_id) . "'"); }
function SendMail($email, $name, $subject, $message) { global $sockethost, $smtpauth, $smtpauthuser, $smtpauthpass, $socketfrom, $socketfromname, $socketreply, $socketreplyname; include 'class.phpmailer.php'; $mail = new phpmailer(); $mail->IsSMTP(); $mail->Host = $sockethost; if ($smtpauth == 'TRUE') { $mail->SMTPAuth = true; $mail->Username = $smtpauthuser; $mail->Password = $smtpauthpass; } if (isset($_GET['caseid']) && ($_GET['caseid'] == 'NewTicket' || $_GET['caseid'] == 'view')) { $mail->From = $email; $mail->FromName = $name; $mail->AddReplyTo($email, $name); } else { $mail->From = $socketfrom; $mail->FromName = $socketfromname; $mail->AddReplyTo($socketreply, $socketreplyname); } $mail->IsHTML(False); $mail->Body = $message; $mail->Subject = $subject; if (isset($_GET['caseid']) && ($_GET['caseid'] == 'NewTicket' || $_GET['caseid'] == 'view')) { $mail->AddAddress($socketfrom, $socketfromname); } else { $mail->AddAddress($email, $name); } if (!$mail->Send()) { return 'Error: ' . $mail->ErrorInfo; } else { return 'Email Sent.'; } $mail->ClearAddresses(); }
function sendMail($fileIN, $fileOUT, $naviera) { //$razonSocial = "MOPSA, S.A. de C.V."; $dominio = "www.almartcon.com"; $att = "Robot"; $fileINOnlyName = str_replace("../ediCodeco/", "", $fileIN); $fileOUTOnlyName = str_replace("../ediCodeco/", "", $fileOUT); // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los métodos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; $mail->Port = 26; // Configurar la cuenta de correo. $mail->Host = "mail.nesoftware.net"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->From = "*****@*****.**"; $mail->FromName = "Robot ALMARTCON"; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 10; // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n <html>\n <body>\n <font size=\"3\"><b>EDI-CODECO</b></font>\n <hr>\n <p>\n A quien corresponda : <br>\n <br>\n El sistema Web ({$dominio}) ha detectado en automático nuevas entradas y salidas mismas que fueron codificadas en formato\n EDI-CODECO para reconocimiento informático de otros sistemas navieros.\n <br>\n <b>Naviera :</b> {$naviera} <br>\n <b>Archivo GateIN :</b> {$fileINOnlyName} <br>\n <b>Archivo GateOUT:</b> {$fileOUTOnlyName} <br>\n <br>\n <i>\n Att. {$att} <br>\n </i>\n <p>\n <hr>\n <font color=\"red\" size=\"2\">\n <i>Este es un correo de envio automático generado por nuestro sistema {$dominio}, por favor no responda este email.<br></i>\n </font>\n <br>\n <br>\n <br>\n </body>\n </html>\n\n "; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\n =====================================================================\n "; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ // TO : Luis Felipe Pineda Mendoza <*****@*****.**> $mail->AddAddress("*****@*****.**"); //$mail->AddCC( "*****@*****.**" ); //$mail->AddCC( "*****@*****.**" ); // Subject : $mail->Subject = "[EDI-CODECO] {$naviera} "; //Incluir Attach. $mail->AddAttachment($fileIN, $fileINOnlyName); $mail->AddAttachment($fileOUT, $fileOUTOnlyName); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true //if( is_array($arrEdiFile) ){ $exito = $mail->Send(); /* // PARA INTAR REENVIARLO //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos=1; while ((!$exito) && ($intentos < 5)) { sleep(5); $exito = $mail->Send(); $intentos=$intentos+1; } */ if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] " . $mail->ErrorInfo . "<br>"; } else { echo "[ <font color=green><b>OK, E-Mail enviado.</b></font> ] <br>"; } if (file_exists($fileIN)) { unlink($fileIN); } if (file_exists($fileOUT)) { unlink($fileOUT); } }
$send_mail->Subject = EMAIL_COUNTRIES_CVS . strftime(DATE_FORMAT_LONG); if ($mail_send_to['admin_gender'] == 'm') { $body = EMAIL_GREET_MR . $mail_send_to['admin_lastname'] . ',' . "\n\n"; } else { $body = EMAIL_GREET_MS . $mail_send_to['admin_lastname'] . ',' . "\n\n"; } $body .= EMAIL_CVS_INTRO . ' ' . strftime(DATE_FORMAT_LONG) . "\n\n"; $body .= EMAIL_FTP_INFO . "\n"; $body .= ' ' . $db_table_file . "\n\n"; $body .= EMAIL_FOOT; $send_mail->Body = $body; $send_mail->AddAddress($mail_send_to['admin_email_address'], $mail_send_to['admin_firstname'] . ' ' . $mail_send_to['admin_lastname']); $send_mail->AddAttachment(OWP_CSV_TEMP . $db_table_file); $send_mail->Send(); // Clear all addresses and attachments for next loop $send_mail->ClearAddresses(); $send_mail->ClearAttachments(); $messageStack->add_session(sprintf(SUCCESS_CVS_COUNTRIES_SENT, $mail_send_to['admin_email_address']), 'notice'); } // download if (CVS_DOWNLOAD == 'true') { $fp = fopen(OWP_CSV_TEMP . $db_table_file, 'r'); $buffer = fread($fp, filesize(OWP_CSV_TEMP . $db_table_file)); fclose($fp); if (CVS_DELETE_FILE == 'true' && CVS_SEND_MAIL == 'false') { @unlink(OWP_CSV_TEMP . $db_table_file); } header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="' . $db_table_file . '"'); header('Expires: 0'); header('Pragma: no-cache');
private function sendStateMsg() { if (!empty($this->obj)) { if ($this->change_state && ($state = ormObjects::get($this->obj->state)) && $state->info) { page::assign('order.id', $this->obj->id); page::assign('order.number', $this->getNumber()); page::assign('order.cost', $this->getTotalCost()); // Информация о доставке page::assign('order.delivery', $this->obj->_delivery); page::assign('order.delivery_price', $this->getDeliveryPrice()); page::assign('order.name', $this->obj->delivery_name); page::assign('order.surname', $this->obj->delivery_surname); page::assign('order.phone', $this->obj->delivery_phone); page::assign('order.address', $this->obj->delivery_address); page::assign('username', user::get('surname') . ' ' . user::get('name')); page::assign('goods_list', page::macros('eshop')->goodsList($this->obj->id, 'goods_list_email')); $text = str_replace(array('{', '}'), '%', $state->email_msg); $title = str_replace(array('{', '}'), '%', $state->email_title); $mail = new phpmailer(); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->From = domains::curDomain()->getEmail(); $mail->FromName = domains::curDomain()->getSiteName(); $mail->Subject = page::parse($title); $mail->Body = page::parse($text); // Отправляем письмо пользователю $mail->AddAddress($this->obj->email); $mail->Send(); // Отправляем письмо администратору if ($state->id == reg::getKey('/eshop/fisrt_state') && reg::getKey('/eshop/dubl_to_email')) { $mail->ClearAddresses(); $mail->AddAddress(domains::curDomain()->getEmail()); $mail->Send(); } } } }
/** * Set up and send an email * * The array argument is searched for the following indices: * key The key of any mail template to be used * section The module to initialize for (mandatory when key is set) * sender The sender name * from The sender e-mail address * to The recipient e-mail address(es), comma separated * reply The reply-to e-mail address * cc The carbon copy e-mail address(es), comma separated * bcc The blind carbon copy e-mail address(es), comma separated * subject The message subject * message The plain text message body * message_html The HTML message body * html If this evaluates to true, turns on HTML mode * attachments An array of file paths to attach. The array keys may * be used for the paths, and the values for the name. * If the keys are numeric, the values are regarded as paths. * inline An array of inline (image) file paths to attach. * If this is used, HTML mode is switched on automatically. * search The array of patterns to be replaced by... * replace The array of replacements for the patterns * substitution A more complex structure for replacing placeholders * and/or complete blocks, conditionally or repeatedly. * If the key index is present, the corresponding mail template is loaded * first. Other indices present (sender, from, to, subject, message, etc.) * will override the template fields. * Missing mandatory fields are filled with the * default values from the global $_CONFIG array (sender, from, to), * or some core language variables (subject, message). * A simple {@see str_replace()} is used for the search and replace * operation, and the placeholder names are quoted in the substitution, * so you cannot use regular expressions. * More complex substitutions including repeated blocks may be specified * in the substitution subarray of the $arrField parameter value. * The e-mail addresses in the To: field will be used as follows: * - Groups of addresses are separated by semicola (;) * - Single addresses are separated by comma (,) * All recipients of any single group are added to the To: field together, * Groups are processed separately. So, if your To: looks like * a@a.com,b@b.com;c@c.com,d@d.com * a total of two e-mails will be sent; one to a and b, and a second one * to c and d. * Addresses for copies (Cc:) and blind copies (Bcc:) are added to all * e-mails sent, so if your e-mail is in the Cc: or Bcc: field in the * example above, you will receive two copies. * Note: The attachment paths must comply with the requirements for * file paths as defined in the {@see File} class version 2.2.0. * @static * @param array $arrField The array of template fields * @return boolean True if the mail could be sent, * false otherwise * @author Reto Kohli <*****@*****.**> */ static function send($arrField) { global $_CONFIG; //, $_CORELANG; if (!\Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { \DBG::log("MailTemplate::send(): ERROR: Failed to load phpMailer"); return false; } $objMail = new \phpmailer(); if (!empty($_CONFIG['coreSmtpServer']) && \Env::get('ClassLoader')->loadFile(ASCMS_CORE_PATH . '/SmtpSettings.class.php')) { $arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer']); if ($arrSmtp) { $objMail->IsSMTP(); $objMail->SMTPAuth = true; $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } if (empty($arrField['lang_id'])) { $arrField['lang_id'] = FRONTEND_LANG_ID; } $section = isset($arrField['section']) ? $arrField['section'] : null; $arrTemplate = null; if (empty($arrField['key'])) { $arrTemplate = self::getEmpty(); } else { $arrTemplate = self::get($section, $arrField['key'], $arrField['lang_id']); if (empty($arrTemplate)) { \DBG::log("MailTemplate::send(): WARNING: No Template for key {$arrField['key']} (section {$section})"); return false; } } $search = isset($arrField['search']) && is_array($arrField['search']) ? $arrField['search'] : null; $replace = isset($arrField['replace']) && is_array($arrField['replace']) ? $arrField['replace'] : null; $substitution = isset($arrField['substitution']) && is_array($arrField['substitution']) ? $arrField['substitution'] : null; //echo("Substitution:<br />".nl2br(var_export($arrField['substitution'], true))."<hr />"); $strip = empty($arrField['do_not_strip_empty_placeholders']); // Replace node placeholders generated by Wysiwyg $arrTemplate['message_html'] = preg_replace('/\\[\\[NODE_([a-zA-Z_0-9]*)\\]\\]/', '{NODE_$1}', $arrTemplate['message_html']); \LinkGenerator::parseTemplate($arrTemplate['message_html'], true); foreach ($arrTemplate as $field => &$value) { if ($field == 'inline' || $field == 'attachments') { continue; } if (isset($arrField[$field])) { $value = $arrField[$field]; } if (empty($value) || is_numeric($value)) { continue; } // TODO: Fix the regex to produce proper "CR/LF" in any case. // Must handle any of CR, LF, CR/LF, and LF/CR! // preg_replace('/[\015\012]/', "\015\012", $value); if ($search) { // we need to replace raw data with HTML entities // for HTML-body of email if ($field == 'message_html') { foreach ($search as $index => $searchTerm) { $value = str_replace($searchTerm, contrexx_raw2xhtml($replace[$index]), $value); } } else { $value = str_replace($search, $replace, $value); } } if ($substitution) { $convertToHtmlEntities = false; if ($field == 'message_html') { $convertToHtmlEntities = true; } self::substitute($value, $substitution, $convertToHtmlEntities); } if ($strip) { self::clearEmptyPlaceholders($value); } } //DBG::log("MailTemplate::send(): Substituted: ".var_export($arrTemplate, true)); //echo("MailTemplate::send(): Substituted:<br /><pre>".nl2br(htmlentities(var_export($arrTemplate, true), ENT_QUOTES, CONTREXX_CHARSET))."</PRE><hr />"); //die();//return true; // Use defaults for missing mandatory fields // if (empty($arrTemplate['sender'])) // $arrTemplate['sender'] = $_CONFIG['coreAdminName']; if (empty($arrTemplate['from'])) { \DBG::log("MailTemplate::send(): INFO: Empty 'from:', falling back to config"); $arrTemplate['from'] = $_CONFIG['coreAdminEmail']; } if (empty($arrTemplate['to'])) { \DBG::log("MailTemplate::send(): INFO: Empty 'to:', falling back to config"); $arrTemplate['to'] = $_CONFIG['coreAdminEmail']; } // if (empty($arrTemplate['subject'])) // $arrTemplate['subject'] = $_CORELANG['TXT_CORE_MAILTEMPLATE_NO_SUBJECT']; // if (empty($arrTemplate['message'])) // $arrTemplate['message'] = $_CORELANG['TXT_CORE_MAILTEMPLATE_NO_MESSAGE']; $objMail->FromName = $arrTemplate['sender']; $objMail->From = $arrTemplate['from']; $objMail->Subject = $arrTemplate['subject']; $objMail->CharSet = CONTREXX_CHARSET; // $objMail->IsHTML(false); if ($arrTemplate['html']) { $objMail->IsHTML(true); $objMail->Body = $arrTemplate['message_html']; $objMail->AltBody = $arrTemplate['message']; } else { $objMail->Body = $arrTemplate['message']; } foreach (preg_split('/\\s*,\\s*/', $arrTemplate['reply'], null, PREG_SPLIT_NO_EMPTY) as $address) { $objMail->AddReplyTo($address); } // foreach (preg_split('/\s*,\s*/', $arrTemplate['to'], null, PREG_SPLIT_NO_EMPTY) as $address) { // $objMail->AddAddress($address); // } foreach (preg_split('/\\s*,\\s*/', $arrTemplate['cc'], null, PREG_SPLIT_NO_EMPTY) as $address) { $objMail->AddCC($address); } foreach (preg_split('/\\s*,\\s*/', $arrTemplate['bcc'], null, PREG_SPLIT_NO_EMPTY) as $address) { $objMail->AddBCC($address); } // Applicable to attachments stored with the MailTemplate only! $arrTemplate['attachments'] = self::attachmentsToArray($arrTemplate['attachments']); //DBG::log("MailTemplate::send(): Template Attachments: ".var_export($arrTemplate['attachments'], true)); // Now the MailTemplates' attachments index is guaranteed to // contain an array. // Add attachments from the parameter array, if any. if (isset($arrField['attachments']) && is_array($arrField['attachments'])) { foreach ($arrField['attachments'] as $path => $name) { // if (empty($path)) $path = $name; // if (empty($name)) $name = basename($path); $arrTemplate['attachments'][$path] = $name; //DBG::log("MailTemplate::send(): Added Field Attachment: $path / $name"); } } //DBG::log("MailTemplate::send(): All Attachments: ".var_export($arrTemplate['attachments'], true)); foreach ($arrTemplate['attachments'] as $path => $name) { if (is_numeric($path)) { $path = $name; } $objMail->AddAttachment(ASCMS_DOCUMENT_ROOT . '/' . $path, $name); } $arrTemplate['inline'] = self::attachmentsToArray($arrTemplate['inline']); if ($arrTemplate['inline']) { $arrTemplate['html'] = true; } foreach ($arrTemplate['inline'] as $path => $name) { if (is_numeric($path)) { $path = $name; } $objMail->AddEmbeddedImage(ASCMS_DOCUMENT_ROOT . '/' . $path, uniqid(), $name); } if (isset($arrField['inline']) && is_array($arrField['inline'])) { $arrTemplate['html'] = true; foreach ($arrField['inline'] as $path => $name) { if (is_numeric($path)) { $path = $name; } $objMail->AddEmbeddedImage(ASCMS_DOCUMENT_ROOT . '/' . $path, uniqid(), $name); } } //die("MailTemplate::send(): Attachments and inlines<br />".var_export($objMail, true)); $objMail->CharSet = CONTREXX_CHARSET; $objMail->IsHTML($arrTemplate['html']); //DBG::log("MailTemplate::send(): Sending: ".nl2br(htmlentities(var_export($objMail, true), ENT_QUOTES, CONTREXX_CHARSET))."<br />Sending...<hr />"); $result = true; foreach (preg_split('/\\s*;\\s*/', $arrTemplate['to'], null, PREG_SPLIT_NO_EMPTY) as $addresses) { $objMail->ClearAddresses(); foreach (preg_split('/\\s*[,]\\s*/', $addresses, null, PREG_SPLIT_NO_EMPTY) as $address) { $objMail->AddAddress($address); } //DBG::log("MailTemplate::send(): ".var_export($objMail, true)); // TODO: Comment for test only! $result &= $objMail->Send(); // TODO: $objMail->Send() seems to sometimes return true on localhost where // sending the mail is actually impossible. Dunno why. } return $result; }
/** * Send Recommendation * * Send an email if the input is valid. Otherwise * Show some error messages and the form again */ function _sendRecomm() { global $_ARRAYLANG, $_CONFIG, $_LANGID, $_CORELANG; if (empty($_POST['receivername'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_RECEIVER_NAME'] . ' ' . $_ARRAYLANG['TXT_IS_EMPTY'] . '<br />'; } if (empty($_POST['receivermail'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_RECEIVER_MAIL'] . ' ' . $_ARRAYLANG['TXT_IS_EMPTY'] . '<br />'; } elseif (!$this->isEmail($_POST['receivermail'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_RECEIVER_MAIL'] . ' ' . $_ARRAYLANG['TXT_IS_INVALID'] . '<br />'; } if (empty($_POST['sendername'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_SENDER_NAME'] . ' ' . $_ARRAYLANG['TXT_IS_EMPTY'] . '<br />'; } if (empty($_POST['sendermail'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_SENDER_MAIL'] . ' ' . $_ARRAYLANG['TXT_IS_EMPTY'] . '<br />'; } elseif (!$this->isEmail($_POST['sendermail'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_SENDER_MAIL'] . ' ' . $_ARRAYLANG['TXT_IS_INVALID'] . '<br />'; } if (empty($_POST['comment'])) { $this->_pageMessage .= $_ARRAYLANG['TXT_STATUS_COMMENT'] . ' ' . $_ARRAYLANG['TXT_IS_EMPTY'] . '<br />'; } $receivername = $_POST['receivername']; $receivermail = $_POST['receivermail']; $sendername = $_POST['sendername']; $sendermail = $_POST['sendermail']; $comment = $_POST['comment']; if (!empty($this->_pageMessage) || !\Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->check()) { //something's missing or wrong $this->_objTpl->setVariable('RECOM_STATUS', '<div class="text-danger">' . $this->_pageMessage . '</div>'); $this->_objTpl->setCurrentBlock('recommend_form'); $this->_objTpl->setVariable(array('RECOM_SCRIPT' => $this->getJs(), 'RECOM_RECEIVER_NAME' => stripslashes($receivername), 'RECOM_RECEIVER_MAIL' => stripslashes($receivermail), 'RECOM_SENDER_NAME' => stripslashes($sendername), 'RECOM_SENDER_MAIL' => stripslashes($sendermail), 'RECOM_COMMENT' => stripslashes($comment), 'RECOM_PREVIEW' => $this->getMessageBody($_LANGID), 'RECOM_FEMALE_SALUTATION_TEXT' => $this->getFemaleSalutation($_LANGID), 'RECOM_MALE_SALUTATION_TEXT' => $this->getMaleSalutation($_LANGID))); $this->_objTpl->setVariable(array('RECOM_TXT_RECEIVER_NAME' => $_ARRAYLANG['TXT_RECEIVERNAME_FRONTEND'], 'RECOM_TXT_RECEIVER_MAIL' => $_ARRAYLANG['TXT_RECEIVERMAIL_FRONTEND'], 'RECOM_TXT_GENDER' => $_ARRAYLANG['TXT_GENDER_FRONTEND'], 'RECOM_TXT_SENDER_NAME' => $_ARRAYLANG['TXT_SENDERNAME_FRONTEND'], 'RECOM_TXT_SENDER_MAIL' => $_ARRAYLANG['TXT_SENDERMAIL_FRONTEND'], 'RECOM_TXT_COMMENT' => $_ARRAYLANG['TXT_COMMENT_FRONTEND'], 'RECOM_TXT_PREVIEW' => $_ARRAYLANG['TXT_PREVIEW_FRONTEND'], 'RECOM_TXT_FEMALE' => $_ARRAYLANG['TXT_FEMALE_FRONTEND'], 'RECOM_TXT_MALE' => $_ARRAYLANG['TXT_MALE_FRONTEND'], 'RECOM_TEXT' => $_ARRAYLANG['TXT_INTRODUCTION'], 'TXT_RECOMMEND_SEND' => $_ARRAYLANG['TXT_RECOMMEND_SEND'], 'TXT_RECOMMEND_DELETE' => $_ARRAYLANG['TXT_RECOMMEND_DELETE'])); $this->_objTpl->setVariable(array('RECOM_TXT_CAPTCHA' => $_CORELANG['TXT_CORE_CAPTCHA'], 'RECOM_CAPTCHA_CODE' => \Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->getCode())); if ($this->_objTpl->blockExists('recommend_captcha')) { $this->_objTpl->parse('recommend_captcha'); } else { $this->_objTpl->hideBlock('recommend_captcha'); } $this->_objTpl->parseCurrentBlock('recommend_form'); $this->_objTpl->parse(); } else { //data is valid if (empty($_POST['uri'])) { $url = ASCMS_PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . ASCMS_PATH_OFFSET; } else { $url = $_POST['uri']; } if ($_POST['gender'] == 'male') { $salutation = $this->getMaleSalutation($_LANGID); } else { $salutation = $this->getFemaleSalutation($_LANGID); } $body = $this->getMessageBody($_LANGID); $body = preg_replace('/<SENDER_NAME>/', $sendername, $body); $body = preg_replace('/<SENDER_MAIL>/', $sendermail, $body); $body = preg_replace('/<RECEIVER_NAME>/', $receivername, $body); $body = preg_replace('/<RECEIVER_MAIL>/', $receivermail, $body); $body = preg_replace('/<URL>/', $url, $body); $body = preg_replace('/<COMMENT>/', $comment, $body); $body = preg_replace('/<SALUTATION>/', $salutation, $body); $subject = $this->getMessageSubject($_LANGID); $subject = preg_replace('/<SENDER_NAME>/', $sendername, $subject); $subject = preg_replace('/<SENDER_MAIL>/', $sendermail, $subject); $subject = preg_replace('/<RECEIVER_NAME>/', $receivername, $subject); $subject = preg_replace('/<RECEIVER_MAIL>/', $receivermail, $subject); $subject = preg_replace('/<URL>/', $url, $subject); $subject = preg_replace('/<COMMENT>/', $comment, $subject); $subject = preg_replace('/<SALUTATION>/', $salutation, $subject); if (@(include_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($sendermail, $sendername); $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $body; $objMail->AddAddress($receivermail); $objMail->Send(); $objMail->ClearAddresses(); $objMail->AddAddress($_CONFIG['contactFormEmail']); $objMail->Send(); } $this->_objTpl->setVariable('RECOM_STATUS', $_ARRAYLANG['TXT_SENT_OK']); $this->_objTpl->parse(); } }
function sendAviso($idNaviera, $msg, $subject) { global $db, $hoy, $mscIdUsuario; /* --------------------------------------------------------------- Esta funcion se encarga de enviar un tipo de AVISO a todos los clientes del catalogo CS_CLIENTE, pero antes debe detectar a que correos los debe enviar. --------------------------------------------------------------- */ $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. /* // EMAIL NAVIERA $sql = "select naviera,email from NAVIERA where id_naviera='$idNaviera'"; $db->query ( $sql ); while ( $db->next_record () ) { $naviera = $db->f( naviera ); $emailCad = $db->f(email); } */ $emailCad = "*****@*****.**"; // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los métodos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes //$mail->PluginDir = "includes/"; $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // Configurar la cuenta de correo. $mail->Host = "vishnu.hosting-mexico.net"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->From = "*****@*****.**"; $mail->FromName = "Robot ALMARTCON"; $mail->Timeout = 10; // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n <html>\n\n <b>ALMARTCON, S.A. de C.V. </b><br>\n <br>\n <center> \n\n </center>\n <p> \n <center><font size=4 color=blUE>* R E P O R T E S *</font></center> \n <p> \n {$msg}\n\n </body>\n </html>\n "; $mail->AltBody = "\n ALMARTCON, S.A. de C.V.\n =====================================================================\n "; // -------------------------------------------------------------- // Reconocer las cuentas de correo que tiene asignadas el cliente. // Se enviara copia de la notificación via email. // -------------------------------------------------------------- //$arrDirDestino = array_unique($arrDirDestino); // Agrupar direcciones "PARA:"; $mail->ClearAddresses(); $flgOk = 0; // ----------- // TEST NESTOR // ----------- /* if( $idNaviera==13 ){ $emailCad = "ijdiaz@maritimex.com.mx,em@clipper-solutions.com,nestor@nesoftware.net"; $subject = "[ALMARTCON, S.A. de C.V.] ** TEST ** "; } */ $emailCad = str_replace(" ", "", $emailCad); $arrDirDestino = explode(",", $emailCad); foreach ($arrDirDestino as $emailDestino) { $emailDestino = trim($emailDestino); if (!empty($emailDestino)) { $mail->AddAddress($emailDestino); $flgOk = 1; } } // Si Existe por lo menos una cuenta de destino, entonces que genere el email. if ($flgOk == 1) { // ------------- // Destinatarios // ------------- // Con copia A: $mail->AddCC("*****@*****.**"); $mail->AddBCC("*****@*****.**"); //$mail->AddBCC("*****@*****.**"); // Subject : $mail->Subject = $subject; // Incluir Attach. $mail->AddAttachment("../files/EntradasNav.xlsx", "Status-Conte.xlsx"); //$mail->AddAttachment("../files/SalidasNav.csv","Salidas.csv"); //$mail->AddAttachment("../files/InventarioNav.csv","Inventario.csv"); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true $exito = $mail->Send(); echo "[ <font color=blue><b>El Msj se envio con exito a {$naviera}!</b></font> ] <br>"; } else { echo "[ <font color=red><b>Falta Email</b></font> ] <a href=\"javascript:ventanaNueva('csNfyCatCli2.php?modo=consulta&idCliente={$idCliente}',600,400)\">{$cliente}</a> <br>"; } }
/** * Send a confirmation e-mail to the address specified in the form, * if any. * @param $id * @param unknown_type $email * @return unknown */ function sendMail($feedId, $email) { global $_CONFIG, $objDatabase, $_ARRAYLANG, $objInit; $feedId = intval($feedId); $languageId = null; // Get the user ID and entry information $objResult = $objDatabase->Execute("\n SELECT addedby, title, language\n FROM " . DBPREFIX . "module_directory_dir\n WHERE id='{$feedId}'"); if ($objResult && !$objResult->EOF) { $userId = $objResult->fields['addedby']; $feedTitle = $objResult->fields['title']; $languageId = $objResult->fields['language']; } // Get user data if (is_numeric($userId)) { $objFWUser = new \FWUser(); if ($objFWUser->objUser->getUser($userId)) { $userMail = $objFWUser->objUser->getEmail(); $userFirstname = $objFWUser->objUser->getProfileAttribute('firstname'); $userLastname = $objFWUser->objUser->getProfileAttribute('lastname'); $userUsername = $objFWUser->objUser->getUsername(); } } if (!empty($email)) { $sendTo = $email; $mailId = 2; } else { // FIXED: The mail addresses may *both* be empty! // Adding the entry was sucessful, however. So we can probably assume // that it was a success anyway? // Added: if (empty($userMail)) { return true; } // ...and a boolean return value below. $sendTo = $userMail; $mailId = 1; } //get mail content n title $objResult = $objDatabase->Execute("\n SELECT title, content\n FROM " . DBPREFIX . "module_directory_mail\n WHERE id='{$mailId}'"); if ($objResult && !$objResult->EOF) { $subject = $objResult->fields['title']; $message = $objResult->fields['content']; } if ($objInit->mode == 'frontend') { $link = "http://" . $_CONFIG['domainUrl'] . CONTREXX_SCRIPT_PATH . "?section=Directory&cmd=detail&id=" . $feedId; } else { $link = "http://" . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . '/' . \FWLanguage::getLanguageParameter($languageId, 'lang') . '/' . CONTREXX_DIRECTORY_INDEX . "?section=Directory&cmd=detail&id=" . $feedId; } // replace placeholders $array_1 = array('[[USERNAME]]', '[[FIRSTNAME]]', '[[LASTNAME]]', '[[TITLE]]', '[[LINK]]', '[[URL]]', '[[DATE]]'); $array_2 = array($userUsername, $userFirstname, $userLastname, $feedTitle, $link, $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET, date(ASCMS_DATE_FORMAT)); $subject = str_replace($array_1, $array_2, $subject); $message = str_replace($array_1, $array_2, $message); $sendTo = explode(';', $sendTo); if (@\Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && @\Env::get('ClassLoader')->loadFile(ASCMS_CORE_PATH . '/SmtpSettings.class.php')) { $arrSmtp = SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer']); if ($arrSmtp !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->From = $_CONFIG['coreAdminEmail']; $objMail->FromName = $_CONFIG['coreAdminName']; $objMail->AddReplyTo($_CONFIG['coreAdminEmail']); $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $message; foreach ($sendTo as $mailAdress) { $objMail->ClearAddresses(); $objMail->AddAddress($mailAdress); $objMail->Send(); } } return true; }
function sendMail() { //$razonSocial = "Lition Logistics, S.A. de C.V."; $dominio = "www.litionlogistics.com/"; $att = "Robot"; // $fileINOnlyName = str_replace("../ediCodeco/","",$fileIN); // $fileOUTOnlyName = str_replace("../ediCodeco/","",$fileOUT); // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los métodos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // Configurar la cuenta de correo. $mail->Host = "vishnu.hosting-mexico.net"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->From = "*****@*****.**"; //$mail->Username = "******"; //$mail->Password = "******"; //$mail->From = "*****@*****.**"; $mail->FromName = "Robot Lition Logistics"; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 10; // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\r\n <html>\r\n <body>\r\n <font size=\"3\"><b>TEST EMAIL</b></font>\r\n <hr>\r\n <p>\r\n A quien corresponda : <br>\r\n <br>\r\n ++++++++ TEST / PRUEBA +++++++++\r\n <br>\r\n <i>\r\n Att. {$att} <br>\r\n </i>\r\n <p>\r\n <hr>\r\n <font color=\"red\" size=\"2\">\r\n <i>Este es un correo de envio automático generado por nuestro sistema {$dominio}, por favor no responda este email.<br></i>\r\n </font>\r\n <br>\r\n <br>\r\n <br>\r\n </body>\r\n </html>\r\n\r\n "; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\r\n =====================================================================\r\n "; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ // TO : $mail->AddAddress("*****@*****.**"); // $mail->AddAddress ( "*****@*****.**" ); // $mail->AddCC( "*****@*****.**" ); // $mail->AddCC( "*****@*****.**" ); // BCC : //$mail->AddBCC("*****@*****.**"); // Subject : $mail->Subject = "[EDI-CODECO][*Test] Naviera : {$naviera} "; //Incluir Attach. //$mail->AddAttachment($fileEDI,$fileName); //$mail->AddAttachment($fileEDI,$fileName); //$mail->AddAttachment($fileIN,$fileINOnlyName); //$mail->AddAttachment($fileOUT,$fileOUTOnlyName); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true //if( is_array($arrEdiFile) ){ $exito = $mail->Send(); /* // PARA INTAR REENVIARLO //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos=1; while ((!$exito) && ($intentos < 5)) { sleep(5); $exito = $mail->Send(); $intentos=$intentos+1; } */ if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] " . $mail->ErrorInfo . "<br>"; } else { echo "[ <font color=green><b>OK, E-Mail enviado.</b></font> ] <br>"; } // --------------------------------------------------------- // ELIMINAR los archivos CSV una vez enviados. // Nota : Ya no se eliminan por que primero se notifica via email // y luego se transmite por FTP y ese proceso lo eliminará // --------------------------------------------------------- // unlink("$fileIN"); // unlink("$fileOUT"); // }
function sendMail($entryId) { global $objDatabase, $_ARRAYLANG, $_CORELANG, $_CONFIG; //entrydata $objResult = $objDatabase->Execute("SELECT id, title, name, userid, email FROM " . DBPREFIX . "module_market WHERE id='" . contrexx_addslashes($entryId) . "' LIMIT 1"); if ($objResult !== false) { while (!$objResult->EOF) { $entryMail = $objResult->fields['email']; $entryName = $objResult->fields['name']; $entryTitle = $objResult->fields['title']; $entryUserid = $objResult->fields['userid']; $objResult->MoveNext(); } } //assesuserdata $objResult = $objDatabase->Execute("SELECT email, username FROM " . DBPREFIX . "access_users WHERE id='" . $entryUserid . "' LIMIT 1"); if ($objResult !== false) { while (!$objResult->EOF) { // TODO: Never used // $userMail = $objResult->fields['email']; $userUsername = $objResult->fields['username']; $objResult->MoveNext(); } } //get mail content n title $objResult = $objDatabase->Execute("SELECT title, content, active, mailcc FROM " . DBPREFIX . "module_market_mail WHERE id='1'"); if ($objResult !== false) { while (!$objResult->EOF) { $mailTitle = $objResult->fields['title']; $mailContent = $objResult->fields['content']; $mailCC = $objResult->fields['mailcc']; $mailOn = $objResult->fields['active']; $objResult->MoveNext(); } } if ($mailOn == 1) { $array = explode('; ', $mailCC); $url = $_SERVER['SERVER_NAME'] . ASCMS_PATH_OFFSET; $link = "http://" . $url . "/index.php?section=Market&cmd=detail&id=" . $entryId; $now = date(ASCMS_DATE_FORMAT); //replase placeholder $array_1 = array('[[EMAIL]]', '[[NAME]]', '[[TITLE]]', '[[ID]]', '[[LINK]]', '[[URL]]', '[[DATE]]', '[[USERNAME]]'); $array_2 = array($entryMail, $entryName, $entryTitle, $entryId, $link, $url, $now, $userUsername); for ($x = 0; $x < 8; $x++) { $mailTitle = str_replace($array_1[$x], $array_2[$x], $mailTitle); } for ($x = 0; $x < 8; $x++) { $mailContent = str_replace($array_1[$x], $array_2[$x], $mailContent); } //create mail $to = $entryMail; $fromName = $_CONFIG['coreAdminName'] . " - " . $url; $fromMail = $_CONFIG['coreAdminEmail']; $subject = $mailTitle; $message = $mailContent; if (\Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($fromMail, $fromName); $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $message; $objMail->AddAddress($to); $objMail->Send(); $objMail->ClearAddresses(); foreach ($array as $toCC) { // Email message if (!empty($toCC)) { $objMail->AddAddress($toCC); $objMail->Send(); $objMail->ClearAddresses(); } } } } }
function sendMassMail($subject, $body, $cname, $emailto) { global $smtp_host, $smtp_port, $admin_name, $admin_email; include_once "include/phpmailer/class.phpmailer.php"; $mail = new phpmailer(); $mail->CharSet = "utf-8"; $mail->IsHTML(true); $mail->Host = $smtp_host; $mail->Port = $smtp_port; $mail->Mailer = "smtp"; $mail->From = $admin_email; $mail->FromName = $admin_name; $mail->Subject = $subject; $mail->Body = "<html><body>" . stripcslashes($body) . "</body></html>"; $mail->AddAddress($emailto, $cname); $result = $mail->Send(); // Clear all addresses and attachments for next loop $mail->ClearAddresses(); return $result; }
/** * This functions performs the email notifications * * @return boolean */ protected function notifyByEmail() { $userlist = array(); // find all the users with this server listed $users = $this->db->select(SM_DB_PREFIX . 'users', 'FIND_IN_SET(\'' . $this->server['server_id'] . '\', `server_id`) AND `email` != \'\'', array('user_id', 'name', 'email')); if (empty($users)) { return false; } // build mail object with some default values $mail = new phpmailer(); $mail->From = sm_get_conf('email_from_email'); $mail->FromName = sm_get_conf('email_from_name'); $mail->Subject = sm_parse_msg($this->status_new, 'email_subject', $this->server); $mail->Priority = 1; $body = sm_parse_msg($this->status_new, 'email_body', $this->server); $mail->Body = $body; $mail->AltBody = str_replace('<br/>', "\n", $body); // go through empl foreach ($users as $user) { // we sent a seperate email to every single user. $userlist[] = $user['user_id']; $mail->AddAddress($user['email'], $user['name']); $mail->Send(); $mail->ClearAddresses(); } if (sm_get_conf('log_email')) { // save to log sm_add_log($this->server['server_id'], 'email', $body, implode(',', $userlist)); } }
function sendReportEmail($idUsr) { global $hoy; $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los métodos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // ++ EXCHANGE MSC ++ $mail->Host = "10.110.0.12"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->From = "*****@*****.**"; $mail->FromName = "Robot.SION"; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 30; $email = getValueTable("Email", "USUARIO", "Id_usuario", $idUsr); $ejecutivo = getValueTable("Nombre", "USUARIO", "Id_usuario", $idUsr); if (!empty($email)) { // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n\t\t\t\t<html>\t\t\t\t\t\t\t\t\n\t\t\t\t<body>\t\t\t\t\n\t\t\t\t<b>MEDITERRANEAN SHIPPING COMPANY MEXICO S.A. DE C.V.<BR>\n\t\t\t\tSolo como Agentes / As Agents only</b>\n\t\t\t\t<hr>\t\t\t\t\n\t\t\t\t<b>DEMORAS</b>\n\t\t\t\t<p>\n\t\t\t\t\n\t\t\t\t<center>\t\t\t\t\n\t\t\t\t<b><u>POSIBLES CONTENEDORES EN ABANDONO</u></b>\n\t\t\t\t</center>\n\t\t\t\t<p>\t\t\t\t\t\t\t\t\n\t\t\t\t<b>{$ejecutivo} :</b>\n\t\t\t\t<p>\t\t\t\t\n\t\t\t\tEl sistema ha detectado algunos clientes que tienen contenedores con mas de 15 días incurriendo en demoras,\n\t\t\t\tfavor de revisar a la brevedad. Adjunto archivo.\n\t\t\t\t<p>\t\t\t\n\t\t\t\tNOTA : El archivo tiene formato CSV, pero se puede abrir con MS-Excel sin problema.\n\t\t\t\t<p>\n\t\t\t\tAtt. Robot SION.\n\t\t\t\t<p>\t\t\t\t\n\t\t\t\t<hr>\n\t\t\t\t<font color=red><b>\n\t\t\t\t* FAVOR DE NO RESPONDER A ESTA DIRECCIÓN DE CORREO YA QUE NO SE RECIBIRA SU MENSAJE Y POR CONSIGUIENTE NO SERA ATENDIDO.\n\t\t\t\t</b>\n\t\t\t\t</font>\t\t\t\t\n\t\t\t\t<p>\t\t\t\t\t\t\t\t\n\t\t\t"; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\nMEDITERRANEAN SHIPPING COMPANY MÉXICO\nMSC México (As Agents Only-Solo como Agentes)\n=====================================================================\n\nYour are a Winner !!!\n\n{$ejecutivo} :\n\nEl sistema ha detectado algunos clientes que tienen contenedores con mas de 15 días incurriendo en demoras,\nfavor de revisar a la brevedad. Adjunto archivo.\nHasta luego.\nAtt. Robot SION.\n* FAVOR DE NO RESPONDER A ESTA DIRECCIÓN DE CORREO YA QUE NO SE RECIBIRA SU MENSAJE Y POR CONSIGUIENTE NO SERA ATENDIDO.\n"; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ $mail->AddAddress("{$email}"); $mail->AddCC("*****@*****.**"); $mail->AddCC("*****@*****.**"); $mail->Subject = "[SION] Pos.Abandono / {$ejecutivo} "; // Incluir Attach. $mail->AddAttachment("../files/demPosAba_{$idUsr}.zip", "demPosAba_{$idUsr}.zip"); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true $exito = $mail->Send(); //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos = 1; while (!$exito && $intentos < 5) { sleep(5); $exito = $mail->Send(); $intentos = $intentos + 1; } if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] <b><a href=\"javascript:ventanaNueva('csNfyCatCli2.php?modo=consulta&idCliente={$idCli}',600,400)\">{$cliente}</a></b> -> <i>{$emailDestino}</i> -> {$valor}" . $mail->ErrorInfo . "<br>"; } else { // echo "[ <font color=green><b>Enviado</b></font> ] <b><a href=\"javascript:ventanaNueva('csNfyCatCli2.php?modo=consulta&idCliente=$idCli',600,400)\">$cliente</a></b> -> <i>$emailDestino</i> <br>"; } } }
function sendMail($vessel, $voyage, $email) { global $hoy, $sionSrv, $sionDB; $db = new DB_Sql(); $db->connect($sionDB, $sionSrv, "root", ""); $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los m�todos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // ++ EXCHANGE MSC ++ $userName = '******'; $linkPass = '******'; $mail->IsSMTP(); $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Host = 'mail.mscgva.ch'; // IP 193.138.73.142 $mail->Username = $userName; $mail->Password = $linkPass; $mail->Port = 25; $mail->From = '*****@*****.**'; $mail->FromName = 'Robot.SION'; $mail->Timeout = 10; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 10; // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n <html>\n <body>\n <center>\n <table border=0 cellpadding=2 cellspacing=1>\n <tr>\n <td width=\"60\" height=\"40\" valign=top align=right><img src=\"http://148.245.13.34/nestor/images/logoMscGoldSmall.gif\" ></td>\n <td valign=top align=center>\n <font size=\"4\"><b>Mediterranean Shipping Company México S.A. de C.V.</b></font><br>\n <font size=\"2\">Sólo como agentes / As agents only</font>\n </td>\n </tr>\n <tr>\n <td colspan=2><hr></td>\n </tr>\n </table>\n <font size=\"4\"><b>NOTIFICACION - BUQUE CARGADO {$vessel} - {$voyage}</font>\n </center>\n <p>\n\n Estimado\n <p>\n El proceso de cargar buques ha terminado.\n <p>\n <i>\n Att. Robot SION.<br>\n </i>\n <p>\n <hr>\n <font color=\"red\" size=\"2\">\n <i>Este es un correo de envio automático por nuestro sistema SION, por favor no responda este email.</i>\n </font>\n <br>\n <br>\n <br>\n\n </body>\n </html>\n\n "; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\n MEDITERRANEAN SHIPPING COMPANY M�XICO\n MSC M�xico (As Agents Only-Solo como Agentes)\n =====================================================================\n "; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ /* $arrDirDestino[] ="*****@*****.**"; foreach ( $arrDirDestino as $emailDestino ) { if (! empty ( $emailDestino )) { $mail->AddAddress ( $emailDestino ); $emailDesTxt .= "$emailDestino,"; } } */ $mail->AddAddress("{$email}"); $mail->Subject = "[SRDO] Vessel Extract Finished / {$vessel} {$voyage}"; // Incluir Attach. //$mail->AddAttachment("../files/demo.txt","demo.txt"); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true $exito = $mail->Send(); // PARA INTAR REENVIARLO //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos = 1; while (!$exito && $intentos < 5) { sleep(5); $exito = $mail->Send(); $intentos = $intentos + 1; } if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] {$emailDestino} -> {$valor}" . $mail->ErrorInfo . "<br>\n"; } else { echo "[ <font color=green><b>Enviado</b></font> ] <br>"; } }
function sendMail() { global $_ARRAYLANG, $_CONFIG; if (\Env::get('ClassLoader')->loadFile(\Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseLibraryPath() . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && \Env::get('ClassLoader')->loadFile(\Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseCorePath() . '/SmtpSettings.class.php')) { $arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer']); if ($arrSmtp !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($_CONFIG['coreAdminEmail'], $_CONFIG['coreGlobalPageTitle']); $objMail->Subject = $this->strTitle; $objMail->IsHTML(false); $objMail->Body = $this->strTemplate; foreach ($this->arrRecipients as $key => $strMailAdress) { if (!empty($strMailAdress)) { $objMail->AddAddress($strMailAdress); $objMail->Send(); $objMail->ClearAddresses(); } } } }
/** * Initialize the mail functionality to the recipient * * @param \Cx\Modules\Calendar\Controller\CalendarEvent $event Event instance * @param integer $actionId Mail action id * @param integer $regId Registration id * @param string $mailTemplate Mail template id */ function sendMail(CalendarEvent $event, $actionId, $regId = null, $mailTemplate = null) { global $objDatabase, $_ARRAYLANG, $_CONFIG; $this->mailList = array(); // Loads the mail template which needs for this action $this->loadMailList($actionId, $mailTemplate); if (!empty($this->mailList)) { $objRegistration = null; if (!empty($regId)) { $objRegistration = new \Cx\Modules\Calendar\Controller\CalendarRegistration($event->registrationForm, $regId); list($registrationDataText, $registrationDataHtml) = $this->getRegistrationData($objRegistration); $query = 'SELECT `v`.`value`, `n`.`default`, `f`.`type` FROM ' . DBPREFIX . 'module_' . $this->moduleTablePrefix . '_registration_form_field_value AS `v` INNER JOIN ' . DBPREFIX . 'module_' . $this->moduleTablePrefix . '_registration_form_field_name AS `n` ON `v`.`field_id` = `n`.`field_id` INNER JOIN ' . DBPREFIX . 'module_' . $this->moduleTablePrefix . '_registration_form_field AS `f` ON `v`.`field_id` = `f`.`id` WHERE `v`.`reg_id` = ' . $regId . ' AND ( `f`.`type` = "salutation" OR `f`.`type` = "firstname" OR `f`.`type` = "lastname" OR `f`.`type` = "mail" )'; $objResult = $objDatabase->Execute($query); $arrDefaults = array(); $arrValues = array(); if ($objResult !== false) { while (!$objResult->EOF) { if (!empty($objResult->fields['default'])) { $arrDefaults[$objResult->fields['type']] = explode(',', $objResult->fields['default']); } $arrValues[$objResult->fields['type']] = $objResult->fields['value']; $objResult->MoveNext(); } } $regSalutation = !empty($arrValues['salutation']) ? $arrDefaults['salutation'][$arrValues['salutation'] - 1] : ''; $regFirstname = !empty($arrValues['firstname']) ? $arrValues['firstname'] : ''; $regLastname = !empty($arrValues['lastname']) ? $arrValues['lastname'] : ''; $regMail = !empty($arrValues['mail']) ? $arrValues['mail'] : ''; $regType = $objRegistration->type == 1 ? $_ARRAYLANG['TXT_CALENDAR_REG_REGISTRATION'] : $_ARRAYLANG['TXT_CALENDAR_REG_SIGNOFF']; $regSearch = array('[[REGISTRATION_TYPE]]', '[[REGISTRATION_SALUTATION]]', '[[REGISTRATION_FIRSTNAME]]', '[[REGISTRATION_LASTNAME]]', '[[REGISTRATION_EMAIL]]'); $regReplace = array($regType, $regSalutation, $regFirstname, $regLastname, $regMail); } $domain = ASCMS_PROTOCOL . "://" . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . "/"; $date = $this->format2userDateTime(new \DateTime()); $startDate = $event->startDate; $endDate = $event->endDate; $eventTitle = $event->title; $eventStart = $event->all_day ? $this->format2userDate($startDate) : $this->formatDateTime2user($startDate, $this->getDateFormat() . ' (H:i:s)'); $eventEnd = $event->all_day ? $this->format2userDate($endDate) : $this->formatDateTime2user($endDate, $this->getDateFormat() . ' (H:i:s)'); $placeholder = array('[[TITLE]]', '[[START_DATE]]', '[[END_DATE]]', '[[LINK_EVENT]]', '[[LINK_REGISTRATION]]', '[[USERNAME]]', '[[FIRSTNAME]]', '[[LASTNAME]]', '[[URL]]', '[[DATE]]'); $recipients = $this->getSendMailRecipients($actionId, $event, $regId, $objRegistration); $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0) { $arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer']); if ($arrSmtp !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($_CONFIG['coreAdminEmail'], $_CONFIG['coreGlobalPageTitle']); foreach ($recipients as $mailAdress => $langId) { if (!empty($mailAdress)) { $langId = $this->getSendMailLangId($actionId, $mailAdress, $langId); if ($objUser = \FWUser::getFWUserObject()->objUser->getUsers($filter = array('email' => $mailAdress, 'is_active' => true))) { $userNick = $objUser->getUsername(); $userFirstname = $objUser->getProfileAttribute('firstname'); $userLastname = $objUser->getProfileAttribute('lastname'); } else { $userNick = $mailAdress; if (!empty($regId) && $mailAdress == $regMail) { $userFirstname = $regFirstname; $userLastname = $regLastname; } else { $userFirstname = ''; $userLastname = ''; } } $mailTitle = $this->mailList[$langId]['mail']->title; $mailContentText = !empty($this->mailList[$langId]['mail']->content_text) ? $this->mailList[$langId]['mail']->content_text : strip_tags($this->mailList[$langId]['mail']->content_html); $mailContentHtml = !empty($this->mailList[$langId]['mail']->content_html) ? $this->mailList[$langId]['mail']->content_html : $this->mailList[$langId]['mail']->content_text; // actual language of selected e-mail template $contentLanguage = $this->mailList[$langId]['lang_id']; if ($actionId == self::MAIL_NOTFY_NEW_APP && $event->arrSettings['confirmFrontendEvents'] == 1) { $eventLink = $domain . "/cadmin/index.php?cmd={$this->moduleName}&act=modify_event&id={$event->id}&confirm=1"; } else { $eventLink = \Cx\Core\Routing\Url::fromModuleAndCmd($this->moduleName, 'detail', $contentLanguage, array('id' => $event->id, 'date' => $event->startDate->getTimestamp()))->toString(); } $regLink = \Cx\Core\Routing\Url::fromModuleAndCmd($this->moduleName, 'register', $contentLanguage, array('id' => $event->id, 'date' => $event->startDate->getTimestamp()))->toString(); $replaceContent = array($eventTitle, $eventStart, $eventEnd, $eventLink, $regLink, $userNick, $userFirstname, $userLastname, $domain, $date); $mailTitle = str_replace($placeholder, $replaceContent, $mailTitle); $mailContentText = str_replace($placeholder, $replaceContent, $mailContentText); $mailContentHtml = str_replace($placeholder, $replaceContent, $mailContentHtml); if (!empty($regId)) { $mailTitle = str_replace($regSearch, $regReplace, $mailTitle); $mailContentText = str_replace($regSearch, $regReplace, $mailContentText); $mailContentHtml = str_replace($regSearch, $regReplace, $mailContentHtml); $mailContentText = str_replace('[[REGISTRATION_DATA]]', $registrationDataText, $mailContentText); $mailContentHtml = str_replace('[[REGISTRATION_DATA]]', $registrationDataHtml, $mailContentHtml); } /*echo "send to: ".$mailAdress."<br />"; echo "send title: ".$mailTitle."<br />";*/ $objMail->Subject = $mailTitle; $objMail->Body = $mailContentHtml; $objMail->AltBody = $mailContentText; $objMail->AddAddress($mailAdress); $objMail->Send(); $objMail->ClearAddresses(); } } } }
function sendMail($bl, $pod) { global $hoy; $db = new DB_Sql(); $db->connect("MscCobranza", "10.110.13.13", "root", ""); $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los métodos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // ++ EXCHANGE MSC ++ $userName = '******'; $pass = '******'; $mail->IsSMTP(); $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Host = 'mail.mscgva.ch'; // IP 193.138.73.142 $mail->Username = $userName; $mail->Password = $pass; $mail->Port = 25; $mail->From = '*****@*****.**'; $mail->FromName = 'Robot.SION'; $mail->Timeout = 10; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 10; $paisSan = getValueTable("country", "DOC_PAIS_SANCIONADO", "code", $pod); // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n <html>\n <body>\n <center>\n <table border=0 cellpadding=2 cellspacing=1>\n <tr>\n <td width=\"60\" height=\"40\" valign=top align=right><img src=\"http://148.245.13.34/nestor/images/logoMscGoldSmall.gif\" ></td>\n <td valign=top align=center>\n <font size=\"4\"><b>Mediterranean Shipping Company México S.A. de C.V.</b></font><br>\n <font size=\"2\">Sólo como agentes / As agents only</font>\n </td>\n </tr>\n <tr>\n <td colspan=2><hr></td>\n </tr>\n </table>\n <font size=\"4\"><b>NOTIFICACION - SANCTIONS COMPLIANCE<br>({$paisSan})</b><BR>{$bl}</font>\n </center>\n <p>\n\n Estimado Ejecutivo de Ventas\n <p>\n El bl de referencia tiene un destino a uno de los países sancionados.\n Por favor confirmar si el procedimiento de las políticas de conformidad ha sido realizado y firmado por el Sr. Alonso Sopeña y/o el Sr. Homely Rojas\n de lo contrario la carga no podrá ser embarcada.\n <p>\n En espera de sus urgentes comentarios.\n <br>\n Este mensaje es enviado por razones de SEGURIDAD.\n <p>\n <i>\n Att. Robot SION.<br>\n </i>\n <p>\n <hr>\n <font color=\"red\" size=\"2\">\n <i>Este es un correo de envio automático por nuestro sistema SION, por favor no responda este email.</i>\n </font>\n <br>\n <br>\n <br>\n\n </body>\n </html>\n\n "; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\n MEDITERRANEAN SHIPPING COMPANY MÉXICO\n MSC México (As Agents Only-Solo como Agentes)\n =====================================================================\n "; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ /* $arrDirDestino[] ="*****@*****.**"; foreach ( $arrDirDestino as $emailDestino ) { if (! empty ( $emailDestino )) { $mail->AddAddress ( $emailDestino ); $emailDesTxt .= "$emailDestino,"; } } */ $mail->AddCC("*****@*****.**"); // Copia Ciega $mail->AddBCC("*****@*****.**"); $mail->AddBCC("*****@*****.**"); //$mail->AddAddress("*****@*****.**"); //if(!empty($sndCC))$mail->AddCC($sndCC); // ----------------------------------------- // Subject //----------------------------------------- $sql = "select * from DOC_CTRL_EXPO "; $sql .= "where bl='{$bl}' "; $db->query($sql); while ($db->next_record()) { // ----------------------------------------- // Comprobar q no tenga la firma BL-REVISION // ----------------------------------------- $bl = $db->f(bl); $bkg = $db->f(bkg); $bkgp = $db->f(bkg_party); $executive = $db->f(bkg_executive); $exeMail1 = getValueTable("mail1", "DOC_CAT_EJE", "cod", $executive); $exeMail2 = getValueTable("mail2", "DOC_CAT_EJE", "cod", $executive); $exeMail3 = getValueTable("mail3", "DOC_CAT_EJE", "cod", $executive); if (!empty($exeMail1)) { $mail->AddAddress($exeMail1); } if (!empty($exeMail2)) { $mail->AddAddress($exeMail2); } if (!empty($exeMail3)) { $mail->AddAddress($exeMail3); } $pol = $db->f(pol); $pod = $db->f(pod); $who = $db->f(who); $idBarco = getValueTable("id_barco", "DOC_CTRL_EXPO", "id_bl", $idBl); $vessel = getValueTable("Nombre", "BARCO", "Id_barco", $idBarco); $voy = getValueTable("Viaje", "BARCO", "Id_barco", $idBarco); $eta = getValueTable("Eta1", "BARCO", "Id_barco", $idBarco); $vesVoy = "{$vessel} / {$voy} (<font color=maroon>{$idBarco}</font>)"; $puerto = getValueTable("puerto", "CS_CODIGO", "codigo", $pod); $pais = getValueTable("pais", "CS_CODIGO", "codigo", $pod); } // VERACRUZ : MXVER // ALTAMIRA : MXLMR,MXATM // PACIFICO : MXZLO,MXMZT,MXSCX,MXLZC,MXPMS,MXGYM if ($pol == "MXVER") { $mail->AddCC("*****@*****.**"); } elseif ($pol == "MXZLO" || $pol == "MXMZT" || $pol == "MXSCX" || $pol == "MXLZC" || $pol == "MXPMS" || $pol == "MXGYM") { $mail->AddCC("*****@*****.**"); } elseif ($pol == "MXLMR" || $pol == "MXATM") { $mail->AddCC("*****@*****.**"); } else { $mail->AddCC("*****@*****.**"); } $paisSan = getValueTable("country", "DOC_PAIS_SANCIONADO", "code", $pol); $txtSubj = "SANCTIONS COMPLIANCE {$paisSan} / [{$who}] / {$vessel} {$voy} / MSCU{$bl} / {$bkg} / {$bkgp} / {$pol} / {$pol} / [{$who}] %0A%0A"; $txtSubj = str_replace("&", "AND", $txtSubj); $mail->Subject = "{$txtSubj}"; // Incluir Attach. //$mail->AddAttachment("../files/demo.txt","demo.txt"); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true $exito = $mail->Send(); /* // PARA INTAR REENVIARLO //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos=1; while ((!$exito) && ($intentos < 5)) { sleep(5); $exito = $mail->Send(); $intentos=$intentos+1; } */ if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] {$emailDestino} -> {$valor}" . $mail->ErrorInfo . "<br>\n"; } else { echo "[ <font color=green><b>Enviado</b></font> ] <br>"; } }
function sendList($list) { // send email of message global $loader, $intl, $conf; $loader->import('saf.Ext.phpmailer'); $mail = new phpmailer(); $mail->IsMail(); $mail->IsHTML(true); foreach ($list as $item) { if (strtoupper($item->type) == 'TASK') { $id = 'T' . $item->id; } elseif (strtoupper($item->type) == 'MESSAGE') { $id = 'M' . $item->id; } else { $id = strtoupper(substr($item->type, 0, 1)) . $item->id; } $mail->From = $conf['Messaging']['return_address']; //$mail->Subject = '[' . $this->id . '] ' . $this->subject; //$mail->Body = $this->body; $mail->AddAddress($item->address); if (defined('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_SUBJECT')) { $mail->Subject = $intl->get(constant('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_SUBJECT'), $item->struct); } else { $mail->Subject = '[' . $id . '] ' . $item->subject; } if (defined('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_BODY')) { $mail->Body = $intl->get(constant('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_BODY'), $item->struct); } else { $mail->Body = $item->body; } if ($item->priority == 'urgent' || $item->priority == 'high') { $mail->Priority = 1; } else { $mail->Priority = 3; } if (!$mail->Send()) { $this->error = $mail->ErrorInfo; return false; } $mail->ClearAddresses(); $mail->ClearAttachments(); } return true; }
$mail = new phpmailer(); $mail->From = $_POST['sender_email']; $mail->FromName = $_POST['sender_email']; $mail->Mailer = "smtp"; $mail->Host = $smtp_mailhost; $mail->SMTPAuth = true; $mail->Username = $smtp_user; $mail->Password = $smtp_pw; $mail->Subject = "EMail vom " . $shopconfig['shopconfig_pagetitle'] . " Gästebuch"; $body = "Hallo " . $_POST['myname'] . ",\nvielen Dank für den Eintrag in unserem Gästebuch,\nName: " . $_POST['myname'] . "\nDatum: " . $datum . "\nEmail: " . $_POST['myemail'] . "\nHomepage: " . $_POST['myhp'] . "\nKommentar: " . $_POST['mymassage'] . "\nText: " . $_POST['text'] . "\n\nDas {$pagename} |" . $mandant['name'] . " Team"; $mail->Body = $body; $mail->AltBody = $body; $mail->AddAddress($_POST['myemail'], $_POST['myname']); $mail->AddCC($mandant['mandant_email'], $mandant['mandant_vorname'] . " " . $mandant['mandant_nachname']); @$mail->Send(); $mail->ClearAddresses(); $mail->ClearAttachments(); } else { print $fehler; if ($fehler == 1) { $smarty->assign("fehler", 1); } if ($fehler == 2) { $smarty->assign("fehler", $fehler); } $_GET['neu'] = 1; $smarty->assign("myname", $_POST['myname']); $smarty->assign("mymassage", $_POST['mymassage']); $smarty->assign("myemail", $_POST['myemail']); $smarty->assign("myhp", $_POST['myhp']); $smarty->assign("myicq", $_POST['myicq']);
/** * Send the email * @param int $UserID * @param int $NewsletterID * @param string $TargetEmail * @param string $type */ function SendEmail($UserID, $NewsletterID, $TargetEmail, $TmpEntry, $type = self::USER_TYPE_NEWSLETTER) { global $objDatabase, $_ARRAYLANG, $_DBCONFIG; require_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php'; $newsletterValues = $this->getNewsletterValues($NewsletterID); if ($newsletterValues !== false) { $subject = $newsletterValues['subject']; $template = $newsletterValues['template']; $content = $newsletterValues['content']; $priority = $newsletterValues['priority']; $sender_email = $newsletterValues['sender_email']; $sender_name = $newsletterValues['sender_name']; $return_path = $newsletterValues['return_path']; $count = $newsletterValues['count']; $smtpAccount = $newsletterValues['smtp_server']; } $break = $this->getSetting('txt_break_after'); $break = intval($break) == 0 ? 80 : $break; $HTML_TemplateSource = $this->GetTemplateSource($template, 'html'); // TODO: Unused // $TEXT_TemplateSource = $this->GetTemplateSource($template, 'text'); $newsletterUserData = $this->getNewsletterUserData($UserID, $type); $testDelivery = !$TmpEntry; $NewsletterBody_HTML = $this->ParseNewsletter($subject, $content, $HTML_TemplateSource, '', $TargetEmail, $newsletterUserData, $NewsletterID, $testDelivery); \LinkGenerator::parseTemplate($NewsletterBody_HTML, true); $NewsletterBody_TEXT = $this->ParseNewsletter('', '', '', 'text', '', $newsletterUserData, $NewsletterID, $testDelivery); \LinkGenerator::parseTemplate($NewsletterBody_TEXT, true); $mail = new \phpmailer(); if ($smtpAccount > 0) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($smtpAccount)) !== false) { $mail->IsSMTP(); $mail->Host = $arrSmtp['hostname']; $mail->Port = $arrSmtp['port']; $mail->SMTPAuth = $arrSmtp['username'] == '-' ? false : true; $mail->Username = $arrSmtp['username']; $mail->Password = $arrSmtp['password']; } } $mail->CharSet = CONTREXX_CHARSET; $mail->AddReplyTo($return_path); $mail->SetFrom($sender_email, $sender_name); $mail->Subject = $subject; $mail->Priority = $priority; $mail->Body = $NewsletterBody_HTML; $mail->AltBody = $NewsletterBody_TEXT; $queryATT = "SELECT newsletter, file_name FROM " . DBPREFIX . "module_newsletter_attachment where newsletter=" . $NewsletterID . ""; $objResultATT = $objDatabase->Execute($queryATT); if ($objResultATT !== false) { while (!$objResultATT->EOF) { $mail->AddAttachment(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesAttachPath() . "/" . $objResultATT->fields['file_name'], $objResultATT->fields['file_name']); $objResultATT->MoveNext(); } } $mail->AddAddress($TargetEmail); if ($UserID) { // mark recipient as in-action to prevent multiple tries of sending the newsletter to the same recipient $query = "UPDATE " . DBPREFIX . "module_newsletter_tmp_sending SET sendt=2 where email='" . $TargetEmail . "' AND newsletter=" . $NewsletterID . " AND sendt=0"; if ($objDatabase->Execute($query) === false || $objDatabase->Affected_Rows() == 0) { return $count; } } if ($mail->Send()) { // && $UserID == 0) { $ReturnVar = $count++; if ($TmpEntry == 1) { // Insert TMP-ENTRY Sended Email & Count++ $query = "UPDATE " . DBPREFIX . "module_newsletter_tmp_sending SET sendt=1 where email='" . $TargetEmail . "' AND newsletter=" . $NewsletterID . ""; if ($objDatabase->Execute($query) === false) { if ($_DBCONFIG['dbType'] == 'mysql' && $objDatabase->ErrorNo() == 2006) { @$objDatabase->Connect($_DBCONFIG['host'], $_DBCONFIG['user'], $_DBCONFIG['password'], $_DBCONFIG['database'], true); if ($objDatabase->Execute($query) === false) { return false; } } } $objDatabase->Execute("\n UPDATE " . DBPREFIX . "module_newsletter\n SET count=count+1\n WHERE id={$NewsletterID}"); $queryCheck = "SELECT 1 FROM " . DBPREFIX . "module_newsletter_tmp_sending where newsletter=" . $NewsletterID . " and sendt=0"; $objResultCheck = $objDatabase->SelectLimit($queryCheck, 1); if ($objResultCheck->RecordCount() == 0) { $objDatabase->Execute("\n UPDATE " . DBPREFIX . "module_newsletter\n SET status=1\n WHERE id={$NewsletterID}"); } } /*elseif ($mail->error_count) { if (strstr($mail->ErrorInfo, 'authenticate')) { self::$strErrMessage .= sprintf($_ARRAYLANG['TXT_NEWSLETTER_MAIL_AUTH_FAILED'], htmlentities($arrSmtp['name'], ENT_QUOTES, CONTREXX_CHARSET)).'<br />'; $ReturnVar = false; } } */ } else { $performRejectedMailOperation = false; if (strstr($mail->ErrorInfo, 'authenticate')) { // -> smtp error self::$strErrMessage .= sprintf($_ARRAYLANG['TXT_NEWSLETTER_MAIL_AUTH_FAILED'], htmlentities($arrSmtp['name'], ENT_QUOTES, CONTREXX_CHARSET)) . '<br />'; } elseif (strstr($mail->ErrorInfo, 'from_failed')) { // -> mail error self::$strErrMessage .= sprintf($_ARRAYLANG['TXT_NEWSLETTER_FROM_ADDR_REJECTED'], htmlentities($sender_email, ENT_QUOTES, CONTREXX_CHARSET)) . '<br />'; } elseif (strstr($mail->ErrorInfo, 'recipients_failed')) { // -> recipient error $performRejectedMailOperation = true; self::$strErrMessage .= sprintf($_ARRAYLANG['TXT_NEWSLETTER_RECIPIENT_FAILED'], htmlentities($TargetEmail, ENT_QUOTES, CONTREXX_CHARSET)) . '<br />'; } elseif (strstr($mail->ErrorInfo, 'instantiate')) { // -> php error self::$strErrMessage .= $_ARRAYLANG['TXT_NEWSLETTER_LOCAL_SMTP_FAILED'] . '<br />'; } elseif (strstr($mail->ErrorInfo, 'connect_host')) { // -> smtp error self::$strErrMessage .= $_ARRAYLANG['TXT_NEWSLETTER_CONNECT_SMTP_FAILED'] . '<br />'; } else { // -> mail error self::$strErrMessage .= $mail->ErrorInfo . '<br />'; } $ReturnVar = false; if ($TmpEntry == 1) { $arrSettings = $this->_getSettings(); if ($performRejectedMailOperation && $arrSettings['rejected_mail_operation']['setvalue'] != 'ignore') { switch ($arrSettings['rejected_mail_operation']['setvalue']) { case 'deactivate': // Remove temporary data from the module if ($objDatabase->Execute("DELETE FROM `" . DBPREFIX . "module_newsletter_tmp_sending` WHERE `email` ='" . addslashes($TargetEmail) . "'") !== false) { switch ($type) { case self::USER_TYPE_CORE: // do nothing with system users break; case self::USER_TYPE_ACCESS: // TODO: Remove newsletter subscription for access_user break; case self::USER_TYPE_NEWSLETTER: default: // Deactivate user $objDatabase->Execute("UPDATE `" . DBPREFIX . "module_newsletter_user` SET `status` = 0 WHERE `id` = " . $UserID); break; } } break; case 'delete': switch ($type) { case self::USER_TYPE_CORE: // do nothing with system users break; case self::USER_TYPE_ACCESS: // TODO: Remove newsletter subscription for access_user break; case self::USER_TYPE_NEWSLETTER: default: // Remove user data from the module $this->_deleteRecipient($UserID); break; } break; case 'inform': $this->informAdminAboutRejectedMail($NewsletterID, $UserID, $TargetEmail, $type, $newsletterUserData); break; } } $ReturnVar = $count; } } $mail->ClearAddresses(); $mail->ClearAttachments(); return $ReturnVar; }
function sendEmail($recipient_address, $recipient_name, $subject, $message) { ## The php builtin mailing functions do not work all the time so I have ## selected to use phpMailer (phpmailer.sourceforge.net/) $mail = new phpmailer(); $mail->From = $this->_adminEmail; $mail->FromName = $this->_adminName; $mail->Host = $this->_emailHosts; $mail->Mailer = "smtp"; $mail->Subject = $subject; $mail->Body = $message; $mail->AddAddress($recipient_address, $recipient_name); if (!$mail->Send()) { echo $this->_('There has been a mail error sending to ' . $recipient_address . " " . $mail->ErrorInfo . "<br />"); return false; } // Clear all addresses and attachments for next loop $mail->ClearAddresses(); $mail->ClearAttachments(); return true; }
/** * send a mail to the email with the message * * @static * @param integer $uploadId the upload id * @param string $subject the subject of the mail for the recipient * @param string $email the recipient's mail address * @param null|string $message the message for the recipient */ public static function sendMail($uploadId, $subject, $emails, $message = null) { global $objDatabase, $_CONFIG; /** * get all file ids from the last upload */ $objResult = $objDatabase->Execute("SELECT `id` FROM " . DBPREFIX . "module_filesharing WHERE `upload_id` = '" . intval($uploadId) . "'"); if ($objResult !== false && $objResult->RecordCount() > 0) { while (!$objResult->EOF) { $files[] = $objResult->fields["id"]; $objResult->MoveNext(); } } if (!is_int($uploadId) && empty($files)) { $files[] = $uploadId; } /** * init mail data. Mail template, Mailsubject and PhpMailer */ $objMail = $objDatabase->SelectLimit("SELECT `subject`, `content` FROM " . DBPREFIX . "module_filesharing_mail_template WHERE `lang_id` = " . FRONTEND_LANG_ID, 1, -1); $content = str_replace(array(']]', '[['), array('}', '{'), $objMail->fields["content"]); if (empty($subject)) { $subject = $objMail->fields["subject"]; } $cx = \Cx\Core\Core\Controller\Cx::instanciate(); if (\Env::get('ClassLoader')->loadFile($cx->getCodeBaseLibraryPath() . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); /** * Load mail template and parse it */ $objTemplate = new \Cx\Core\Html\Sigma('.'); $objTemplate->setErrorHandling(PEAR_ERROR_DIE); $objTemplate->setTemplate($content); $objTemplate->setVariable(array("DOMAIN" => $_CONFIG["domainUrl"], 'MESSAGE' => $message)); if ($objTemplate->blockExists('filesharing_file')) { foreach ($files as $file) { $objTemplate->setVariable(array('FILE_DOWNLOAD' => self::getDownloadLink($file))); $objTemplate->parse('filesharing_file'); } } if ($_CONFIG['coreSmtpServer'] > 0 && \Env::get('ClassLoader')->loadFile($cx->getCodeBaseCorePath() . '/SmtpSettings.class.php')) { if (($arrSmtp = SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($_CONFIG['coreAdminEmail'], $_CONFIG['coreGlobalPageTitle']); $objMail->Subject = $subject; $objMail->Body = $objTemplate->get(); foreach ($emails as $email) { $objMail->AddAddress($email); $objMail->Send(); $objMail->ClearAddresses(); } } }
/** * Notify subscribers about new posts per mail * @param $from Name in from field. * @param $subject Mail subject * @param $message Mail message. */ function notifySubscribers($from, $subject, $message) { global $dbi, $login; // Send mail to subscribers $to = ""; $subscribers = explode(",", $this->blog->subscribers); for ($i = 0; $i < sizeof($subscribers); $i++) { $to .= ($i != 0 ? "," : "") . "{$subscribers[$i]}"; } // Create plain text version $h2t =& new html2text($message); // Create PHPMailer object $mail = new phpmailer(); $user = new User($login->id); // Set mail values $mail->CharSet = "UTF-8"; $mail->Sender = $user->email; $mail->From = $user->email; $mail->FromName = $user->name; $mail->Subject = $subject; $mail->Body = $message; $mail->AltBody = $h2t->get_text(); // Send mail to subscribers if (sizeof($subscribers) > 0) { for ($i = 0; $i < sizeof($subscribers); $i++) { $mail->AddAddress($subscribers[$i]); $mail->Send(); // Clear all addresses for next loop $mail->ClearAddresses(); } } }
/** * Очищает все адреса получателей * */ public function ClearAddresses() { $this->oMailer->ClearAddresses(); }
/** * Sends an email with the contact details to the responsible persons * * This methode sends an email to all email addresses that are defined in the * option "Receiver address(es)" of the requested contact form. * @access private * @global array * @global array * @param array Details of the contact request * @see _getEmailAdressOfString(), phpmailer::From, phpmailer::FromName, phpmailer::AddReplyTo(), phpmailer::Subject, phpmailer::IsHTML(), phpmailer::Body, phpmailer::AddAddress(), phpmailer::Send(), phpmailer::ClearAddresses() */ private function sendMail($arrFormData) { global $_ARRAYLANG, $_CONFIG; $plaintextBody = ''; $replyAddress = ''; $firstname = ''; $lastname = ''; $senderName = ''; $isHtml = $arrFormData['htmlMail'] == 1 ? true : false; // stop send process in case no real data had been submitted if (!isset($arrFormData['data']) && !isset($arrFormData['uploadedFiles'])) { return false; } // check if we shall send the email as multipart (text/html) if ($isHtml) { // setup html mail template $objTemplate = new \Cx\Core\Html\Sigma('.'); $objTemplate->setErrorHandling(PEAR_ERROR_DIE); $objTemplate->setTemplate($arrFormData['mailTemplate']); $objTemplate->setVariable(array('DATE' => date(ASCMS_DATE_FORMAT, $arrFormData['meta']['time']), 'HOSTNAME' => contrexx_raw2xhtml($arrFormData['meta']['host']), 'IP_ADDRESS' => contrexx_raw2xhtml($arrFormData['meta']['ipaddress']), 'BROWSER_LANGUAGE' => contrexx_raw2xhtml($arrFormData['meta']['lang']), 'BROWSER_VERSION' => contrexx_raw2xhtml($arrFormData['meta']['browser']))); } // TODO: check if we have to excape $arrRecipients later in the code $arrRecipients = $this->getRecipients(intval($_GET['cmd'])); // calculate the longest field label. // this will be used to correctly align all user submitted data in the plaintext e-mail // TODO: check if the label of upload-fields are taken into account as well $maxlength = 0; foreach ($arrFormData['fields'] as $arrField) { $length = strlen($arrField['lang'][FRONTEND_LANG_ID]['name']); $maxlength = $maxlength < $length ? $length : $maxlength; } // try to fetch a user submitted e-mail address to which we will send a copy to if (!empty($arrFormData['fields'])) { foreach ($arrFormData['fields'] as $fieldId => $arrField) { // check if field validation is set to e-mail if ($arrField['check_type'] == '2') { $mail = trim($arrFormData['data'][$fieldId]); if (\FWValidator::isEmail($mail)) { $replyAddress = $mail; break; } } if ($arrField['type'] == 'special') { switch ($arrField['special_type']) { case 'access_firstname': $firstname = trim($arrFormData['data'][$fieldId]); break; case 'access_lastname': $lastname = trim($arrFormData['data'][$fieldId]); break; default: break; } } } } if ($arrFormData['useEmailOfSender'] == 1 && (!empty($firstname) || !empty($lastname))) { $senderName = trim($firstname . ' ' . $lastname); } else { $senderName = $_CONFIG['coreGlobalPageTitle']; } // a recipient mail address which has been picked by sender $chosenMailRecipient = null; // fill the html and plaintext body with the submitted form data foreach ($arrFormData['fields'] as $fieldId => $arrField) { if ($fieldId == 'unique_id') { //generated for uploader. no interesting mail content. continue; } $htmlValue = ''; $plaintextValue = ''; $textAreaKeys = array(); switch ($arrField['type']) { case 'label': case 'fieldset': // TODO: parse TH row instead // TODO: parse TH row instead case 'horizontalLine': // TODO: add visual horizontal line // we need to use a 'continue 2' here to first break out of the switch and then move over to the next iteration of the foreach loop continue 2; break; case 'file': case 'multi_file': $htmlValue = ""; $plaintextValue = ""; if (isset($arrFormData['uploadedFiles'][$fieldId])) { $htmlValue = "<ul>"; foreach ($arrFormData['uploadedFiles'][$fieldId] as $file) { $htmlValue .= "<li><a href='" . ASCMS_PROTOCOL . "://" . $_CONFIG['domainUrl'] . \Env::get('cx')->getWebsiteOffsetPath() . contrexx_raw2xhtml($file['path']) . "' >" . contrexx_raw2xhtml($file['name']) . "</a></li>"; $plaintextValue .= ASCMS_PROTOCOL . "://" . $_CONFIG['domainUrl'] . \Env::get('cx')->getWebsiteOffsetPath() . $file['path'] . "\r\n"; } $htmlValue .= "</ul>"; } break; case 'checkbox': $plaintextValue = !empty($arrFormData['data'][$fieldId]) ? $_ARRAYLANG['TXT_CONTACT_YES'] : $_ARRAYLANG['TXT_CONTACT_NO']; $htmlValue = $plaintextValue; break; case 'recipient': // TODO: check for XSS $plaintextValue = $arrRecipients[$arrFormData['data'][$fieldId]]['lang'][FRONTEND_LANG_ID]; $htmlValue = $plaintextValue; $chosenMailRecipient = $arrRecipients[$arrFormData['data'][$fieldId]]['email']; break; case 'textarea': //we need to know all textareas - they're indented differently then the rest of the other field types $textAreaKeys[] = $fieldId; default: $plaintextValue = isset($arrFormData['data'][$fieldId]) ? $arrFormData['data'][$fieldId] : ''; $htmlValue = contrexx_raw2xhtml($plaintextValue); break; } $fieldLabel = $arrField['lang'][FRONTEND_LANG_ID]['name']; // try to fetch an e-mail address from submitted form date in case we were unable to fetch one from an input type with e-mail validation if (empty($replyAddress)) { $mail = $this->_getEmailAdressOfString($plaintextValue); if (\FWValidator::isEmail($mail)) { $replyAddress = $mail; } } // parse html body if ($isHtml) { if (!empty($htmlValue)) { if ($objTemplate->blockExists('field_' . $fieldId)) { // parse field specific template block $objTemplate->setVariable(array('FIELD_' . $fieldId . '_LABEL' => contrexx_raw2xhtml($fieldLabel), 'FIELD_' . $fieldId . '_VALUE' => $htmlValue)); $objTemplate->parse('field_' . $fieldId); } elseif ($objTemplate->blockExists('form_field')) { // parse regular field template block $objTemplate->setVariable(array('FIELD_LABEL' => contrexx_raw2xhtml($fieldLabel), 'FIELD_VALUE' => $htmlValue)); $objTemplate->parse('form_field'); } } elseif ($objTemplate->blockExists('field_' . $fieldId)) { // hide field specific template block, if present $objTemplate->hideBlock('field_' . $fieldId); } } // parse plaintext body $tabCount = $maxlength - strlen($fieldLabel); $tabs = $tabCount == 0 ? 1 : $tabCount + 1; // TODO: what is this all about? - $value is undefined if ($arrFormData['fields'][$fieldId]['type'] == 'recipient') { $value = $arrRecipients[$value]['lang'][FRONTEND_LANG_ID]; } if (in_array($fieldId, $textAreaKeys)) { // we're dealing with a textarea, don't indent value $plaintextBody .= $fieldLabel . ":\n" . $plaintextValue . "\n"; } else { $plaintextBody .= $fieldLabel . str_repeat(" ", $tabs) . ": " . $plaintextValue . "\n"; } } $arrSettings = $this->getSettings(); // TODO: this is some fixed plaintext message data -> must be ported to html body $message = $_ARRAYLANG['TXT_CONTACT_TRANSFERED_DATA_FROM'] . " " . $_CONFIG['domainUrl'] . "\n\n"; if ($arrSettings['fieldMetaDate']) { $message .= $_ARRAYLANG['TXT_CONTACT_DATE'] . " " . date(ASCMS_DATE_FORMAT, $arrFormData['meta']['time']) . "\n\n"; } $message .= $plaintextBody . "\n\n"; if ($arrSettings['fieldMetaHost']) { $message .= $_ARRAYLANG['TXT_CONTACT_HOSTNAME'] . " : " . contrexx_raw2xhtml($arrFormData['meta']['host']) . "\n"; } if ($arrSettings['fieldMetaIP']) { $message .= $_ARRAYLANG['TXT_CONTACT_IP_ADDRESS'] . " : " . contrexx_raw2xhtml($arrFormData['meta']['ipaddress']) . "\n"; } if ($arrSettings['fieldMetaLang']) { $message .= $_ARRAYLANG['TXT_CONTACT_BROWSER_LANGUAGE'] . " : " . contrexx_raw2xhtml($arrFormData['meta']['lang']) . "\n"; } $message .= $_ARRAYLANG['TXT_CONTACT_BROWSER_VERSION'] . " : " . contrexx_raw2xhtml($arrFormData['meta']['browser']) . "\n"; if (@(include_once \Env::get('cx')->getCodeBaseLibraryPath() . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && @(include_once \Env::get('cx')->getCodeBaseCorePath() . '/SmtpSettings.class.php')) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->From = $_CONFIG['coreAdminEmail']; $objMail->FromName = $senderName; if (!empty($replyAddress)) { $objMail->AddReplyTo($replyAddress); if ($arrFormData['sendCopy'] == 1) { $objMail->AddAddress($replyAddress); } if ($arrFormData['useEmailOfSender'] == 1) { $objMail->From = $replyAddress; } } $objMail->Subject = $arrFormData['subject']; if ($isHtml) { $objMail->Body = $objTemplate->get(); $objMail->AltBody = $message; } else { $objMail->IsHTML(false); $objMail->Body = $message; } // attach submitted files to email if (count($arrFormData['uploadedFiles']) > 0 && $arrFormData['sendAttachment'] == 1) { foreach ($arrFormData['uploadedFiles'] as $arrFilesOfField) { foreach ($arrFilesOfField as $file) { $objMail->AddAttachment(\Env::get('cx')->getWebsiteDocumentRootPath() . $file['path'], $file['name']); } } } if ($chosenMailRecipient !== null) { if (!empty($chosenMailRecipient)) { $objMail->AddAddress($chosenMailRecipient); $objMail->Send(); $objMail->ClearAddresses(); } } else { foreach ($arrFormData['emails'] as $sendTo) { if (!empty($sendTo)) { $objMail->AddAddress($sendTo); $objMail->Send(); $objMail->ClearAddresses(); } } } } return true; }
function sendMail() { global $hoy; $mail = new phpmailer(); $mail->Priority = 0; // Se declara la prioridad del mensaje. // ------------------------------------------------ // CONFIGURAR EMAIL. // ------------------------------------------------ //Definimos las propiedades y llamamos a los m�todos //correspondientes del objeto mail //Con PluginDir le indicamos a la clase phpmailer donde se //encuentra la clase smtp que como he comentado al principio de //este ejemplo va a estar en el subdirectorio includes $mail->PluginDir = "../include/"; $mail->Mailer = "smtp"; // ++ EXCHANGE MSC ++ $userName = '******'; $linkPass = '******'; $mail->IsSMTP(); $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Host = '10.21.56.22'; // IP 193.138.73.142 $mail->Username = $userName; $mail->Password = $linkPass; $mail->Port = 25; $mail->From = '*****@*****.**'; $mail->FromName = 'Robot.SION'; $mail->Timeout = 10; //El valor por defecto 10 de Timeout es un poco escaso dado que voy a usar //una cuenta gratuita, por tanto lo pongo a 30 //$mail->Timeout=10; $mail->Timeout = 10; // -------------------- // FORMATO HTML // -------------------- $mail->Body = "\n <html>\n <body>\n <center>\n <table border=0 cellpadding=2 cellspacing=1>\n <tr>\n <td width=\"60\" height=\"40\" valign=top align=right></td>\n <td valign=top align=center>\n <font size=\"4\"><b>Mediterranean Shipping Company Mexico S.A. de C.V.</b></font><br>\n <font size=\"2\">S�lo como agentes / As agents only</font>\n </td>\n </tr>\n <tr>\n <td colspan=2><hr></td>\n </tr>\n </table>\n <font size=\"4\"><b>NOTIFICACION - CARGA DE BLS DE MSCLINK A SION</b><BR>{$bl}</font>\n </center>\n <p>\n\n Estimado \n <p>\n El proceso de cargar los Bls de MscLink a SION ha terminado.\n <p>\n <i>\n Att. Robot SION.<br>\n </i>\n <p>\n <hr>\n <font color=\"red\" size=\"2\">\n <i>Este es un correo de envio autom�tico por nuestro sistema SION, por favor no responda este email.</i>\n </font>\n <br>\n <br>\n <br>\n\n </body>\n </html>\n\n "; // ------------------------------------------------------- // FORMATO TEXTO // Definimos AltBody por si el destinatario del correo // no admite email con formato html // ------------------------------------------------------- $mail->AltBody = "\n MEDITERRANEAN SHIPPING COMPANY M�XICO\n MSC Mexico (As Agents Only-Solo como Agentes)\n =====================================================================\n "; // Nota : // La direccion PARA solo se puede manejar 1. // Las direcciones CC puede manejar N correos. // ------------- // Destinatarios // ------------- $mail->ClearAddresses(); // ------------------------------------------------ $arrDirDestino[] = "*****@*****.**"; foreach ($arrDirDestino as $emailDestino) { if (!empty($emailDestino)) { $mail->AddAddress($emailDestino); $emailDesTxt .= "{$emailDestino},"; } } $mail->AddCC("*****@*****.**"); // Copia Ciega $mail->Subject = "Finalizo el proceso Cargar-Bls de MscLink a SION"; // Incluir Attach. //$mail->AddAttachment("../files/demo.txt","demo.txt"); // Se envia el mensaje, si no ha habido problemas, la variable $exito tendra el valor true $exito = $mail->Send(); /* // PARA INTAR REENVIARLO //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho //para intentar enviar el mensaje, cada intento se hara 5 segundos despues //del anterior, para ello se usa la funcion sleep $intentos=1; while ((!$exito) && ($intentos < 5)) { sleep(5); $exito = $mail->Send(); $intentos=$intentos+1; } */ if (!$exito) { echo "[ <font color=red><b>Problema de envio</b></font> ] {$emailDestino} -> {$valor}" . $mail->ErrorInfo . "<br>\n"; } else { echo "[ <font color=green><b>Enviado</b></font> ] <br>"; } }
function emailSend($data) { $stime = array_sum(explode(' ', microtime())); require_once "getmxrr.php"; $smtp =& $this->params; $mail = new phpmailer(); $mail->Mailer = "smtp"; $mail->From = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->FromName = isset($data['fromName']) & !empty($data['fromName']) ? $data['fromName'] : 'RuSoft'; $mail->Sender = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->Host = $smtp['host']; $mail->CharSet = $smtp['charset']; $mail->Encoding = $smtp['encoding']; $mail->Port = $smtp['port']; $mail->SMTPAuth = $smtp['auth']; $mail->Subject = isset($data['subj']) & !empty($data['subj']) ? $data['subj'] : ''; if ($smtp['auth']) { $mail->Username = $smtp['user']; $mail->Password = $smtp['pass']; } // HTML body if (isset($data['mess']['html']) & !empty($data['mess']['html'])) { $body = $data['mess']['html']; $mail->isHTML(true); } // Plain text body (for mail clients that cannot read HTML) if (isset($data['mess']['text']) & !empty($data['mess']['text'])) { $text_body = $data['mess']['text']; $mail->isHTML(false); } $mail->AltBody = isset($text_body) ? $text_body : ''; $mail->Body = isset($body) ? $body : (isset($text_body) ? $text_body : ''); $i = 1; // порядковый номер файла //добавляем файлы прикрепленные файлы if (isset($data['attachment']) & !empty($data['attachment'])) { foreach ($data['attachment'] as $k => $item) { if (isset($item['binary']) & !empty($item['binary'])) { $mail->AddStringAttachment($item["binary"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } elseif (isset($item['path']) & !empty($item['path'])) { $mail->AddAttachment($item["path"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } // добавляем файлы, отображаемые на странице if (isset($data['embedded']) & !empty($data['embedded'])) { foreach ($data['embedded'] as $k => $item) { if (isset($item['path']) & !empty($item['path'])) { $mail->AddEmbeddedImage($item["path"], isset($item["cid"]) & !empty($item["cid"]) ? $item["cid"] : $i, isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } //pr($mail); //на данном этапе имеется уже собранное письмо и нам необходимо определить mx серверы для отправки...для каждого письма. //чтобы повторно не искать серверы в момент отправки для каждого... //сохраняем для каждого домена один и тот же сервер $mxsrvs = array(); $mxemails = array(); $debug['ctime'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; foreach ($data['to'] as $email => $name) { //берем чисто host if (!$this->_is_valid_email($email)) { $debug['emails'][$email]['error'] = "неправильно указан email адрес."; continue; } $host = substr($email, strpos($email, "@") + 1); $domains = explode(".", $host); foreach ($domains as $level => $domain) { $address = implode(".", $domains); if (!key_exists($address, $mxsrvs)) { $time = array_sum(explode(' ', microtime())); if (getmxrr_portable($address, $mxhosts, $preference) == true) { array_multisort($preference, $mxhosts); } $debug['emails'][$email]['mxtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; if (!empty($mxhosts)) { $mxhosts[] = $smtp['host']; //потому что shadow тормознутый сервак if (in_array('shadow.rusoft.ru', $mxhosts)) { unset($mxhosts[0]); } //чтобы включить рассылку на smtp серверы получателей, необходимо закоментировать следующую строчку $mxhosts = array_reverse($mxhosts); $mxsrvs[$address] = $mxhosts; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; break; } else { unset($domains[$level]); } } else { $debug['emails'][$email]['mxtime'] = 'cache(0 ms)'; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; } } } //получены все mx северы и теперь начинаем отправку по списку foreach ($mxemails as $email => $mxs) { //проверяем email адрес на существование и работу mx сервера //можно включить проверку, но это 1) замедляет, 2) вероятность очень низкая //$this->checkEmail($email, $mxs, $debug); $mail->AddAddress($email, $name); foreach ($mxs as $k => $host) { $mail->Host = $host; $time = array_sum(explode(' ', microtime())); $status = $mail->Send(); $debug['emails'][$email]['sendtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; $debug['emails'][$email]['status'] = $status; if ($status) { $debug['emails'][$email]['host'] = $host; break; } } $mail->ClearAddresses(); } $debug['time'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; if (function_exists('log_notice')) { //скидываем в лог информацию о отправленных сообщениях $str = "<b>Были отправлены следующие сообщения:</b><br>Время генерации шалона для отправки: " . $debug['ctime'] . "<br>Общее время: " . $debug['time'] . "<br><b>Адреса:</b><br>"; foreach ($debug['emails'] as $k => $v) { $str .= "<br> <b><font color='blue'>" . $k . "</font></b>"; $str .= "<br> Определение smtp серверов: " . $v['mxtime']; $str .= "<br> Отправлено через: " . $v['host']; $str .= "<br> Время отправления: " . $v['sendtime']; $str .= "<br> Статус: " . ($v['status'] ? '<font color="green">успешно</font>' : '<font color="red">неудачно</font>'); } log_notice('email', false, $str); } //$status = true; // Clear attachments for next loop $mail->ClearAttachments(); if ($status) { return true; } return false; }