function sendmail($subject, $mailcontent, $receiver, $receivername, $attachment = "") { if (strpos($_SERVER['HTTP_HOST'], "localhost")) { return false; } $mail = new phpmailer(); $mail->IsSMTP(); $mail->Host = "mail.pepool.com"; $mail->Port = 2525; $mail->SMTPAuth = true; $mail->Username = "******"; // Write SMTP username in "" $mail->Password = "******"; $mail->Mailer = "smtp"; $mail->IsHTML(true); $mail->ClearAddresses(); $mail->From = "*****@*****.**"; $mail->FromName = "pepool"; $mail->Subject = $subject; $mail->Body = $mailcontent; $mail->AddAddress($receiver, $receivername); if ($attachment != '') { $mail->AddAttachment($attachment); } $suc = $mail->Send(); return $suc > 0; }
/** * Activate a given user. * @param $id Identifier of user. * @param $activationKey Activation key for user. */ function activateUser($id, $activationKey) { if (!empty($id) && !empty($activationKey)) { global $dbi; global $lActivate; $result = $dbi->query("SELECT username,activationKey FROM " . userTableName . " WHERE id=" . $dbi->quote($id)); if ($result->rows()) { list($username, $activationKeyDB) = $result->fetchrow_array(); if ($activationKey == $activationKeyDB) { $dbi->query("UPDATE " . userTableName . " SET registered=registered,lastUpdated=lastUpdated,lastLogged=lastLogged,activated=1,activationKey='' WHERE id=" . $dbi->quote($id)); // Send confirmation email $result = $dbi->query("SELECT name,email FROM " . userDataTableName . " WHERE id=" . $dbi->quote($id)); if ($result->rows()) { list($name, $email) = $result->fetchrow_array(); // Send activation email $mail = new phpmailer(); $mail->CharSet = "UTF-8"; $mail->Sender = pageAdminMail; $mail->From = pageAdminMail; $mail->FromName = pageTitle; $mail->Subject = $lActivate["MailSubject"]; $mail->Body = sprintf($lActivate["MailMessage"], $name, $username); $mail->IsHTML(false); $mail->AddAddress($email); $mail->Send(); } echo '<p>' . $lActivate["HeaderText"] . '</p>'; } else { echo '<p>' . $lActivate["HeaderTextError"] . '</p>'; } } } }
function f_SEND($t_email = '', $t_asunto = '', $t_contenido) { require_once '../modelo/phpmailer/class.phpmailer.php'; $a_email = new phpmailer(); $a_email->Mailer = "smtp"; $a_email->Host = ""; $a_email->SMTPAuth = true; $a_email->Port = '465'; $a_email->CharSet = 'utf8'; $a_email->Username = ''; $a_email->Password = ''; $a_email->From = ''; $a_email->FromName = '' . utf8_decode(''); //escribir la el contenido del correo //dirección destino $a_correo = '' . $t_email; $a_email->addAddress($a_correo); $a_email->Subject = '' . utf8_decode('' . $t_asunto); $a_email->AddEmbeddedImage('../imagenes/inen_header.png', 'logoinen', 'inen_header.png'); $a_email->IsHTML(true); $a_email->Body = "<p><img src=\"cid:logoinen\" /></p><p>" . utf8_decode('' . $t_contenido) . "</p>"; $a_email->AltBody = ' '; if ($a_email->send()) { echo "</br>Mensaje enviado correctamente.</br>"; } else { echo "<br/><strong>Información:</strong><br/>" . $a_email->ErrorInfo; } }
/** * Send mail, similar to PHP's mail * * A true return value does not automatically mean that the user received the * email successfully. It just only means that the method used was able to * process the request without any errors. * * The default content type is 'text/plain' which does not allow using HTML. */ public static function send($from_email, $from_name, array $to, $subject, $message, array $cc = array(), array $bcc = array(), array $attachments = array()) { $mailer = new phpmailer(); $content_type = 'text/plain'; $mailer->ContentType = $content_type; $mailer->Hostname = \lib\conf\constants::$domain; $mailer->IsMail(); $mailer->IsHTML(false); $mailer->From = $from_email; $mailer->FromName = $from_name; // add recipients foreach ((array) $to as $recipient_name => $recipient_email) { $mailer->AddAddress(trim($recipient_email), trim($recipient_name)); } // Add any CC and BCC recipients foreach ($cc as $recipient_name => $recipient_email) { $mailer->AddCc(trim($recipient_email), trim($recipient_name)); } foreach ($bcc as $recipient_name => $recipient_email) { $mailer->AddBcc(trim($recipient_email), trim($recipient_name)); } // Set mail's subject and body $mailer->Subject = $subject; $mailer->Body = $message; foreach ($attachments as $attachment) { $mailer->AddAttachment($attachment); } // Send! $result = $mailer->Send(); return $result; }
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; }
public function proc_upd() { $obj = ormPages::get(system::POST('obj_id')); $obj->tabuList('pseudo_url', 'h1', 'keywords', 'title', 'description', 'active', 'is_home_page', 'view_in_menu', 'view_submenu', 'in_search', 'in_index', 'in_new_window', 'other_link', 'img_act', 'img_no_act', 'img_h1'); $obj->loadFromPost(); // Публикация на сайте if (system::POST('publ', isBool)) { if ($obj->isInheritor('faq') && $obj->newVal('answer') == '') { ui::MessageBox(lang::get('TEXT_MESSAGE_ERROR'), lang::get('FEEDBACK_MSG_3')); ui::selectErrorFields(array('select' => '', 'focus' => 'answer')); } else { $obj->active = 1; } } $obj_id = $obj->save(); // Если объект не сохранился, выводим пользователю текст ошибки. if ($obj_id === false) { system::savePostToSession(); ui::MessageBox(lang::get('TEXT_MESSAGE_ERROR'), $obj->getErrorListText()); ui::selectErrorFields($obj->getErrorFields()); system::redirect('/feedback/message_upd/' . $_POST['obj_id']); } if (system::POST('send_to_email', isBool) && !$obj->send_answer_to_user && ($form_obj = ormObjects::get($obj->form_id))) { if ($form_obj->send_answer) { if ($obj->answer != '') { $fields = $obj->getClass()->loadFields(); while (list($num, $field) = each($fields)) { if (!empty($field['f_sname'])) { page::assign($field['f_sname'], $obj->__get($field['f_sname'])); } } page::assign('site_name', domains::curDomain()->getSiteName()); page::assign('base_email', domains::curDomain()->getEmail()); $mail = new phpmailer(); $mail->From = $this->parse($form_obj->answer_sender_address); $mail->FromName = $this->parse($form_obj->answer_sender_name); $mail->AddAddress($obj->email); $mail->WordWrap = 50; $mail->IsHTML(true); $mail->Subject = $this->parse($form_obj->answer_subject); $mail->Body = $this->parse($form_obj->answer_template); $mail->Send(); // Помечаем, что ответ отправлен $obj->send_answer_to_user = 1; $obj->save(); ui::MessageBox(lang::get('FEEDBACK_MSG_1'), ''); } else { ui::MessageBox(lang::get('TEXT_MESSAGE_ERROR'), lang::get('FEEDBACK_MSG_2')); ui::selectErrorFields(array('select' => '', 'focus' => 'answer')); } } } // Если данные изменились корректно перенаправляем на соответствующию страницу if ($_POST['parram'] == 'apply') { system::redirect('/feedback/message_upd/' . $obj_id); } else { system::redirect('/feedback'); } }
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; }
* @param string mailto address * @param string mail content * @param array word replace rules * */ public static function autosend($mailto, $content, $replace = null) { foreach ($replace as $k => $v) { $content = str_replace($k, $v, $content); } $to = array(); if (is_string($mailto)) { $to[0] = $mailto; } assert(trim($mailto) == ''); Mail::_send($to, $content); } /** * Basic send function. * @param array mailto list * @param string content * @param array attachment path list */ private static function _send($mailto, $content, $title = '', $attachment = null) { require_once 'phpmailer/class.phpmailer.php'; #echo "Begin!<br/>"; if ($title == '') { $title = '来自IBM Power大赛官方的自动邮件,请勿直接回复本邮件。'; } $mail = new phpmailer(); // defaults to using php "mail()" $mail->IsSmtp(); // telling the class to use SendMail transport #$body = 'hello cxj!<br/>'; #$body = eregi_replace("[\]",'',$body); $config = C('PHPMAILER'); $address = $config['FROM']; $password = $config['PASSWORD']; $smtp = $config['HOST']; $port = $config['PORT']; #$mail->AddReplyTo($address,"First Last"); foreach ($mailto as $m) { $mail->AddAddress($m, "Power大赛参赛选手 {$m} "); } $mail->SMTPAuth = true; //$mail->from = $address; //$mail->to = $address; $mail->smtpsecure = 'ssl'; $mail->From = $address;
/** * Constructor * * @param ctrl_abstract $ctrl * */ public function __construct(ctrl_abstract $ctrl = null) { $args = func_get_args(); /* $ctrl = */ array_shift($args); parent::__construct($args); $this->add_controller = $ctrl; }
function a2b_mail($to, $subject, $mail_content, $from = 'root@localhost', $fromname = '', $contenttype = 'multipart/alternative') { $mail = new phpmailer(); $mail->From = $from; $mail->FromName = $fromname; //$mail -> IsSendmail(); //$mail -> IsSMTP(); $mail->Subject = $subject; $mail->Body = nl2br($mail_content); //$HTML; $mail->AltBody = $mail_content; // Plain text body (for mail clients that cannot read HTML) // if ContentType = multipart/alternative -> HTML will be send $mail->ContentType = $contenttype; $mail->AddAddress($to); $mail->Send(); }
function sendList($list) { // send email of message global $loader, $intl, $conf; $loader->import('saf.Ext.phpmailer'); $mail = new phpmailer(); $mail->IsMail(); $mail->IsHTML(true); foreach ($list as $item) { if (strtoupper($item->type) == 'TASK') { $id = 'T' . $item->id; } elseif (strtoupper($item->type) == 'MESSAGE') { $id = 'M' . $item->id; } else { $id = strtoupper(substr($item->type, 0, 1)) . $item->id; } $mail->From = $conf['Messaging']['return_address']; //$mail->Subject = '[' . $this->id . '] ' . $this->subject; //$mail->Body = $this->body; $mail->AddAddress($item->address); if (defined('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_SUBJECT')) { $mail->Subject = $intl->get(constant('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_SUBJECT'), $item->struct); } else { $mail->Subject = '[' . $id . '] ' . $item->subject; } if (defined('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_BODY')) { $mail->Body = $intl->get(constant('WORKSPACE_' . strtoupper($item->type) . '_' . strtoupper($this->name) . '_BODY'), $item->struct); } else { $mail->Body = $item->body; } if ($item->priority == 'urgent' || $item->priority == 'high') { $mail->Priority = 1; } else { $mail->Priority = 3; } if (!$mail->Send()) { $this->error = $mail->ErrorInfo; return false; } $mail->ClearAddresses(); $mail->ClearAttachments(); } return true; }
/** * конструктор * * инициирует необходимые параметры в свойствах родительского класса * * @return void */ public function __construct() { parent::__construct(); $this->CharSet = CONF_DEFAULT_CHARSET; $this->Host = CONF_MAIL_SMTP_HOST; $this->Port = CONF_MAIL_SMTP_PORT; $this->Username = CONF_MAIL_SMTP_USER; $this->Password = CONF_MAIL_SMTP_PASS; $this->SMTPAuth = true; 'smtp' === CONF_MAIL_METHOD ? $this->IsSMTP() : $this->IsMail(); CONF_MAIL_FORMAT_HTML ? $this->IsHTML(true) : $this->IsHTML(false); }
protected function sendEmail($to, $subject, $body) { include_once '../../libraries/phpmailer/class.phpmailer.php'; if (empty($to)) { return false; } $mail = new phpmailer(); $mail->PluginDir = '../../libraries/phpmailer'; $mail->CharSet = 'UTF-8'; $mail->Subject = substr(stripslashes($subject), 0, 900); $mail->From = '*****@*****.**'; $mail->FromName = 'ARIS Mailer'; $mail->AddAddress($to, 'ARIS Author'); $mail->MsgHTML($body); $mail->WordWrap = 79; if ($mail->Send()) { return true; } else { return false; } }
function send_mail($email, $date, $time) { require '../phpmailer/PHPMailerAutoload.php'; $mail = new phpmailer(); $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = '******'; $mail->Password = '******'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->setFrom('*****@*****.**', 'Mailer'); $mail->addAddress('' . $email . '', 'user'); $mail->isHTML(true); $mail->Subject = 'booking'; $mail->Body = 'This email is coming from global styling to: ' . $email . ' </br> your booking is set for ' . $date . ' at ' . $time . ' thank you for booking with us. Global Styling'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if (!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent to your E-Mail address'; } }
function send($newsletter_id) { global $db; $owpDBTable = owpDBGetTables(); $send_mail = new phpmailer(); $send_mail->From = OWP_EMAIL_ADDRESS; $send_mail->FromName = OWP_NAME; $send_mail->Subject = $this->title; $sql = "SELECT admin_gender, admin_firstname, admin_lastname,\n admin_email_address \n FROM " . $owpDBTable['administrators'] . " \n WHERE admin_newsletter = '1'"; $mail_values = $db->Execute($sql); while ($mail = $mail_values->fields) { $send_mail->Body = $this->content; $send_mail->AddAddress($mail['admin_email_address'], $mail['admin_firstname'] . ' ' . $mail['admin_lastname']); $send_mail->Send(); // Clear all addresses and attachments for next loop $send_mail->ClearAddresses(); $send_mail->ClearAttachments(); $mail_values->MoveNext(); } $today = date("Y-m-d H:i:s"); $db->Execute("UPDATE " . $owpDBTable['newsletters'] . " \n SET date_sent = " . $db->DBTimeStamp($today) . ",\n status = '1' \n WHERE newsletters_id = '" . owpDBInput($newsletter_id) . "'"); }
function send() { // send email of message global $loader, $intl, $conf; $loader->import('saf.Ext.phpmailer'); $mail = new phpmailer(); $mail->IsMail(); if (strtoupper($this->type) == 'TASK') { $this->id = 'T' . $this->id; } elseif (strtoupper($this->type) == 'MESSAGE') { $this->id = 'M' . $this->id; } else { $this->id = strtoupper(substr($this->type, 0, 1)) . $this->id; } $mail->From = $conf['Messaging']['return_address']; if (defined('WORKSPACE_' . strtoupper($this->type) . '_' . strtoupper($this->name) . '_SUBJECT')) { $mail->Subject = $intl->get(constant('WORKSPACE_' . strtoupper($this->type) . '_' . strtoupper($this->name) . '_SUBJECT'), $this); } else { $mail->Subject = '[' . $this->id . '] ' . $intl->get('Notice'); } if (defined('WORKSPACE_' . strtoupper($this->type) . '_' . strtoupper($this->name) . '_BODY')) { $mail->Body = $intl->get(constant('WORKSPACE_' . strtoupper($this->type) . '_' . strtoupper($this->name) . '_BODY'), $this); } else { $mail->Body = $this->subject; } // message body should be less than $this->charlimit characters $mail->Body = substr($mail->Body, 0, $this->charlimit); $mail->AddAddress($this->address); if ($this->priority == 'urgent' || $this->priority == 'high') { $mail->Priority = 1; } if ($mail->Send()) { return true; } $this->error = $mail->ErrorInfo; return false; }
function send_email($content) { require "PHPMailer/class.phpmailer.php"; //Instanciamos un objeto de la clase phpmailer $mail = new phpmailer(); //Indicamos a la clase phpmailer donde se encuentra la clase smtp //$mail->PluginDir = ""; //Indicamos que vamos a conectar por smtp $mail->Mailer = "smtp"; $mail->CharSet = "UTF-8"; //Nuestro servidor smtp. Como ves usamos cifrado ssl $mail->Host = "ssl://smtp.gmail.com"; //Puerto de gmail 465 $mail->Port = "465"; //Le indicamos que el servidor smtp requiere autenticación $mail->SMTPAuth = true; //Le decimos cual es nuestro nombre de usuario y password $mail->Username = "******"; $mail->Password = "******"; //Indicamos cual es nuestra dirección de correo y el nombre que //queremos que vea el usuario que lee nuestro correo $mail->From = "*****@*****.**"; $mail->FromName = "Nuevo registro en iNBest"; //El valor por defecto de Timeout es 10, le voy a dar un poco mas $mail->Timeout = 30; //Indicamos cual es la dirección de destino del correo. $mail->AddAddress("*****@*****.**"); //$mail->AddCC("*****@*****.**"); //Asignamos asunto $mail->Subject = "Nuevo Registro a través del sitio de iNBest - Solicita más Información"; //Cuerpo del mensaje. Puede contener html $mail->Body = $content; //Si no admite html $mail->AltBody = "Cuerpo de mensaje solo texto"; //Envia en email $resultado = $mail->Send(); }
function forgotPassword(&$Model, $email) { $user = $Model->find("User.email = '" . $email . "'"); if ($user) { $id = $user['User']['id']; $mail = new phpmailer(); $mail->AddAddress($user['User']['email'], $user['User']['username']); $mail->FromName = Configure::read('SparkPlug.administrator.from_name'); $mail->From = Configure::read('SparkPlug.administrator.email'); $mail->Subject = 'Password Reset'; $password = $user['User']['password']; $salt = Configure::read("Security.salt"); $activate_key = md5($password . $salt); $link = Router::url("/users/activate_password?ident={$id}&activate={$activate_key}", true); $mail->Body = "Dear " . $user['User']['username'] . ",\n\nKindly click the link below:\n" . $link . "\n\t\nThen set your password.\n\nRegards,\nSite Admin"; if ($Model->useDbConfig != 'test_suite') { $mail->Send(); } $Model->lastResetPassword = array('id' => $id, 'password' => $password); return true; } else { return false; } }
public function sendmail($from, $to, $subject, $body, $altbody = null, $options = null, $attachments = null, $html = false) { if (!is_array($from)) { $from = array($from, $from); } $mail = new phpmailer(); $mail->PluginDir = 'M/lib/phpmailer/'; if ($this->getConfig('smtp')) { $mail->isSMTP(); $mail->Host = $this->getConfig('smtphost'); if ($this->getConfig('smtpusername')) { $mail->SMTPAuth = true; $mail->Port = $this->getConfig('smtpport') ? $this->getConfig('smtpport') : 25; $mail->SMTPDebug = $this->smtpdebug; $mail->Username = $this->getConfig('smtpusername'); $mail->Password = $this->getConfig('smtppassword'); } } $mail->CharSet = $this->getConfig('encoding'); $mail->AddAddress($to); $mail->Subject = $subject; $mail->Body = $note . $body; $mail->AltBody = $altbody; if (!is_array($from)) { $from = array($from, $from); } $mail->From = $from[0]; $mail->FromName = $from[1]; if (key_exists('reply-to', $options)) { $mail->AddReplyTo($options['reply-to']); unset($options['reply-to']); } if (key_exists('Sender', $options)) { $mail->Sender = $options['Sender']; } if (null != $attachments) { if (!is_array($attachments)) { $attachments = array($attachments); } foreach ($attachments as $k => $v) { if (!$mail->AddAttachment($v, basename($v))) { trigger_error("Attachment {$v} could not be added"); } } } $mail->IsHTML($html); $result = $mail->send(); }
function SendMail($email, $name, $subject, $message) { global $sockethost, $smtpauth, $smtpauthuser, $smtpauthpass, $socketfrom, $socketfromname, $socketreply, $socketreplyname; include 'class.phpmailer.php'; $mail = new phpmailer(); $mail->IsSMTP(); $mail->Host = $sockethost; if ($smtpauth == 'TRUE') { $mail->SMTPAuth = true; $mail->Username = $smtpauthuser; $mail->Password = $smtpauthpass; } if (isset($_GET['caseid']) && ($_GET['caseid'] == 'NewTicket' || $_GET['caseid'] == 'view')) { $mail->From = $email; $mail->FromName = $name; $mail->AddReplyTo($email, $name); } else { $mail->From = $socketfrom; $mail->FromName = $socketfromname; $mail->AddReplyTo($socketreply, $socketreplyname); } $mail->IsHTML(False); $mail->Body = $message; $mail->Subject = $subject; if (isset($_GET['caseid']) && ($_GET['caseid'] == 'NewTicket' || $_GET['caseid'] == 'view')) { $mail->AddAddress($socketfrom, $socketfromname); } else { $mail->AddAddress($email, $name); } if (!$mail->Send()) { return 'Error: ' . $mail->ErrorInfo; } else { return 'Email Sent.'; } $mail->ClearAddresses(); }
function fu_envia_clave($nom, $email, $email_ins, $user, $clave, $tipo) { require_once "class.phpmailer.php"; $mail = new phpmailer(); $mail->From = "*****@*****.**"; $mail->FromName = "Oficina Asesora de Sistemas"; $mail->Host = "mail.udistrital.edu.co"; $mail->Mailer = "smtp"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->Timeout = 120; $mail->Charset = "utf-8"; $mail->IsHTML(false); if ($tipo == 4) { $tip = "Coordinador"; } elseif ($tipo == 16) { $tip = "Decano"; } elseif ($tipo == 24) { $tip = "Funcionario"; } elseif ($tipo == 26) { $tip = "Proveedor"; } elseif ($tipo == 30) { $tip = "Docente"; } elseif ($tipo == 51) { $tip = "Estudiante"; } //echo "tipo en fua_ ".$tipo; exit; $fecha = date("d-M-Y h:i:s A"); $comen = "Mensaje generado automáticamente por el servidor de la Oficina Asesora de Sistemas.\n"; $comen .= "Este es su usuario y clave para ingresar al Sistema de Información Cóndor.\n\n"; $comen .= "Por seguridad cambie la clave.\n\n"; $sujeto = "Clave"; $cuerpo = "Fecha de envio: " . $fecha . "\n\n"; $cuerpo .= "Señor(a) : " . $nom . "\n\n"; $cuerpo .= $comen . "\n\n"; $cuerpo .= "Tipo: " . $tip . "\n"; $cuerpo .= "Usuario: " . $user . "\n"; $cuerpo .= "Clave Acceso: " . $clave . "\n"; $mail->Body = $cuerpo; $mail->Subject = $sujeto; $mail->AddAddress($email); $mail->AddCC($email_ins); if (!$mail->Send()) { header("Location: {$redir}?error_login=16"); } else { header("Location: {$redir}?error_login=18"); } $mail->ClearAllRecipients(); }
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"; } }
/** * * send email */ public function sendEmail($to, $subject = '', $body = '') { $to = filter_var($to, FILTER_SANITIZE_EMAIL); if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { return false; } // add email signature here $body .= gatorconf::get('mail_signature'); // use simple php mail instead of smtp if (gatorconf::get('use_smtp_protocol') !== true) { $from = gatorconf::get('mail_from_name') . ' <' . gatorconf::get('mail_from') . '>'; $headers = ''; $headers .= "From: {$from}\n"; $headers .= "Return-Path: {$from}\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; mail($to, $subject, $body, $headers); gator::writeLog('email link sent to: ' . $to); return; } require_once gatorconf::get('base_path') . "/include/phpmailer/class.phpmailer.php"; $mail = new phpmailer(true); try { $mail->SMTPDebug = gatorconf::get('mail_smtp_debug'); $mail->SMTPSecure = gatorconf::get('mail_smtp_connection_security'); $mail->IsSMTP(); // send via SMTP $mail->Host = gatorconf::get('mail_smtp_host'); // SMTP servers $mail->SMTPAuth = true; // turn on SMTP authentication $mail->Username = gatorconf::get('mail_smtp_username'); // SMTP username $mail->Password = gatorconf::get('mail_smtp_password'); // SMTP password $mail->From = gatorconf::get('mail_from'); $mail->FromName = gatorconf::get('mail_from_name'); $mail->AddAddress($to); $mail->Subject = $subject; $mail->Body = $body; $mail->Send(); gator::writeLog('email link sent to: ' . $to); } catch (phpmailerException $e) { echo $e->errorMessage(); //Pretty error messages from PHPMailer if (gatorconf::get('mail_smtp_debug')) { die; } } catch (Exception $e) { echo $e->getMessage(); //Boring error messages from anything else! if (gatorconf::get('mail_smtp_debug')) { die; } } return; }
/** * Устанавливает режим отправки письма как Text(Plain) * */ public function setPlain() { $this->oMailer->IsHTML(false); }
/** * 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; }
<?php /** * Created by PhpStorm. * User: Viry * Date: 17/11/2015 * Time: 01:42 PM */ require_once '../mail/class.phpmailer.php'; require "../mail/class.smtp.php"; $mail = new phpmailer(); $mail->PluginDir = '../mail/'; $mail->SMTPSecure = "tls"; $mail->Host = "smtp.gmail.com"; $mail->SMTPAuth = true; $mail->Username = "******"; $mail->Password = "******"; $mail->Port = 587; //puerto de autenticacion que usa gmail $mail->AddAddress("*****@*****.**"); $mail->IsHTML = true; $mail->MsgHTML('Recuperacion de Contraseña <br><br> Contraseña: <br><br> Ingresa a este Link: http://proyectospi.com/PuntodeEncuentroP/html/pages/forgot-password.html <br><br>para Ingresar a tu sesion con la contraseña que te enviamos en este correo.'); $mail->SetFrom("*****@*****.**", "Punto de Encuentro"); $mail > Subject == "Recuperacion de Contraseña"; //indico destinatario $exito = $mail->Send(); if (!$exito) { echo "Error al enviar: " . $mail > ErrorInfo; } else { echo "Mensaje enviado!"; }
if (strlen($_POST['myemail']) == 0) { $email = "Keine E-Mail Adresse"; } if (strlen($_POST['mymassage']) < 4) { $fehler = 2; } if (strlen($_POST['myname']) < 3) { $fehler = 1; } if (strlen($_POST['myhp']) == 0) { $homepage = "Keine eigene Homepage"; } if ($fehler == "") { $varresult = $db->query("INSERT INTO rhs_gaestebuch (mandant, name, datum, kommentar, email, homepage, icq, aim, yahoo) VALUES('" . $mandant['mandant_id'] . "', '" . $_POST['myname'] . "', '" . $datum . "', '" . $_POST['mymassage'] . "', '" . $_POST['myemail'] . "', '" . $_POST['myhp'] . "', '" . $_POST['myicq'] . "', '" . $_POST['myaim'] . "', '" . $_POST['myyahoo'] . "')"); $_GET['neu'] = 0; $mail = new phpmailer(); $mail->From = $_POST['sender_email']; $mail->FromName = $_POST['sender_email']; $mail->Mailer = "smtp"; $mail->Host = $smtp_mailhost; $mail->SMTPAuth = true; $mail->Username = $smtp_user; $mail->Password = $smtp_pw; $mail->Subject = "EMail vom " . $shopconfig['shopconfig_pagetitle'] . " Gästebuch"; $body = "Hallo " . $_POST['myname'] . ",\nvielen Dank für den Eintrag in unserem Gästebuch,\nName: " . $_POST['myname'] . "\nDatum: " . $datum . "\nEmail: " . $_POST['myemail'] . "\nHomepage: " . $_POST['myhp'] . "\nKommentar: " . $_POST['mymassage'] . "\nText: " . $_POST['text'] . "\n\nDas {$pagename} |" . $mandant['name'] . " Team"; $mail->Body = $body; $mail->AltBody = $body; $mail->AddAddress($_POST['myemail'], $_POST['myname']); $mail->AddCC($mandant['mandant_email'], $mandant['mandant_vorname'] . " " . $mandant['mandant_nachname']); @$mail->Send(); $mail->ClearAddresses();
/** * 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 = contrexx_raw2db($dbuser); $dbgpcs = htmlspecialchars(addslashes($gpcs), ENT_QUOTES, CONTREXX_CHARSET); $dbgpcs = contrexx_raw2db($dbgpcs); $where = addslashes("{$file} : {$line}"); $where = contrexx_raw2db($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->SetFrom($config['coreAdminEmail'], $config['coreAdminName']); $objMail->Subject = $_SERVER['HTTP_HOST'] . " : {$type}"; $objMail->IsHTML(false); $objMail->Body = $message; $objMail->AddAddress($emailto); $objMail->Send(); } }
/** * send a mail to the email with the message * * @static * @param integer $uploadId the upload id * @param string $subject the subject of the mail for the recipient * @param string $email the recipient's mail address * @param null|string $message the message for the recipient */ public static function sendMail($uploadId, $subject, $emails, $message = null) { global $objDatabase, $_CONFIG; /** * get all file ids from the last upload */ $objResult = $objDatabase->Execute("SELECT `id` FROM " . DBPREFIX . "module_filesharing WHERE `upload_id` = '" . intval($uploadId) . "'"); if ($objResult !== false && $objResult->RecordCount() > 0) { while (!$objResult->EOF) { $files[] = $objResult->fields["id"]; $objResult->MoveNext(); } } if (!is_int($uploadId) && empty($files)) { $files[] = $uploadId; } /** * init mail data. Mail template, Mailsubject and PhpMailer */ $objMail = $objDatabase->SelectLimit("SELECT `subject`, `content` FROM " . DBPREFIX . "module_filesharing_mail_template WHERE `lang_id` = " . FRONTEND_LANG_ID, 1, -1); $content = str_replace(array(']]', '[['), array('}', '{'), $objMail->fields["content"]); if (empty($subject)) { $subject = $objMail->fields["subject"]; } $cx = \Cx\Core\Core\Controller\Cx::instanciate(); if (\Env::get('ClassLoader')->loadFile($cx->getCodeBaseLibraryPath() . '/phpmailer/class.phpmailer.php')) { $objMail = new \phpmailer(); /** * Load mail template and parse it */ $objTemplate = new \Cx\Core\Html\Sigma('.'); $objTemplate->setErrorHandling(PEAR_ERROR_DIE); $objTemplate->setTemplate($content); $objTemplate->setVariable(array("DOMAIN" => $_CONFIG["domainUrl"], 'MESSAGE' => $message)); if ($objTemplate->blockExists('filesharing_file')) { foreach ($files as $file) { $objTemplate->setVariable(array('FILE_DOWNLOAD' => self::getDownloadLink($file))); $objTemplate->parse('filesharing_file'); } } if ($_CONFIG['coreSmtpServer'] > 0 && \Env::get('ClassLoader')->loadFile($cx->getCodeBaseCorePath() . '/SmtpSettings.class.php')) { if (($arrSmtp = SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->SetFrom($_CONFIG['coreAdminEmail'], $_CONFIG['coreGlobalPageTitle']); $objMail->Subject = $subject; $objMail->Body = $objTemplate->get(); foreach ($emails as $email) { $objMail->AddAddress($email); $objMail->Send(); $objMail->ClearAddresses(); } } }
function emailSend($data) { $stime = array_sum(explode(' ', microtime())); require_once "getmxrr.php"; $smtp =& $this->params; $mail = new phpmailer(); $mail->Mailer = "smtp"; $mail->From = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->FromName = isset($data['fromName']) & !empty($data['fromName']) ? $data['fromName'] : 'RuSoft'; $mail->Sender = isset($data['from']) & !empty($data['from']) ? $data['from'] : '*****@*****.**'; $mail->Host = $smtp['host']; $mail->CharSet = $smtp['charset']; $mail->Encoding = $smtp['encoding']; $mail->Port = $smtp['port']; $mail->SMTPAuth = $smtp['auth']; $mail->Subject = isset($data['subj']) & !empty($data['subj']) ? $data['subj'] : ''; if ($smtp['auth']) { $mail->Username = $smtp['user']; $mail->Password = $smtp['pass']; } // HTML body if (isset($data['mess']['html']) & !empty($data['mess']['html'])) { $body = $data['mess']['html']; $mail->isHTML(true); } // Plain text body (for mail clients that cannot read HTML) if (isset($data['mess']['text']) & !empty($data['mess']['text'])) { $text_body = $data['mess']['text']; $mail->isHTML(false); } $mail->AltBody = isset($text_body) ? $text_body : ''; $mail->Body = isset($body) ? $body : (isset($text_body) ? $text_body : ''); $i = 1; // порядковый номер файла //добавляем файлы прикрепленные файлы if (isset($data['attachment']) & !empty($data['attachment'])) { foreach ($data['attachment'] as $k => $item) { if (isset($item['binary']) & !empty($item['binary'])) { $mail->AddStringAttachment($item["binary"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } elseif (isset($item['path']) & !empty($item['path'])) { $mail->AddAttachment($item["path"], isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } // добавляем файлы, отображаемые на странице if (isset($data['embedded']) & !empty($data['embedded'])) { foreach ($data['embedded'] as $k => $item) { if (isset($item['path']) & !empty($item['path'])) { $mail->AddEmbeddedImage($item["path"], isset($item["cid"]) & !empty($item["cid"]) ? $item["cid"] : $i, isset($item["name"]) & !empty($item["name"]) ? $item["name"] : 'file' . $i, $smtp['encoding']); $i++; } } } //pr($mail); //на данном этапе имеется уже собранное письмо и нам необходимо определить mx серверы для отправки...для каждого письма. //чтобы повторно не искать серверы в момент отправки для каждого... //сохраняем для каждого домена один и тот же сервер $mxsrvs = array(); $mxemails = array(); $debug['ctime'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; foreach ($data['to'] as $email => $name) { //берем чисто host if (!$this->_is_valid_email($email)) { $debug['emails'][$email]['error'] = "неправильно указан email адрес."; continue; } $host = substr($email, strpos($email, "@") + 1); $domains = explode(".", $host); foreach ($domains as $level => $domain) { $address = implode(".", $domains); if (!key_exists($address, $mxsrvs)) { $time = array_sum(explode(' ', microtime())); if (getmxrr_portable($address, $mxhosts, $preference) == true) { array_multisort($preference, $mxhosts); } $debug['emails'][$email]['mxtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; if (!empty($mxhosts)) { $mxhosts[] = $smtp['host']; //потому что shadow тормознутый сервак if (in_array('shadow.rusoft.ru', $mxhosts)) { unset($mxhosts[0]); } //чтобы включить рассылку на smtp серверы получателей, необходимо закоментировать следующую строчку $mxhosts = array_reverse($mxhosts); $mxsrvs[$address] = $mxhosts; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; break; } else { unset($domains[$level]); } } else { $debug['emails'][$email]['mxtime'] = 'cache(0 ms)'; $mxemails[$email] =& $mxsrvs[$address]; $debug['emails'][$email]['mxsrvs'] =& $mxsrvs[$address]; } } } //получены все mx северы и теперь начинаем отправку по списку foreach ($mxemails as $email => $mxs) { //проверяем email адрес на существование и работу mx сервера //можно включить проверку, но это 1) замедляет, 2) вероятность очень низкая //$this->checkEmail($email, $mxs, $debug); $mail->AddAddress($email, $name); foreach ($mxs as $k => $host) { $mail->Host = $host; $time = array_sum(explode(' ', microtime())); $status = $mail->Send(); $debug['emails'][$email]['sendtime'] = round((array_sum(explode(' ', microtime())) - $time) * 1000, 2) . " ms"; $debug['emails'][$email]['status'] = $status; if ($status) { $debug['emails'][$email]['host'] = $host; break; } } $mail->ClearAddresses(); } $debug['time'] = round((array_sum(explode(' ', microtime())) - $stime) * 1000, 2) . " ms"; if (function_exists('log_notice')) { //скидываем в лог информацию о отправленных сообщениях $str = "<b>Были отправлены следующие сообщения:</b><br>Время генерации шалона для отправки: " . $debug['ctime'] . "<br>Общее время: " . $debug['time'] . "<br><b>Адреса:</b><br>"; foreach ($debug['emails'] as $k => $v) { $str .= "<br> <b><font color='blue'>" . $k . "</font></b>"; $str .= "<br> Определение smtp серверов: " . $v['mxtime']; $str .= "<br> Отправлено через: " . $v['host']; $str .= "<br> Время отправления: " . $v['sendtime']; $str .= "<br> Статус: " . ($v['status'] ? '<font color="green">успешно</font>' : '<font color="red">неудачно</font>'); } log_notice('email', false, $str); } //$status = true; // Clear attachments for next loop $mail->ClearAttachments(); if ($status) { return true; } return false; }