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; }
/** * Send mail, similar to PHP's mail * * A true return value does not automatically mean that the user received the * email successfully. It just only means that the method used was able to * process the request without any errors. * * The default content type is 'text/plain' which does not allow using HTML. */ public static function send($from_email, $from_name, array $to, $subject, $message, array $cc = array(), array $bcc = array(), array $attachments = array()) { $mailer = new phpmailer(); $content_type = 'text/plain'; $mailer->ContentType = $content_type; $mailer->Hostname = \lib\conf\constants::$domain; $mailer->IsMail(); $mailer->IsHTML(false); $mailer->From = $from_email; $mailer->FromName = $from_name; // add recipients foreach ((array) $to as $recipient_name => $recipient_email) { $mailer->AddAddress(trim($recipient_email), trim($recipient_name)); } // Add any CC and BCC recipients foreach ($cc as $recipient_name => $recipient_email) { $mailer->AddCc(trim($recipient_email), trim($recipient_name)); } foreach ($bcc as $recipient_name => $recipient_email) { $mailer->AddBcc(trim($recipient_email), trim($recipient_name)); } // Set mail's subject and body $mailer->Subject = $subject; $mailer->Body = $message; foreach ($attachments as $attachment) { $mailer->AddAttachment($attachment); } // Send! $result = $mailer->Send(); return $result; }
/** * Send an email to a specified user * * @uses $CFG * @param user $user A {@link $USER} object * @param user $from A {@link $USER} object * @param string $subject plain text subject line of the email * @param string $messagetext plain text version of the message * @param string $messagehtml complete html version of the message (optional) * @param string $attachment a file on the filesystem * @param string $attachname the name of the file (extension indicates MIME) * @param bool $usetrueaddress determines whether $from email address should * be sent out. Will be overruled by user profile setting for maildisplay * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email * was blocked by user and "false" if there was another sort of error. */ function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '') { global $CFG; $textlib = textlib_get_instance(); include_once $CFG->libdir . '/phpmailer/class.phpmailer.php'; if (empty($user) || empty($user->email)) { return false; } /* if (over_bounce_threshold($user)) { error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending."); return false; } */ // this doesn't exist right now, we may bring it in later though. $mail = new phpmailer(); $mail->Version = 'Elgg '; // mailer version (should have $CFG->version on here but we don't have it yet) $mail->PluginDir = $CFG->libdir . '/phpmailer/'; // plugin directory (eg smtp plugin) $mail->CharSet = 'UTF-8'; // everything is now uft8 if (empty($CFG->smtphosts)) { $mail->IsMail(); // use PHP mail() = sendmail } else { if ($CFG->smtphosts == 'qmail') { $mail->IsQmail(); // use Qmail system } else { $mail->IsSMTP(); // use SMTP directly if ($CFG->debug > 7) { echo '<pre>' . "\n"; $mail->SMTPDebug = true; } $mail->Host = $CFG->smtphosts; // specify main and backup servers if ($CFG->smtpuser) { // Use SMTP authentication $mail->SMTPAuth = true; $mail->Username = $CFG->smtpuser; $mail->Password = $CFG->smtppass; } } } /* not here yet, leave it in just in case. // make up an email address for handling bounces if (!empty($CFG->handlebounces)) { $modargs = 'B'.base64_encode(pack('V',$user->ident)).substr(md5($user->email),0,16); $mail->Sender = generate_email_processing_address(0,$modargs); } else { $mail->Sender = $CFG->sysadminemail; } */ $mail->Sender = $CFG->sysadminemail; // for elgg. delete if we change the above. // TODO add a preference for maildisplay if (is_string($from)) { // So we can pass whatever we want if there is need $mail->From = $CFG->noreplyaddress; $mail->FromName = $from; } else { if (empty($from)) { // make stuff up $mail->From = $CFG->sysadminemail; $mail->FromName = $CFG->sitename . ' ' . __gettext('Administrator'); } else { if ($usetrueaddress and !empty($from->maildisplay)) { $mail->From = $from->email; $mail->FromName = $from->name; } else { $mail->From = $CFG->noreplyaddress; $mail->FromName = $from->name; if (empty($replyto)) { $mail->AddReplyTo($CFG->noreplyaddress, __gettext('Do not reply')); } } } } if (!empty($replyto)) { $mail->AddReplyTo($replyto, $replytoname); } $mail->Subject = $textlib->substr(stripslashes($subject), 0, 900); $mail->AddAddress($user->email, $user->name); $mail->WordWrap = 79; // set word wrap if (!empty($from->customheaders)) { // Add custom headers if (is_array($from->customheaders)) { foreach ($from->customheaders as $customheader) { $mail->AddCustomHeader($customheader); } } else { $mail->AddCustomHeader($from->customheaders); } } if (!empty($from->priority)) { $mail->Priority = $from->priority; } //TODO add a user preference for this. right now just send plaintext $user->mailformat = 0; if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it $mail->IsHTML(true); $mail->Encoding = 'quoted-printable'; // Encoding to use $mail->Body = $messagehtml; $mail->AltBody = "\n{$messagetext}\n"; } else { $mail->IsHTML(false); $mail->Body = "\n{$messagetext}\n"; } if ($attachment && $attachname) { if (ereg("\\.\\.", $attachment)) { // Security check for ".." in dir path $mail->AddAddress($CFG->sysadminemail, $CFG->sitename . ' ' . __gettext('Administrator')); $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain'); } else { require_once $CFG->libdir . '/filelib.php'; $mimetype = mimeinfo('type', $attachname); $mail->AddAttachment($attachment, $attachname, 'base64', $mimetype); } } if ($mail->Send()) { // set_send_count($user); // later return true; } else { mtrace('ERROR: ' . $mail->ErrorInfo); return false; } }
public function sendmail($from, $to, $subject, $body, $altbody = null, $options = null, $attachments = null, $html = false) { if (!is_array($from)) { $from = array($from, $from); } $mail = new phpmailer(); $mail->PluginDir = 'M/lib/phpmailer/'; if ($this->getConfig('smtp')) { $mail->isSMTP(); $mail->Host = $this->getConfig('smtphost'); if ($this->getConfig('smtpusername')) { $mail->SMTPAuth = true; $mail->Port = $this->getConfig('smtpport') ? $this->getConfig('smtpport') : 25; $mail->SMTPDebug = $this->smtpdebug; $mail->Username = $this->getConfig('smtpusername'); $mail->Password = $this->getConfig('smtppassword'); } } $mail->CharSet = $this->getConfig('encoding'); $mail->AddAddress($to); $mail->Subject = $subject; $mail->Body = $note . $body; $mail->AltBody = $altbody; if (!is_array($from)) { $from = array($from, $from); } $mail->From = $from[0]; $mail->FromName = $from[1]; if (key_exists('reply-to', $options)) { $mail->AddReplyTo($options['reply-to']); unset($options['reply-to']); } if (key_exists('Sender', $options)) { $mail->Sender = $options['Sender']; } if (null != $attachments) { if (!is_array($attachments)) { $attachments = array($attachments); } foreach ($attachments as $k => $v) { if (!$mail->AddAttachment($v, basename($v))) { trigger_error("Attachment {$v} could not be added"); } } } $mail->IsHTML($html); $result = $mail->send(); }
/** * Update the order status and send the confirmation mail * according to the settings * * The resulting javascript code displays a message box or * does some page redirect. * @param integer $order_id The order ID * @return string Javascript code * @static */ static function updateOrder($order_id, $newStatus = 1) { global $_ARRAYLANG, $_CONFIG; $product_id = self::getOrderValue('order_product', $order_id); if (empty($product_id)) { return 'alert("' . $_ARRAYLANG['TXT_EGOV_ERROR_UPDATING_ORDER'] . '");' . "\n"; } // Has this order been updated already? $orderStatus = self::GetOrderValue('order_state', $order_id); if ($orderStatus != 0) { // Do not resend mails! return ''; } $arrFields = self::getOrderValues($order_id); $FormValue4Mail = ''; $arrMatch = array(); foreach ($arrFields as $name => $value) { // If the value matches a calendar date, prefix the string with // the day of the week if (preg_match('/^(\\d\\d?)\\.(\\d\\d?)\\.(\\d\\d\\d\\d)$/', $value, $arrMatch)) { // ISO-8601 numeric representation of the day of the week // 1 (for Monday) through 7 (for Sunday) $dotwNumber = date('N', mktime(1, 1, 1, $arrMatch[2], $arrMatch[1], $arrMatch[3])); $dotwName = $_ARRAYLANG['TXT_EGOV_DAYNAME_' . $dotwNumber]; $value = "{$dotwName}, {$value}"; } $FormValue4Mail .= html_entity_decode($name) . ': ' . html_entity_decode($value) . "\n"; } // Bestelleingang-Benachrichtigung || Mail f�r den Administrator $recipient = self::GetProduktValue('product_target_email', $product_id); if (empty($recipient)) { $recipient = self::GetSettings('set_orderentry_recipient'); } if (!empty($recipient)) { $SubjectText = str_replace('[[PRODUCT_NAME]]', html_entity_decode(self::GetProduktValue('product_name', $product_id)), self::GetSettings('set_orderentry_subject')); $SubjectText = html_entity_decode($SubjectText); $BodyText = str_replace('[[ORDER_VALUE]]', $FormValue4Mail, self::GetSettings('set_orderentry_email')); $BodyText = html_entity_decode($BodyText); $replyAddress = self::GetEmailAdress($order_id); if (empty($replyAddress)) { $replyAddress = self::GetSettings('set_orderentry_sender'); } if (@(include_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if (!empty($_CONFIG['coreSmtpServer'])) { 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; $from = self::GetSettings('set_orderentry_sender'); $fromName = self::GetSettings('set_orderentry_name'); $objMail->AddReplyTo($replyAddress); $objMail->SetFrom($from, $fromName); $objMail->Subject = $SubjectText; $objMail->Priority = 3; $objMail->IsHTML(false); $objMail->Body = $BodyText; $objMail->AddAddress($recipient); $objMail->Send(); } } // Update 29.10.2006 Statusmail automatisch abschicken || Produktdatei if (self::GetProduktValue('product_electro', $product_id) == 1 || self::GetProduktValue('product_autostatus', $product_id) == 1) { self::updateOrderStatus($order_id, $newStatus); $TargetMail = self::GetEmailAdress($order_id); if ($TargetMail != '') { $FromEmail = self::GetProduktValue('product_sender_email', $product_id); if ($FromEmail == '') { $FromEmail = self::GetSettings('set_sender_email'); } $FromName = self::GetProduktValue('product_sender_name', $product_id); if ($FromName == '') { $FromName = self::GetSettings('set_sender_name'); } $SubjectDB = self::GetProduktValue('product_target_subject', $product_id); if ($SubjectDB == '') { $SubjectDB = self::GetSettings('set_state_subject'); } $SubjectText = str_replace('[[PRODUCT_NAME]]', html_entity_decode(self::GetProduktValue('product_name', $product_id)), $SubjectDB); $SubjectText = html_entity_decode($SubjectText); $BodyDB = self::GetProduktValue('product_target_body', $product_id); if ($BodyDB == '') { $BodyDB = self::GetSettings('set_state_email'); } $BodyText = str_replace('[[ORDER_VALUE]]', $FormValue4Mail, $BodyDB); $BodyText = str_replace('[[PRODUCT_NAME]]', html_entity_decode(self::GetProduktValue('product_name', $product_id)), $BodyText); $BodyText = html_entity_decode($BodyText); 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($FromEmail, $FromName); $objMail->Subject = $SubjectText; $objMail->Priority = 3; $objMail->IsHTML(false); $objMail->Body = $BodyText; $objMail->AddAddress($TargetMail); if (self::GetProduktValue('product_electro', $product_id) == 1) { $objMail->AddAttachment(ASCMS_PATH . self::GetProduktValue('product_file', $product_id)); } $objMail->Send(); } } } return ''; }
/** * Send an email to a specified user * * @uses $CFG * @uses $FULLME * @uses SITEID * @param user $user A {@link $USER} object * @param user $from A {@link $USER} object * @param string $subject plain text subject line of the email * @param string $messagetext plain text version of the message * @param string $messagehtml complete html version of the message (optional) * @param string $attachment a file on the filesystem, relative to $CFG->dataroot * @param string $attachname the name of the file (extension indicates MIME) * @param bool $usetrueaddress determines whether $from email address should * be sent out. Will be overruled by user profile setting for maildisplay * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email * was blocked by user and "false" if there was another sort of error. */ function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '') { global $CFG, $FULLME; include_once $CFG->libdir . '/phpmailer/class.phpmailer.php'; /// We are going to use textlib services here $textlib = textlib_get_instance(); if (empty($user)) { return false; } // skip mail to suspended users if (isset($user->auth) && $user->auth == 'nologin') { return true; } if (!empty($user->emailstop)) { return 'emailstop'; } if (over_bounce_threshold($user)) { error_log("User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending."); return false; } $mail = new phpmailer(); $mail->Version = 'Moodle ' . $CFG->version; // mailer version $mail->PluginDir = $CFG->libdir . '/phpmailer/'; // plugin directory (eg smtp plugin) $mail->CharSet = 'UTF-8'; if ($CFG->smtphosts == 'qmail') { $mail->IsQmail(); // use Qmail system } else { if (empty($CFG->smtphosts)) { $mail->IsMail(); // use PHP mail() = sendmail } else { $mail->IsSMTP(); // use SMTP directly if (!empty($CFG->debugsmtp)) { echo '<pre>' . "\n"; $mail->SMTPDebug = true; } $mail->Host = $CFG->smtphosts; // specify main and backup servers if ($CFG->smtpuser) { // Use SMTP authentication $mail->SMTPAuth = true; $mail->Username = $CFG->smtpuser; $mail->Password = $CFG->smtppass; } } } $supportuser = generate_email_supportuser(); // make up an email address for handling bounces if (!empty($CFG->handlebounces)) { $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16); $mail->Sender = generate_email_processing_address(0, $modargs); } else { $mail->Sender = $supportuser->email; } if (is_string($from)) { // So we can pass whatever we want if there is need $mail->From = $CFG->noreplyaddress; $mail->FromName = $from; } else { if ($usetrueaddress and $from->maildisplay) { $mail->From = $from->email; $mail->FromName = fullname($from); } else { $mail->From = $CFG->noreplyaddress; $mail->FromName = fullname($from); if (empty($replyto)) { $mail->AddReplyTo($CFG->noreplyaddress, get_string('noreplyname')); } } } if (!empty($replyto)) { $mail->AddReplyTo($replyto, $replytoname); } $mail->Subject = substr(stripslashes($subject), 0, 900); $mail->AddAddress($user->email, fullname($user)); $mail->WordWrap = 79; // set word wrap if (!empty($from->customheaders)) { // Add custom headers if (is_array($from->customheaders)) { foreach ($from->customheaders as $customheader) { $mail->AddCustomHeader($customheader); } } else { $mail->AddCustomHeader($from->customheaders); } } if (!empty($from->priority)) { $mail->Priority = $from->priority; } if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it $mail->IsHTML(true); $mail->Encoding = 'quoted-printable'; // Encoding to use $mail->Body = $messagehtml; $mail->AltBody = "\n{$messagetext}\n"; } else { $mail->IsHTML(false); $mail->Body = "\n{$messagetext}\n"; } if ($attachment && $attachname) { if (ereg("\\.\\.", $attachment)) { // Security check for ".." in dir path $mail->AddAddress($supportuser->email, fullname($supportuser, true)); $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain'); } else { require_once $CFG->libdir . '/filelib.php'; $mimetype = mimeinfo('type', $attachname); $mail->AddAttachment($CFG->dataroot . '/' . $attachment, $attachname, 'base64', $mimetype); } } /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email /// encoding to the specified one if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) { /// Set it to site mail charset $charset = $CFG->sitemailcharset; /// Overwrite it with the user mail charset if (!empty($CFG->allowusermailcharset)) { if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) { $charset = $useremailcharset; } } /// If it has changed, convert all the necessary strings $charsets = get_list_of_charsets(); unset($charsets['UTF-8']); if (in_array($charset, $charsets)) { /// Save the new mail charset $mail->CharSet = $charset; /// And convert some strings $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet); } $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject foreach ($mail->to as $key => $to) { $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names } $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject } } if ($mail->Send()) { set_send_count($user); $mail->IsSMTP(); // use SMTP directly if (!empty($CFG->debugsmtp)) { echo '</pre>'; } return true; } else { mtrace('ERROR: ' . $mail->ErrorInfo); add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: ' . $mail->ErrorInfo); if (!empty($CFG->debugsmtp)) { echo '</pre>'; } return false; } }
* @param string mailto address * @param string mail content * @param array word replace rules * */ public static function autosend($mailto, $content, $replace = null) { foreach ($replace as $k => $v) { $content = str_replace($k, $v, $content); } $to = array(); if (is_string($mailto)) { $to[0] = $mailto; } assert(trim($mailto) == ''); Mail::_send($to, $content); } /** * Basic send function. * @param array mailto list * @param string content * @param array attachment path list */ private static function _send($mailto, $content, $title = '', $attachment = null) { require_once 'phpmailer/class.phpmailer.php'; #echo "Begin!<br/>"; if ($title == '') { $title = '来自IBM Power大赛官方的自动邮件,请勿直接回复本邮件。'; } $mail = new phpmailer(); // defaults to using php "mail()" $mail->IsSmtp(); // telling the class to use SendMail transport #$body = 'hello cxj!<br/>'; #$body = eregi_replace("[\]",'',$body); $config = C('PHPMAILER'); $address = $config['FROM']; $password = $config['PASSWORD']; $smtp = $config['HOST']; $port = $config['PORT']; #$mail->AddReplyTo($address,"First Last"); foreach ($mailto as $m) { $mail->AddAddress($m, "Power大赛参赛选手 {$m} "); } $mail->SMTPAuth = true; //$mail->from = $address; //$mail->to = $address; $mail->smtpsecure = 'ssl'; $mail->From = $address;
/** * 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; }
exit; } if (fwrite($gestor, $dompdf->output()) === FALSE) { echo "No se puede escribir al archivo ({$nombre_archivo})"; exit; } echo "Éxito, se escribió al archivo ({$nombre_archivo})"; fclose($gestor); //$dompdf->stream('personal.pdf'); //mail("*****@*****.**", "Comision", $codigoHtml); $mail->ClearAllRecipients(); $mail->ClearAttachments(); // añado el usuario de destino y otras configuraciones $usuario_obj = "*****@*****.**"; $mail->AddAddress($usuario_obj); $mail->Subject = "Prueba de phpmailer"; $cuerpo_mensaje = "hola"; $mail->Body = $cuerpo_mensaje; // nombre_adjunto es el nombre que verá el usuario cuando reciba el mail como nombre del archivo $mail->AddAttachment($nombre_archivo, "nombre_adjunto.pdf"); // texto alternativo por si el usuario no admite html $mail->AltBody = "Mensaje de prueba mandado con phpmailer en formato solo texto"; $exito = $mail->Send(); // borro el fichero real unlink($nombre_archivo); if (!$exito) { echo "Problemas enviando correo electrónico"; echo "\n" . $mail->ErrorInfo; } else { echo "Mensaje enviado correctamente"; }
$upl_tmp_dir = get_cfg_var('upload_tmp_dir'); } if ($fix_tmp_dir) { // only for fixing on some servers, normally NOT used - set in config.php $tmp_dir = $fix_tmp_dir; } elseif ($upl_tmp_dir) { $tmp_dir = $upl_tmp_dir; } else { $tmp_dir = dirname(tempnam('', '')); } if ($pic1 != "none" && $pic1) { $pic1_file = $tmp_dir . "/pic1.tmp"; copy($pic1, $pic1_file); } if ($pic1_file) { $mail->AddAttachment("{$pic1_file}", "{$pic1_name}"); } if ($pic2 != "none" && $pic2) { $pic2_file = $tmp_dir . "/pic2.tmp"; copy($pic2, $pic2_file); } if ($pic2_file) { $mail->AddAttachment("{$pic2_file}", "{$pic2_name}"); } if ($pic3 != "none" && $pic3) { $pic3_file = $tmp_dir . "/pic3.tmp"; copy($pic3, $pic3_file); } if ($pic3_file) { $mail->AddAttachment("{$pic3_file}", "{$pic3_name}"); }
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>"; } } }
$mail->UseMSMailHeaders = true; $mail->AddCustomHeader("X-Mailer: {$bazar_name} {$bazar_}#{$Id}\$- Email Interface"); $mail->AddAddress("{$toemail}", "{$toname}"); if ($cc) { $mail->AddBCC($fromemail, $fromname); } $mail->Subject = stripslashes($subject); if ($webmail_enable) { $mail->Body = addslashes($body); $mail->Subject = addslashes($subject); } else { $mail->Body = stripslashes($body); $mail->Subject = stripslashes($subject); } if ($pic1 != "none" && $pic1) { $mail->AddAttachment("{$pic1}", "{$pic1_name}"); } if ($pic2 != "none" && $pic2) { $mail->AddAttachment("{$pic2}", "{$pic2_name}"); } if ($pic3 != "none" && $pic3) { $mail->AddAttachment("{$pic3}", "{$pic3_name}"); } if (!$mail->Send()) { echo "There was an error sending the message"; exit; } if ($mail_notify) { $subject_notify = "NOTIFY E-Mail from {$fromname}<{$fromemail}> to {$toname}<{$toemail}>"; if ($webmail_enable && !$friend) { //WebMail or NOT ???
/** * Funcion que envia el correo * @param $to * @param $cc * @param $cco * @param $subject * @param $from * @param $body * Valida que los destinatarios con sus * respectivos nombres y asunto tengan * un formato válido. * * Se envia correo a los destinatarios recibidos * Retorna boolean true al enviar correo exitoso. * @return boolean */ public function Send($value = '') { $to = $this->to; // Cuenta que los destinatarios to no sean mas de 5. $contador = count($to); if ($contador > 5) { $this->errors = "MAX_FIVE_RECIPIENTS"; return 0; } // Se evoca la funcion validadora para comprobar // los formatos de correo y respectivos nombres. $t = $this->Valida_dest($to); if ($t == 0) { return 0; } $cc = $this->cc; // Cuenta que los destinatarios cc(si hubiese) no sean mas de 5. $contador = count($cc); if ($contador > 5) { $this->errors = "MAX_FIVE_COPYS"; return 0; } // Se evoca la funcion validadora para comprobar // los formatos de correo y respectivos nombres(si hubiese). $c = $this->Valida_dest($cc); if ($c == 0) { return 0; } $cco = $this->cco; // Cuenta que los destinatarios cco(si hubiese) no sean mas de 5. $contador = count($cco); if ($contador > 20) { $this->errors = "MAX_TWENTY_BCC"; return 0; } // Se evoca la funcion validadora para comprobar // los formatos de correo y respectivos nombres(si hubiese). $co = $this->Valida_dest($cco); if ($co == 0) { return 0; } $subject = $this->subject; // Se evoca la funcion validadora para comprobar // el formato del asunto. if (!empty($subject)) { $s = $this->Valida_headers($subject); if ($s == 0) { return 0; } foreach ($subject as $key => $value) { $subject = $value; } } $from = $this->from; if (!empty($from)) { // Se evoca la funcion validadora para comprobar // el formato del correo y nombre del remitente. $def_from = 1; $f = $this->Valida_headers($from); if ($f == 0) { return 0; } $from = array(); foreach ($f as $key => $value) { $from[] = $value; } } else { $def_from = 0; } $replyto = $this->replyto; if (!empty($replyto)) { $rp = 1; // Se evoca la funcion validadora para comprobar // el formato del correo y nombre para informar // sobre correos fallidos(si hubiese). $rt = $this->Valida_headers($replyto); if ($rt == 0) { return 0; } $replyto = array(); foreach ($rt as $key => $value) { $replyto[] = $value; } } else { $rp = 0; } $body = $this->body; // Recibimos las rutas y alias de los archivos adjuntos // necesarios a enviar en el correo (si hubiese). $attachment = $this->attachment; if (!empty($attachment)) { $z = 2; $attachment_r = array(); $attachment_t = array(); foreach (new ArrayIterator($this->attachment) as $route => $type) { $attachment_r[] = $route; $attachment_t[] = $type; } } else { $z = 1; } // Recibimos las rutas y alias de las imagenes embebidas en un html // necesarios a enviar en el correo (si hubiese). $embeddedimg = $this->embeddedimg; if (!empty($embeddedimg)) { $y = 2; $embeddedimg_r = array(); $embeddedimg_t = array(); foreach (new ArrayIterator($this->embeddedimg) as $route => $type) { $embeddedimg_r[] = $route; $embeddedimg_t[] = $type; } } else { $y = 1; } // si se deseára configurar los parametros de el dominio // y cuenta de correo default, aquí se recibirian los parámetros. $port = $this->port; $smtp_secure = $this->smtp_secure; $auth = $this->auth; $host = $this->host; $username = $this->username; $password = $this->password; $mail = new phpmailer(); $mail->CharSet = 'UTF-8'; $mail->Mailer = "smtp"; $mail->IsSMTP(); ini_set('max_execution_time', 600); $mail->SMTPAuth = true; // si se indica un puerto este se utilizara, // de lo contrario su usará el default. if (empty($port)) { $mail->Port = 465; } else { $mail->Port = $port; } // si se indica un tipo de seguridad este se utilizara, // de lo contrario su usará el default. if (empty($smtp_secure)) { $mail->SMTPSecure = 'ssl'; } else { $mail->SMTPSecure = $smtp_secure; } // si se indica un cambio en la autenticación este se utilizara, // de lo contrario su usará el default. if (empty($auth)) { $mail->SMTPAuth = true; } else { $mail->SMTPAuth = $auth; } // si se indica un host este se utilizara, // de lo contrario su usará el default. if (empty($host)) { $mail->Host = "securemail.aplus.net"; } else { $mail->Host = $host; } // si se indica un usuario este se utilizara, // de lo contrario su usará el default. if (empty($username)) { $mail->Username = "******"; } else { $mail->Username = $username; } // si se indica un password este se utilizara, // de lo contrario su usará el default. if (empty($password)) { $mail->Password = "******"; } else { $mail->Password = $password; } $mail->Subject = $subject; if ($def_from == 1) { $mail->SetFrom($from[1], $from[0]); } else { $mail->SetFrom('*****@*****.**', 'Global Corporation'); } if ($rp == 1) { $mail->AddReplyTo($replyto[1], $replyto[0]); } $mail->Body = " "; $mail->MsgHTML($body); if ($z == 2) { for ($a = 0; $a < count($attachment_r); $a++) { $mail->AddAttachment($attachment_r[$a], $attachment_t[$a]); } } if ($y == 2) { for ($a = 0; $a < count($embeddedimg_r); $a++) { $mail->AddEmbeddedImage($embeddedimg_r[$a], $embeddedimg_t[$a]); } } for ($i = 0; $i < count($to); $i++) { $a = $to[$i]; $mail->AddAddress($a['direccion'], $a['nombre']); } for ($j = 0; $j < count($cc); $j++) { $a = $cc[$j]; $mail->AddCC($a['direccion'], $a['nombre']); } for ($k = 0; $k < count($cco); $k++) { $a = $cco[$k]; $mail->AddBCC($a['direccion'], $a['nombre']); } $mail->IsHTML(true); if ($mail->Send()) { return true; } else { $this->errors = "SEND_MAIL_ERROR " . $mail->ErrorInfo; return 0; } }
/** * 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; }
$mail->FromName = "Backup Bolão"; $mail->Hostname = "smtp.netsite.com.br"; $mail->Host = "smtp.netsite.com.br"; // $mail->SMTPDebug = 2; $mail->Username = "******"; $mail->Password = "******"; $mail->SMTPAuth = true; $mail->Timeout = 120; $body = "Backup automático do bolão"; $text_body = "Backup automático do bolão"; $mail->isHTML(true); $mail->Subject = sprintf("Backup Bolão do dia %s", date("d/m/Y H:i:s")); $mail->Body = $body; $mail->AltBody = $text_body; $mail->AddAddress($row['emailwbm'], ""); $mail->AddAttachment("/home/bkbolao/bkdados.tar.gz"); $mail->AddAttachment("/home/bkbolao/bkfontes.tar.gz"); $exito = $mail->Send(); $v = 0; 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(); mysql_free_result($result);
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); } }
static function sendNextBlock($release_id, $num_block) { if ($release = ormObjects::get($release_id)) { $subscribe = $release->getParent(); $release->last_subscribe = date('Y-m-d H:i:s'); $release->error_iteration_num = $num_block + 1; $release->save(); $start = ($_SESSION['SUBSCR_PART'] - 1) * reg::getKey('/subscription/count_mails_day') + ($num_block - 1) * reg::getKey('/subscription/count_mails'); $sel = new ormSelect('subscribe_user'); $sel->where('parents', '=', $release->parent_id); $sel->limit($start, reg::getKey('/subscription/count_mails')); while ($obj = $sel->getObject()) { // Подставляем ФИО пользователя page::assign('user.id', $obj->id); page::assign('user_name', ''); if (file_exists(TEMPL_DIR . '/subscription/mails/' . $subscribe->template . '.tpl')) { include TEMPL_DIR . '/subscription/mails/' . $subscribe->template . '.tpl'; if ($obj->first_name != '') { if ($subscribe->name_format == 2) { $name = $obj->second_name . ' ' . $obj->first_name; } else { $name = $obj->first_name; } page::assign('user_name', $name); $hello = page::parse($TEMPLATE['hello_username']); } else { $hello = page::parse($TEMPLATE['hello']); } } else { $hello = ''; } page::assign('hello', $hello); // Отправляет письмо $mail = new phpmailer(); $mail->From = $subscribe->back_email; $mail->FromName = $subscribe->back_name; $mail->AddAddress($obj->name); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->AddAttachment(ROOT_DIR . '/' . $release->file, system::fileName($release->file)); $mail->Subject = page::parse($_SESSION['SUBSCR_SUBJECT']); $mail->Body = page::parse($_SESSION['SUBSCR_MAILHTML']); $mail->Send(); } } }
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_mail = new phpmailer(); $send_mail->From = OWP_OWNER_EMAIL_ADDRESS; $send_mail->FromName = OWP_NAME; $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');
/** * Добавляем прикрепляемый файл * * @param string $sPath Абсолютный путь к файлу * @param string $sName Свое имя файла * @param string $sEncoding Кодированик файла * @param string $sType Расширение файла (MIME). */ public function AddAttachment($sPath, $sName = '', $sEncoding = 'base64', $sType = 'application/octet-stream') { ob_start(); $this->oMailer->AddAttachment($sPath, $sName, $sEncoding, $sType); $this->sError = ob_get_clean(); }
/** * 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; }
if (!$mail->Send()) { echo "<b>Err envoi</b>"; } else { echo "envoi ok"; } echo "<br><br>"; echo "<h1>function send_Email: </h1>"; if (!send_Email($to, $sujet, $message, $from, $pieces)) { echo "<b>Err envoi</b>"; } else { echo "envoi ok"; } echo "<br><br>"; echo "<h1>Lib phpmailer: </h1>"; $phpmail = new phpmailer(); $phpmail->From = $from; $phpmail->FromName = $from_name; $phpmail->AddAddress($to); $phpmail->Mailer = "sendmail"; $phpmail->Subject = $sujet; $phpmail->Body = $message; $phpmail->AddAttachment($pieces["nom"]); if (!$phpmail->Send()) { echo "<b>Err envoi</b>"; } else { echo "envoi ok"; } ?> </body> </html>
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; }