/** * 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; } }
function __construct() { $mail = new phpmailer(); $mail->IsSMTP(); //$mail->IsMail(); $mail->SMTPAuth = true; // enable SMTP authentication $mail->SMTPSecure = "ssl"; // sets the prefix to the servier $mail->Host = SMTP_HOST; // sets GMAIL as the SMTP server $mail->Port = SMTP_PORT; // set the SMTP port for the GMAIL server $mail->Username = SMTP_USERNAME; // GMAIL username $mail->Password = SMTP_PASSWORD; // GMAIL password $mail->AddReplyTo(EMAIL_FROM, ""); $mail->From = EMAIL_FROM; $mail->FromName = EMAIL_FROM_NAME; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->WordWrap = 50; // set word wrap $this->_mail = $mail; }
function sendQRmail($from, $to, $subject, $msg, $qrcodeImage, $cid, $name) { include_once 'inc/class.phpmailer.php'; $mail = new phpmailer(); $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only, 0 = off $mail->IsSMTP(); // Set mailer to use SMTP $mail->Host = 'mailhub.eait.uq.edu.au'; // Specify server $mail->Port = 25; // Server port: 465 ssl OR 587 tls //$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted $mail->SMTPAuth = false; // Enable SMTP authentication $mail->Username = '******'; // SMTP username $mail->Password = '******'; // SMTP password $mail->SetFrom($from, 'QRappi'); // Sender $mail->AddReplyTo($from, 'Support'); // Set an alternative reply-to address $mail->AddAddress($to, 'User'); // Set who the message is to be sent to $mail->Subject = $subject; // Set the subject line // Prepares message for html (see doc for details http://phpmailer.worxware.com/?pg=tutorial) $mail->MsgHTML($msg); // Add the image to the email as an inline element (i.e. not as an attachment) $mail->AddStringEmbeddedImage($qrcodeImage, $cid, $name); // Send the message, check for errors $ok = $mail->Send(); return $ok; }
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(); }
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(); }
function enviar($arguntos) { # code... $mail = new phpmailer(true); // the true param means it will throw exceptions on errors, which we need to catch $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = Host; // SMTP server $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) $mail->IsHTML(true); $mail->SMTPAuth = SMTPAuth; // enable SMTP authentication $mail->SMTPSecure = SMTPSecure; // sets the prefix to the servier $mail->Port = Port; // set the SMTP port for the GMAIL server $mail->Username = Username; // GMAIL username $mail->Password = Password; // GMAIL password $mail->AddAddress($arguntos['email'], $arguntos['nomebusca']); if (AddReplyTo != '') { $mail->AddReplyTo(AddReplyTo); } $mail->Subject = $arguntos['Subject']; $mail->From = SetFromEmail; $mail->FromName = SetFromNome; $mail->Body = $arguntos['conteudo']; // optional - MsgHTML will create an alternate automatically // $mail->MsgHTML($arguntos['conteudo']); if ($mail->Send()) { echo "<p>Mensagem enviada com Sucesso!!!!</p>\n"; } }
/** * 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; } }
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->From = $fromMail; $objMail->FromName = $fromName; $objMail->AddReplyTo($fromMail); $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 send_email($to, $subject, $body, $from = '', $fromname = '', $stmp = true, $sender = '', $host = '', $port = '', $ssl = '', $username = '', $password = '') { global $charset; $mail = new phpmailer(); if (!$stmp) { $mail->IsMail(); } else { $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = $host; if ($ssl) { $mail->SMTPSecure = "ssl"; } if ($port != '') { $mail->Port = $port; } $mail->Username = $username; $mail->Password = $password; } $mail->IsHTML(true); $mail->Sender = $sender; $mail->FromEmail = $from; $mail->FromName = $fromname; $mail->Subject = $subject; $mail->Body = $body; $mail->CharSet = $charset; $mail->WordWrap = 50; if (is_array($to)) { foreach ($to as $email) { $mail->AddAddress($email, ""); } } else { $mail->AddAddress($to, ""); } if ($fromname != '') { $mail->AddReplyTo($from, $fromname); } $mail->IsHTML(true); if (!$mail->Send()) { return "Mailer Error: " . $mail->ErrorInfo; } else { return true; } }
/** * Inform the admin about a reject * * If an email could not be sent, inform the administrator * about that (only if the option to do so was set) * @author Stefan Heinemann <*****@*****.**> * @param int $newsletterID * @param int $userID * @param string $email * @param const */ protected function informAdminAboutRejectedMail($newsletterID, $userID, $email, $type) { // Get the current user's email address $addy = \FWUser::getFWUserObject()->objUser->getEmail(); \Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php'); $mail = new \phpmailer(); $newsletterValues = $this->getNewsletterValues($newsletterID); if ($newsletterValues['smtp_server'] > 0) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($newsletterValues['smtp_server'])) !== 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->From = $newsletterValues['sender_email']; $mail->FromName = $newsletterValues['sender_name']; $mail->AddReplyTo($newsletterValues['return_path']); $mail->Subject = $newsletterValues['subject']; $mail->Priority = $newsletterValues['priority']; $mail->Body = $this->getInformMailBody($userID, $email, $type); $mail->AddAddress($addy); $mail->send(); }
function sendMessage($id) { global $objDatabase, $_ARRAYLANG, $_CORELANG, $_CONFIG; $this->_objTpl->setTemplate($this->pageContent, true, true); //get erntry $this->getEntries('', 'id', $id); if (isset($id) && count($this->entries) != 0) { //get search $this->getSearch(); //get navigatin $this->getNavigation($this->entries[$id]['catid']); if ($_POST['title'] != '' && $_POST['message'] != '') { //create mail $sendTo = $this->entries[$id]['email']; $fromName = $_POST['name']; $fromMail = $_POST['email']; $subject = $_POST['title']; $newPrice = $_POST['newprice'] != '' ? "\n\n" . $_ARRAYLANG['TXT_PRICE_EXPECTATION'] . "\n" . $_POST['newprice'] : ''; $oldPrice = $_POST['price'] != '' ? "\n\n" . $_ARRAYLANG['TXT_MARKET_MESSAGE_PRICE'] . "\n" . $_POST['price'] : ''; $message = $_POST['message'] . $oldPrice . $newPrice; 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')) { 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 = $fromMail; $objMail->FromName = $fromName; $objMail->AddReplyTo($fromMail); $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $message; $objMail->AddAddress($sendTo); $objMail->Send(); } // set variables $this->_objTpl->setVariable(array('MARKET_TITLE' => $_ARRAYLANG['TXT_MARKET_MESSAGE_SUCCESS_TITLE'], 'MARKET_MSG_SEND' => $_ARRAYLANG['TXT_MARKET_MESSAGE_SUCCESS_BODY'], 'TXT_MARKET_BACK' => $_CORELANG['TXT_BACK'])); } } else { \Cx\Core\Csrf\Controller\Csrf::header('Location: ?section=Market'); } }
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->From = $_CONFIG['coreAdminEmail']; $objMail->FromName = $_CONFIG['coreGlobalPageTitle']; $objMail->AddReplyTo($_CONFIG['coreAdminEmail']); $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(); } } } }
function supportSendMail($email, $name, $subject, $message, $response_flag = false) { global $sendmethod, $sockethost, $smtpauth, $smtpauthuser, $smtpauthpass, $socketfrom, $socketfromname, $socketreply, $socketreplyname; include_once 'class.phpmailer.php'; $mail = new phpmailer(); if (file_exists('class/language/phpmailer.lang-en.php')) { $mail->SetLanguage('en', 'class/language/'); } else { $mail->SetLanguage('en', '../class/language/'); } if (isset($sendmethod) && $sendmethod == 'sendmail') { $mail->IssupportSendMail(); } elseif (isset($sendmethod) && $sendmethod == 'smtp') { $mail->IsSMTP(); } elseif (isset($sendmethod) && $sendmethod == 'mail') { $mail->IsMail(); } elseif (isset($sendmethod) && $sendmethod == 'qmail') { $mail->IsQmail(); } $mail->Host = $sockethost; if ($smtpauth == 'TRUE') { $mail->SMTPAuth = true; $mail->Username = $smtpauthuser; $mail->Password = $smtpauthpass; } if (!$response_flag && 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 (!$response_flag && 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->ErrorInfo; } $mail->ClearAddresses(); }
/** * 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; } }
/** * @return void * @desc Sends a notification email to the administrator */ function sendNotificationEmail($forename, $name, $comment, $email = null) { global $_ARRAYLANG, $_CONFIG; $message = $_ARRAYLANG['TXT_CHECK_GUESTBOOK_ENTRY'] . "\n\n"; $message .= $_ARRAYLANG['TXT_ENTRY_READS'] . "\n" . $forename . " " . $name . "\n" . html_entity_decode($comment, ENT_QUOTES, CONTREXX_CHARSET); $mailto = $_CONFIG['coreAdminEmail']; $subject = $_ARRAYLANG['TXT_NEW_GUESTBOOK_ENTRY'] . " " . $_CONFIG['domainUrl']; if (@(include_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && @(include_once ASCMS_CORE_PATH . '/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; if (isset($email)) { $objMail->From = $email; $objMail->AddReplyTo($email); } else { $objMail->From = $mailto; } $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $message; $objMail->AddAddress($mailto); if ($objMail->Send()) { return true; } } return false; }
/** * 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; }
function _sendNotificationEmail($action, $recipientId) { global $_CONFIG, $_ARRAYLANG, $objDatabase; //action: 1 = subscribe | 2 = unsubscribe $objSettings = $objDatabase->Execute("SELECT `setname`, `setvalue` FROM `" . DBPREFIX . "module_newsletter_settings` WHERE `setname` = 'notificationSubscribe' OR `setname` = 'notificationUnsubscribe' "); if ($objSettings !== false) { while (!$objSettings->EOF) { $arrSettings[$objSettings->fields['setname']] = $objSettings->fields['setvalue']; $objSettings->MoveNext(); } } if ($arrSettings['notificationSubscribe'] == 1 && $action == 1 || $arrSettings['notificationUnsubscribe'] == 1 && $action == 2) { if (!@(include_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { return false; } $objRecipient = $objDatabase->SelectLimit("SELECT sex, salutation, lastname, firstname, email FROM " . DBPREFIX . "module_newsletter_user WHERE id=" . $recipientId, 1); if ($objRecipient !== false) { $arrRecipient['sex'] = $objRecipient->fields['sex']; $arrRecipient['salutation'] = $objRecipient->fields['salutation']; $arrRecipient['lastname'] = $objRecipient->fields['lastname']; $arrRecipient['firstname'] = $objRecipient->fields['firstname']; $arrRecipient['email'] = $objRecipient->fields['email']; } $objRecipientTitle = $objDatabase->SelectLimit("SELECT title FROM " . DBPREFIX . "module_newsletter_user_title WHERE id=" . $arrRecipient['salutation'], 1); if ($objRecipientTitle !== false) { $arrRecipientTitle = $objRecipientTitle->fields['title']; } $objNotificationMail = $objDatabase->SelectLimit("SELECT title, content, recipients FROM " . DBPREFIX . "module_newsletter_confirm_mail WHERE id='3'", 1); if ($action == 1) { $txtAction = $_ARRAYLANG['TXT_NEWSLETTER_NOTIFICATION_SUBSCRIBE']; } else { $txtAction = $_ARRAYLANG['TXT_NEWSLETTER_NOTIFICATION_UNSUBSCRIBE']; $objNotificationAdressesFromLists = $objDatabase->Execute('SELECT notification_email FROM ' . DBPREFIX . 'module_newsletter_category AS c INNER JOIN ' . DBPREFIX . 'module_newsletter_rel_user_cat AS r ON r.category = c.id WHERE r.user = '******',', $objNotificationAdressesFromLists->fields['notification_email']) as $mail) { if (!in_array($mail, $notifyMails)) { array_push($notifyMails, trim($mail)); } } $objNotificationAdressesFromLists->MoveNext(); } } } $arrParsedTxts = str_replace(array('[[action]]', '[[url]]', '[[date]]', '[[sex]]', '[[title]]', '[[lastname]]', '[[firstname]]', '[[e-mail]]'), array($txtAction, $_CONFIG['domainUrl'], date(ASCMS_DATE_FORMAT), $arrRecipient['sex'], $arrRecipientTitle, $arrRecipient['lastname'], $arrRecipient['firstname'], $arrRecipient['email']), array($objNotificationMail->fields['title'], $objNotificationMail->fields['content'])); $arrRecipients = explode(',', $objNotificationMail->fields['recipients']); $arrSettings =& $this->_getSettings(); $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && @(include_once ASCMS_CORE_PATH . '/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 = $arrSettings['sender_mail']['setvalue']; $objMail->FromName = $arrSettings['sender_name']['setvalue']; $objMail->AddReplyTo($arrSettings['reply_mail']['setvalue']); $objMail->Subject = $arrParsedTxts[0]; $objMail->Priority = 3; $objMail->IsHTML(false); $objMail->Body = $arrParsedTxts[1]; foreach ($arrRecipients as $key => $recipientEmail) { $objMail->AddAddress($recipientEmail); } foreach ($notifyMails as $mail) { $objMail->AddAddress($mail); } if ($objMail->Send()) { return true; } } // TODO: This used to return *nothing* when notifications were turned off. // Probably true should be returned in this case instead. // -- See the condition way above. return false; }
/** * Initialize the mail functionality to the recipient * * @global object $objDatabase * @global array $_ARRAYLANG * @global integer $_LANGID * @global array $_CONFIG * @param integer $eventId * @param integer $actionId * @param integer $regId * @param string $mailTemplate */ function sendMail($eventId, $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)) { $objEvent = new \Cx\Modules\Calendar\Controller\CalendarEvent($eventId); $objRegistration = null; if (!empty($regId)) { $objRegistration = new \Cx\Modules\Calendar\Controller\CalendarRegistration($objEvent->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 = date(parent::getDateFormat() . " - H:i:s"); $eventTitle = $objEvent->title; $eventStart = $objEvent->all_day ? date(parent::getDateFormat(), $objEvent->startDate) : date(parent::getDateFormat() . " (H:i:s)", $objEvent->startDate); $eventEnd = $objEvent->all_day ? date(parent::getDateFormat(), $objEvent->endDate) : date(parent::getDateFormat() . " (H:i:s)", $objEvent->endDate); $placeholder = array('[[TITLE]]', '[[START_DATE]]', '[[END_DATE]]', '[[LINK_EVENT]]', '[[LINK_REGISTRATION]]', '[[USERNAME]]', '[[FIRSTNAME]]', '[[LASTNAME]]', '[[URL]]', '[[DATE]]'); $recipients = $this->getSendMailRecipients($actionId, $objEvent, $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->From = $_CONFIG['coreAdminEmail']; $objMail->FromName = $_CONFIG['coreGlobalPageTitle']; $objMail->AddReplyTo($_CONFIG['coreAdminEmail']); 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 && $objEvent->arrSettings['confirmFrontendEvents'] == 1) { $eventLink = $domain . "/cadmin/index.php?cmd={$this->moduleName}&act=modify_event&id={$objEvent->id}&confirm=1"; } else { $eventLink = \Cx\Core\Routing\Url::fromModuleAndCmd($this->moduleName, 'detail', $contentLanguage, array('id' => $objEvent->id, 'date' => $objEvent->startDate))->toString(); } $regLink = \Cx\Core\Routing\Url::fromModuleAndCmd($this->moduleName, 'register', $contentLanguage, array('id' => $objEvent->id, 'date' => $objEvent->startDate))->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(); } } } }
$sql = 'UPDATE anonymous_users SET validated = 1 WHERE email = \'%s\' AND hash = \'%s\''; } $sql = sprintf($sql, $_REQUEST['email'], $_REQUEST['h']); $result = mysql_query($sql); if ($result === false) { $output->pushMsg(new GeneralResponse('We\'re sorry there was an error when trying to verify your email address. An administrator has been contacted. Please try again later.'), iResponseQ::MSG_TYPE_ERROR); $body = 'failed to execute sql \'' . $sql . '\''; $body .= ' Db error \'' . mysql_error() . '\''; $body .= ' _REQUEST[] = ' . var_export($_REQUEST, true); $mail = new phpmailer(); $mail->From = "*****@*****.**"; $mail->FromName = "No-reply"; $mail->Host = "127.0.0.1"; // specify main and backup server $mail->AddAddress($adminEmail, "BoD Admin"); $mail->AddReplyTo("*****@*****.**", "No-reply"); $mail->WordWrap = 50; // set word wrap $mail->IsHTML(true); // set email format to HTML $mail->Subject = "Error: Verifying user email"; $mail->Body = $body; $mail->Send(); // send message } else { if (mysql_affected_rows() == 0) { $sql = 'SELECT validated FROM anonymous_users WHERE email = \'%s\' AND hash = \'%s\''; $sql = sprintf($sql, $_REQUEST['email'], $_REQUEST['h']); $result = mysql_query($sql); if ($result === false) { $output->pushMsg(new GeneralResponse('Email address not found - DB error'), iResponseQ::MSG_TYPE_ERROR);
/** * Always use this function for all emails to users * * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email * @param object $userfrom user object to send email from. If null, email will come from mahara * @param string $subject email subject * @param string $messagetext text version of email * @param string $messagehtml html version of email (will send both html and text) * @param array $customheaders email headers * @throws EmailException * @throws EmailDisabledException */ function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml = '', $customheaders = null) { global $IDPJUMPURL; static $mnetjumps = array(); if (!get_config('sendemail')) { // You can entirely disable Mahara from sending any e-mail via the // 'sendemail' configuration variable return true; } if (empty($userto)) { throw new InvalidArgumentException("empty user given to email_user"); } if (!($mailinfo = can_receive_email($userto))) { throw new EmailDisabledException("email for this user has been disabled"); } // If the user is a remote xmlrpc user, trawl through the email text for URLs // to our wwwroot and modify the url to direct the user's browser to login at // their home site before hitting the link on this site if (!empty($userto->mnethostwwwroot) && !empty($userto->mnethostapp)) { require_once get_config('docroot') . 'auth/xmlrpc/lib.php'; // Form the request url to hit the idp's jump.php if (isset($mnetjumps[$userto->mnethostwwwroot])) { $IDPJUMPURL = $mnetjumps[$userto->mnethostwwwroot]; } else { $mnetjumps[$userto->mnethostwwwroot] = $IDPJUMPURL = PluginAuthXmlrpc::get_jump_url_prefix($userto->mnethostwwwroot, $userto->mnethostapp); } $wwwroot = get_config('wwwroot'); $messagetext = preg_replace_callback('%(' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))%', 'localurl_to_jumpurl', $messagetext); $messagehtml = preg_replace_callback('%href=["\'`](' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))["\'`]%', 'localurl_to_jumpurl', $messagehtml); } require_once 'phpmailer/class.phpmailer.php'; $mail = new phpmailer(); // Leaving this commented out - there's no reason for people to know this //$mail->Version = 'Mahara ' . get_config('release'); $mail->PluginDir = get_config('libroot') . 'phpmailer/'; $mail->CharSet = 'UTF-8'; $smtphosts = get_config('smtphosts'); if ($smtphosts == 'qmail') { // use Qmail system $mail->IsQmail(); } else { if (empty($smtphosts)) { // use PHP mail() = sendmail $mail->IsMail(); } else { $mail->IsSMTP(); // use SMTP directly $mail->Host = get_config('smtphosts'); if (get_config('smtpuser')) { // Use SMTP authentication $mail->SMTPAuth = true; $mail->Username = get_config('smtpuser'); $mail->Password = get_config('smtppass'); } } } if (get_config('bounces_handle') && isset($mailinfo->owner)) { $mail->Sender = generate_email_processing_address($mailinfo->owner, $userto); } if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) { if (empty($mail->Sender)) { $mail->Sender = get_config('noreplyaddress'); } $mail->From = get_config('noreplyaddress'); $mail->FromName = isset($userfrom->id) ? display_name($userfrom, $userto) : get_config('sitename'); $customheaders[] = 'Precedence: Bulk'; // Try to avoid pesky out of office responses $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n"; if ($messagehtml) { $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n"; } } else { if (empty($mail->Sender)) { $mail->Sender = $userfrom->email; } $mail->From = $userfrom->email; $mail->FromName = display_name($userfrom, $userto); } $replytoset = false; if (!empty($customheaders) && is_array($customheaders)) { foreach ($customheaders as $customheader) { $mail->AddCustomHeader($customheader); if (0 === stripos($customheader, 'reply-to')) { $replytoset = true; } } } if (!$replytoset) { $mail->AddReplyTo($mail->From, $mail->FromName); } $mail->Subject = substr(stripslashes($subject), 0, 900); if ($to = get_config('sendallemailto')) { // Admins can configure the system to send all email to a given address // instead of whoever would receive it, useful for debugging. $mail->addAddress($to); $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email); $messagetext = $notice . "\n\n" . $messagetext; if ($messagehtml) { $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml; } $usertoname = display_name($userto, $userto, true) . ' (' . get_string('divertingemailto', 'mahara', $to) . ')'; } else { $usertoname = display_name($userto, $userto); if (empty($userto->email)) { throw new EmailException("Cannot send email to {$usertoname} with subject {$subject}. User has no primary email address set."); } $mail->AddAddress($userto->email, $usertoname); $to = $userto->email; } $mail->WordWrap = 79; if ($messagehtml) { $mail->IsHTML(true); $mail->Encoding = 'quoted-printable'; $mail->Body = $messagehtml; $mail->AltBody = $messagetext; } else { $mail->IsHTML(false); $mail->Body = $messagetext; } if ($mail->Send()) { if ($logfile = get_config('emaillog')) { $docroot = get_config('docroot'); @($client = (string) $_SERVER['REMOTE_ADDR']); @($script = (string) $_SERVER['SCRIPT_FILENAME']); if (strpos($script, $docroot) === 0) { $script = substr($script, strlen($docroot)); } $line = "{$to} <- {$mail->From} - " . str_shorten_text($mail->Subject, 200); @error_log('[' . date("Y-m-d h:i:s") . "] [{$client}] [{$script}] {$line}\n", 3, $logfile); } // Update the count of sent mail update_send_count($userto); return true; } throw new EmailException("Couldn't send email to {$usertoname} with subject {$subject}. " . "Error from phpmailer was: " . $mail->ErrorInfo); }
function send() { global $objDatabase, $_ARRAYLANG, $_CONFIG; $this->_objTpl->setTemplate($this->pageContent); // Initialize variables $code = substr(md5(rand()), 1, 10); $url = ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ($_SERVER['SERVER_PORT'] == 80 ? null : ':' . intval($_SERVER['SERVER_PORT'])) . CONTREXX_SCRIPT_PATH . '?section=Ecard&cmd=show&code=' . $code; // Initialize POST variables $id = intval($_POST['selectedEcard']); $message = contrexx_addslashes($_POST['ecardMessage']); $recipientSalutation = contrexx_stripslashes($_POST['ecardRecipientSalutation']); $senderName = contrexx_stripslashes($_POST['ecardSenderName']); $senderEmail = \FWValidator::isEmail($_POST['ecardSenderEmail']) ? $_POST['ecardSenderEmail'] : ''; $recipientName = contrexx_stripslashes($_POST['ecardRecipientName']); $recipientEmail = \FWValidator::isEmail($_POST['ecardRecipientEmail']) ? $_POST['ecardRecipientEmail'] : ''; if (empty($senderEmail) || empty($recipientEmail)) { $this->_objTpl->setVariable(array('STATUS_MESSAGE' => $_ARRAYLANG['TXT_ECARD_SENDING_ERROR'])); return false; } $query = "\n SELECT `setting_name`, `setting_value`\n FROM " . DBPREFIX . "module_ecard_settings"; $objResult = $objDatabase->Execute($query); while (!$objResult->EOF) { switch ($objResult->fields['setting_name']) { case 'validdays': $validdays = $objResult->fields['setting_value']; break; // Never used // case 'greetings': // $greetings = $objResult->fields['setting_value']; // break; // Never used // case 'greetings': // $greetings = $objResult->fields['setting_value']; // break; case 'subject': $subject = $objResult->fields['setting_value']; break; case 'emailText': $emailText = strip_tags($objResult->fields['setting_value']); break; } $objResult->MoveNext(); } $timeToLife = $validdays * 86400; // Replace placeholders with used in notification mail with user data $emailText = str_replace('[[ECARD_RECIPIENT_SALUTATION]]', $recipientSalutation, $emailText); $emailText = str_replace('[[ECARD_RECIPIENT_NAME]]', $recipientName, $emailText); $emailText = str_replace('[[ECARD_RECIPIENT_EMAIL]]', $recipientEmail, $emailText); $emailText = str_replace('[[ECARD_SENDER_NAME]]', $senderName, $emailText); $emailText = str_replace('[[ECARD_SENDER_EMAIL]]', $senderEmail, $emailText); $emailText = str_replace('[[ECARD_VALID_DAYS]]', $validdays, $emailText); $emailText = str_replace('[[ECARD_URL]]', $url, $emailText); $body = $emailText; // Insert ecard to DB $query = "\n INSERT INTO `" . DBPREFIX . "module_ecard_ecards` (\n code, date, TTL, salutation,\n senderName, senderEmail,\n recipientName, recipientEmail,\n message\n ) VALUES (\n '" . $code . "',\n '" . time() . "',\n '" . $timeToLife . "',\n '" . addslashes($recipientSalutation) . "',\n '" . addslashes($senderName) . "',\n '" . $senderEmail . "',\n '" . addslashes($recipientName) . "',\n '" . $recipientEmail . "',\n '" . $message . "');"; if ($objDatabase->Execute($query)) { $query = "\n SELECT setting_value\n FROM " . DBPREFIX . "module_ecard_settings\n WHERE setting_name='motive_{$id}'"; $objResult = $objDatabase->SelectLimit($query, 1); // Copy motive to new file with $code as filename $fileExtension = preg_replace('/^.+(\\.[^\\.]+)$/', '$1', $objResult->fields['setting_value']); $fileName = $objResult->fields['setting_value']; $objFile = new \File(); if ($objFile->copyFile(ASCMS_ECARD_OPTIMIZED_PATH . '/', $fileName, ASCMS_ECARD_SEND_ECARDS_PATH . '/', $code . $fileExtension)) { $objMail = new \phpmailer(); // Check e-mail settings if ($_CONFIG['coreSmtpServer'] > 0 && @(include_once ASCMS_CORE_PATH . '/SmtpSettings.class.php')) { $objSmtpSettings = new \SmtpSettings(); if (($arrSmtp = $objSmtpSettings->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']; } } // Send notification mail to ecard-recipient $objMail->CharSet = CONTREXX_CHARSET; $objMail->From = $senderEmail; $objMail->FromName = $senderName; $objMail->AddReplyTo($senderEmail); $objMail->Subject = $subject; $objMail->IsHTML(false); $objMail->Body = $body; $objMail->AddAddress($recipientEmail); if ($objMail->Send()) { $this->_objTpl->setVariable(array('STATUS_MESSAGE' => $_ARRAYLANG['TXT_ECARD_HAS_BEEN_SENT'])); } else { $this->_objTpl->setVariable(array('STATUS_MESSAGE' => $_ARRAYLANG['TXT_ECARD_MAIL_SENDING_ERROR'])); } } } else { $this->_objTpl->setVariable(array('STATUS_MESSAGE' => $_ARRAYLANG['TXT_ECARD_SENDING_ERROR'])); } }
/** * Reports a possible intrusion attempt to the administrator * @param $type The type of intrusion attempt to report. * @param $file The file requesting the report (defaults to "Filename not available") * @param $line The line number requesting the report (defaults to "Linenumber not available") **/ function reportIntrusion($type, $file = "Filename not available", $line = "Linenumber not available") { $objDatabase = \Env::get('db'); $config = \Env::get('config'); $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "Not set"; $httpxforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : "Not set"; $httpvia = isset($_SERVER['HTTP_VIA']) ? $_SERVER['HTTP_VIA'] : "Not set"; $httpclientip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : "Not set"; $gethostbyname = gethostbyname($remoteaddr); if ($gethostbyname == $remoteaddr) { $gethostbyname = "No matching hostname"; } // Add all the user's info to $user $user = "******" . "HTTP_X_FORWARDED_FOR : {$httpxforwardedfor}\r\n" . "HTTP_VIA : {$httpvia}\r\n" . "HTTP_CLIENT_IP : {$httpclientip}\r\n" . "GetHostByName : {$gethostbyname}\r\n"; // Add all requested information foreach ($this->criticalServerVars as $serverVar) { $_SERVERlite[$serverVar] = $_SERVER[$serverVar]; } $httpheaders = function_exists('getallheaders') ? getallheaders() : null; $gpcs = ""; $gpcs .= $this->getRequestInfo($httpheaders, "HTTP HEADER"); $gpcs .= $this->getRequestInfo($_REQUEST, "REQUEST"); $gpcs .= $this->getRequestInfo($_GET, "GET"); $gpcs .= $this->getRequestInfo($_POST, "POST"); $gpcs .= $this->getRequestInfo($_SERVERlite, "SERVER"); $gpcs .= $this->getRequestInfo($_COOKIE, "COOKIE"); $gpcs .= $this->getRequestInfo($_FILES, "FILES"); $gpcs .= $this->getRequestInfo($_SESSION, "SESSION"); // Get the data to insert in the database $cdate = time(); $dbuser = htmlspecialchars(addslashes($user), ENT_QUOTES, CONTREXX_CHARSET); $dbuser = mysql_escape_string($dbuser); $dbgpcs = htmlspecialchars(addslashes($gpcs), ENT_QUOTES, CONTREXX_CHARSET); $dbgpcs = mysql_escape_string($dbgpcs); $where = addslashes("{$file} : {$line}"); $where = mysql_escape_string($where); // Insert the intrusion in the database $objDatabase->Execute("INSERT INTO " . DBPREFIX . "ids (timestamp, type, remote_addr, http_x_forwarded_for, http_via, user, gpcs, file)\n VALUES(" . $cdate . ", '" . $type . "', '" . $remoteaddr . "', '" . $httpxforwardedfor . "', '" . $httpvia . "', '" . $dbuser . "', '" . $dbgpcs . "', '" . $where . "')"); // The headers for the e-mail $emailto = $config['coreAdminName'] . " <" . $config['coreAdminEmail'] . ">"; // The message to send $message = "DATE : {$cdate}\r\nFILE : {$where}\r\n\r\n{$user}\r\n\r\n{$gpcs}"; // Send the e-mail to the administrator 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')) { 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 = $config['coreAdminName']; $objMail->AddReplyTo($config['coreAdminEmail']); $objMail->Subject = $_SERVER['HTTP_HOST'] . " : {$type}"; $objMail->IsHTML(false); $objMail->Body = $message; $objMail->AddAddress($emailto); $objMail->Send(); } }
/** * 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; }
/** * 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'])); $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->From = $sendermail; $objMail->FromName = $sendername; $objMail->AddReplyTo($sendermail); $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(); } }
/** * 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; }
$mailbody .= "Browser: " . getenv("HTTP_USER_AGENT") . "\n\n"; $use_phpmailer = false; // true: uses php mailer | false: uses the default mail() function // We are going to check the fields... if (check_email_address($email) and check_value($name) and check_value($message)) { // Waht are we using? if ($use_phpmailer) { // Hail PHPMailer! require_once __CHV_PATH_CLASSES__ . 'class.phpmailer.php'; $mail = new phpmailer(); $mail->Subject = $subject; $mail->Body = $mailbody; $mail->From = $from; $mail->FromName = $name . ' (contact form)'; $mail->AddAddress($to); $mail->AddReplyTo($email); // indicates ReplyTo headers $mail->Mailer = "mail"; // mail|smtp|sendmail //$mail->Host = ''; // SMTP host //$mail->SMTPAuth = true; // Turn on SMTP auth (use when SMTP needs to indicate the user:password //$mail->SMTPSecure = 'ssl'; // Values: ssl|tls //$mail->Username = ''; // For SMTPAuth //$mail->Password = ''; // For SMTPAuth //$mail->SMTPDebug = 1; // Problems sending with SMTP? Uncomment this line to get the debug. $mail->Timeout = 30; $success = $mail->Send(); } else { $success = mail($to, $subject, $mailbody, 'From: ' . $email); // $to, $subject, $mailbody }
/** * 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; }
/** * Always use this function for all emails to users * * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email * @param object $userfrom user object to send email from. If null, email will come from mahara * @param string $subject email subject * @param string $messagetext text version of email * @param string $messagehtml html version of email (will send both html and text) * @param array $customheaders email headers * @throws EmailException */ function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml = '', $customheaders = null) { if (!get_config('sendemail')) { // You can entirely disable Mahara from sending any e-mail via the // 'sendemail' configuration variable return true; } if (empty($userto)) { throw new InvalidArgumentException("empty user given to email_user"); } require_once 'phpmailer/class.phpmailer.php'; $mail = new phpmailer(); // Leaving this commented out - there's no reason for people to know this //$mail->Version = 'Mahara ' . get_config('release'); $mail->PluginDir = get_config('libroot') . 'phpmailer/'; $mail->CharSet = 'UTF-8'; $smtphosts = get_config('smtphosts'); if ($smtphosts == 'qmail') { // use Qmail system $mail->IsQmail(); } else { if (empty($smtphosts)) { // use PHP mail() = sendmail $mail->IsMail(); } else { $mail->IsSMTP(); // use SMTP directly $mail->Host = get_config('smtphosts'); if (get_config('smtpuser')) { // Use SMTP authentication $mail->SMTPAuth = true; $mail->Username = get_config('smtpuser'); $mail->Password = get_config('smtppass'); } } } if (empty($userfrom)) { $mail->Sender = get_config('noreplyaddress'); $mail->From = $mail->Sender; $mail->FromName = get_string('emailname'); $customheaders[] = 'Precedence: Bulk'; // Try to avoid pesky out of office responses $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n"; if ($messagehtml) { $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n"; } } else { $mail->Sender = $userfrom->email; $mail->From = $mail->Sender; $mail->FromName = display_name($userfrom, $userto); } $replytoset = false; if (!empty($customheaders) && is_array($customheaders)) { foreach ($customheaders as $customheader) { $mail->AddCustomHeader($customheader); if (0 === stripos($customheader, 'reply-to')) { $replytoset = true; } } } if (!$replytoset) { $mail->AddReplyTo($mail->From, $mail->FromName); } $mail->Subject = substr(stripslashes($subject), 0, 900); if ($to = get_config('sendallemailto')) { // Admins can configure the system to send all email to a given address // instead of whoever would receive it, useful for debugging. $mail->addAddress($to); $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email); $messagetext = $notice . "\n\n" . $messagetext; if ($messagehtml) { $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml; } } else { $usertoname = display_name($userto, $userto); $mail->AddAddress($userto->email, $usertoname); } $mail->WordWrap = 79; if ($messagehtml) { $mail->IsHTML(true); $mail->Encoding = 'quoted-printable'; $mail->Body = $messagehtml; $mail->AltBody = $messagetext; } else { $mail->IsHTML(false); $mail->Body = $messagetext; } if ($mail->Send()) { return true; } throw new EmailException("Couldn't send email to {$usertoname} with subject {$subject}. " . "Error from phpmailer was: " . $mail->ErrorInfo); }