如何实现CDOSYS邮件系统

时间:2018-06-20 08:27:10

标签: php html email cdo.message cdo

我最近为一个客户启动了一个网站,他的网站托管不包括php的sendmail功能。主机建议我实施CDOSYS。有谁知道如何使这种事情起作用?我想以CDOSYS作为外部汇总表格。我真的很想使用PHPmailer,但是对于此客户端虚拟主机来说是不可能的。

我目前已将表单设置为通过PHPmailer发送,并带有错误消息验证器。因此,我需要更改它以使表单连接到CDOSYS并通过该.asp

发送邮件

/*!
 * Validator v0.11.5 for Bootstrap 3, by @1000hz
 * Copyright 2016 Cina Saffary
 * Licensed under http://opensource.org/licenses/MIT
 *
 * https://github.com/1000hz/bootstrap-validator
 */

+ function($) {
  'use strict';

  // VALIDATOR CLASS DEFINITION
  // ==========================

  function getValue($el) {
    return $el.is('[type="checkbox"]') ? $el.prop('checked') :
      $el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
      $el.val()
  }

  var Validator = function(element, options) {
    this.options = options
    this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
    this.$element = $(element)
    this.$btn = $('button[type="submit"], input[type="submit"]')
      .filter('[form="' + this.$element.attr('id') + '"]')
      .add(this.$element.find('input[type="submit"], button[type="submit"]'))

    this.update()

    this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
    this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
    this.$element.on('reset.bs.validator', $.proxy(this.reset, this))

    this.$element.find('[data-match]').each(function() {
      var $this = $(this)
      var target = $this.data('match')

      $(target).on('input.bs.validator', function(e) {
        getValue($this) && $this.trigger('input.bs.validator')
      })
    })

    this.$inputs.filter(function() {
      return getValue($(this))
    }).trigger('focusout')

    this.$element.attr('novalidate', true) // disable automatic native validation
    this.toggleSubmit()
  }

  Validator.VERSION = '0.11.5'

  Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)'

  Validator.FOCUS_OFFSET = 20

  Validator.DEFAULTS = {
    delay: 500,
    html: false,
    disable: true,
    focus: true,
    custom: {},
    errors: {
      match: 'Does not match',
      minlength: 'Not long enough'
    },
    feedback: {
      success: 'glyphicon-ok',
      error: 'glyphicon-remove'
    }
  }

  Validator.VALIDATORS = {
    'native': function($el) {
      var el = $el[0]
      if (el.checkValidity) {
        return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!")
      }
    },
    'match': function($el) {
      var target = $el.data('match')
      return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match
    },
    'minlength': function($el) {
      var minlength = $el.data('minlength')
      return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength
    }
  }

  Validator.prototype.update = function() {
    this.$inputs = this.$element.find(Validator.INPUT_SELECTOR)
      .add(this.$element.find('[data-validate="true"]'))
      .not(this.$element.find('[data-validate="false"]'))

    return this
  }

  Validator.prototype.onInput = function(e) {
    var self = this
    var $el = $(e.target)
    var deferErrors = e.type !== 'focusout'

    if (!this.$inputs.is($el)) return

    this.validateInput($el, deferErrors).done(function() {
      self.toggleSubmit()
    })
  }

  Validator.prototype.validateInput = function($el, deferErrors) {
    var value = getValue($el)
    var prevErrors = $el.data('bs.validator.errors')
    var errors

    if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')

    var e = $.Event('validate.bs.validator', {
      relatedTarget: $el[0]
    })
    this.$element.trigger(e)
    if (e.isDefaultPrevented()) return

    var self = this

    return this.runValidators($el).done(function(errors) {
      $el.data('bs.validator.errors', errors)

      errors.length ?
        deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el) :
        self.clearErrors($el)

      if (!prevErrors || errors.toString() !== prevErrors.toString()) {
        e = errors.length ?
          $.Event('invalid.bs.validator', {
            relatedTarget: $el[0],
            detail: errors
          }) :
          $.Event('valid.bs.validator', {
            relatedTarget: $el[0],
            detail: prevErrors
          })

        self.$element.trigger(e)
      }

      self.toggleSubmit()

      self.$element.trigger($.Event('validated.bs.validator', {
        relatedTarget: $el[0]
      }))
    })
  }


  Validator.prototype.runValidators = function($el) {
    var errors = []
    var deferred = $.Deferred()

    $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
    $el.data('bs.validator.deferred', deferred)

    function getValidatorSpecificError(key) {
      return $el.data(key + '-error')
    }

    function getValidityStateError() {
      var validity = $el[0].validity
      return validity.typeMismatch ? $el.data('type-error') :
        validity.patternMismatch ? $el.data('pattern-error') :
        validity.stepMismatch ? $el.data('step-error') :
        validity.rangeOverflow ? $el.data('max-error') :
        validity.rangeUnderflow ? $el.data('min-error') :
        validity.valueMissing ? $el.data('required-error') :
        null
    }

    function getGenericError() {
      return $el.data('error')
    }

    function getErrorMessage(key) {
      return getValidatorSpecificError(key) ||
        getValidityStateError() ||
        getGenericError()
    }

    $.each(this.validators, $.proxy(function(key, validator) {
      var error = null
      if ((getValue($el) || $el.attr('required')) &&
        ($el.data(key) || key == 'native') &&
        (error = validator.call(this, $el))) {
        error = getErrorMessage(key) || error!~errors.indexOf(error) && errors.push(error)
      }
    }, this))

    if (!errors.length && getValue($el) && $el.data('remote')) {
      this.defer($el, function() {
        var data = {}
        data[$el.attr('name')] = getValue($el)
        $.get($el.data('remote'), data)
          .fail(function(jqXHR, textStatus, error) {
            errors.push(getErrorMessage('remote') || error)
          })
          .always(function() {
            deferred.resolve(errors)
          })
      })
    } else deferred.resolve(errors)

    return deferred.promise()
  }

  Validator.prototype.validate = function() {
    var self = this

    $.when(this.$inputs.map(function(el) {
      return self.validateInput($(this), false)
    })).then(function() {
      self.toggleSubmit()
      self.focusError()
    })

    return this
  }

  Validator.prototype.focusError = function() {
    if (!this.options.focus) return

    var $input = this.$element.find(".has-error:first :input")
    if ($input.length === 0) return

    $('html, body').animate({
      scrollTop: $input.offset().top - Validator.FOCUS_OFFSET
    }, 250)
    $input.focus()
  }

  Validator.prototype.showErrors = function($el) {
    var method = this.options.html ? 'html' : 'text'
    var errors = $el.data('bs.validator.errors')
    var $group = $el.closest('.form-group')
    var $block = $group.find('.help-block.with-errors')
    var $feedback = $group.find('.form-control-feedback')

    if (!errors.length) return

    errors = $('<ul/>')
      .addClass('list-unstyled')
      .append($.map(errors, function(error) {
        return $('<li/>')[method](error)
      }))

    $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
    $block.empty().append(errors)
    $group.addClass('has-error has-danger')

    $group.hasClass('has-feedback') &&
      $feedback.removeClass(this.options.feedback.success) &&
      $feedback.addClass(this.options.feedback.error) &&
      $group.removeClass('has-success')
  }

  Validator.prototype.clearErrors = function($el) {
    var $group = $el.closest('.form-group')
    var $block = $group.find('.help-block.with-errors')
    var $feedback = $group.find('.form-control-feedback')

    $block.html($block.data('bs.validator.originalContent'))
    $group.removeClass('has-error has-danger has-success')

    $group.hasClass('has-feedback') &&
      $feedback.removeClass(this.options.feedback.error) &&
      $feedback.removeClass(this.options.feedback.success) &&
      getValue($el) &&
      $feedback.addClass(this.options.feedback.success) &&
      $group.addClass('has-success')
  }

  Validator.prototype.hasErrors = function() {
    function fieldErrors() {
      return !!($(this).data('bs.validator.errors') || []).length
    }

    return !!this.$inputs.filter(fieldErrors).length
  }

  Validator.prototype.isIncomplete = function() {
    function fieldIncomplete() {
      var value = getValue($(this))
      return !(typeof value == "string" ? $.trim(value) : value)
    }

    return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
  }

  Validator.prototype.onSubmit = function(e) {
    this.validate()
    if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
  }

  Validator.prototype.toggleSubmit = function() {
    if (!this.options.disable) return
    this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
  }

  Validator.prototype.defer = function($el, callback) {
    callback = $.proxy(callback, this, $el)
    if (!this.options.delay) return callback()
    window.clearTimeout($el.data('bs.validator.timeout'))
    $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
  }

  Validator.prototype.reset = function() {
    this.$element.find('.form-control-feedback')
      .removeClass(this.options.feedback.error)
      .removeClass(this.options.feedback.success)

    this.$inputs
      .removeData(['bs.validator.errors', 'bs.validator.deferred'])
      .each(function() {
        var $this = $(this)
        var timeout = $this.data('bs.validator.timeout')
        window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
      })

    this.$element.find('.help-block.with-errors')
      .each(function() {
        var $this = $(this)
        var originalContent = $this.data('bs.validator.originalContent')

        $this
          .removeData('bs.validator.originalContent')
          .html(originalContent)
      })

    this.$btn.removeClass('disabled')

    this.$element.find('.has-error, .has-danger, .has-success').removeClass('has-error has-danger has-success')

    return this
  }

  Validator.prototype.destroy = function() {
    this.reset()

    this.$element
      .removeAttr('novalidate')
      .removeData('bs.validator')
      .off('.bs.validator')

    this.$inputs
      .off('.bs.validator')

    this.options = null
    this.validators = null
    this.$element = null
    this.$btn = null

    return this
  }

  // VALIDATOR PLUGIN DEFINITION
  // ===========================


  function Plugin(option) {
    return this.each(function() {
      var $this = $(this)
      var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
      var data = $this.data('bs.validator')

      if (!data && option == 'destroy') return
      if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.validator

  $.fn.validator = Plugin
  $.fn.validator.Constructor = Validator


  // VALIDATOR NO CONFLICT
  // =====================

  $.fn.validator.noConflict = function() {
    $.fn.validator = old
    return this
  }


  // VALIDATOR DATA-API
  // ==================

  $(window).on('load', function() {
    $('form[data-toggle="validator"]').each(function() {
      var $form = $(this)
      Plugin.call($form, $form.data())
    })
  })

}(jQuery);
/*Contact Form CSS*/

.contact-form {}

.form-control {
  border: 1px solid #F15632;
  background-color: #EDEDED;
  border-radius: 4px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

.form-control:focus {
  color: #fff;
  background-color: #363636;
  border: 1px solid #F15632;
  box-shadow: none;
}

.help-block.with-errors {
  color: red !important;
}

textarea {
  resize: none;
}
<form method="POST" role="form" action="contact-2.php" class="contact-form row margin-top-0">
  <br/>
  <div class="container-fluid">
    <div class="row">
      <div class="m-auto">
        <div class="messages"></div>
      </div>
    </div>
    <!--END ROW-->
  </div>
  <!--END CONTAINER-->
  <div class="col-md-4">
    <div class="form-group">
      <label for="form_name"></label>
      <input name="name" type="text" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
      <div class="help-block with-errors"></div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="form-group">
      <label for="form_email"></label>
      <input name="email" type="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
      <div class="help-block with-errors"></div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="form-group">
      <label for="form_subject"></label>
      <select name="subject" type="text" class="form-control" id="exampleFormControlSelect1" required data-error="Specific Project Required">
        <option>Overall Projects</option>
        <option>Kitchen Projects</option>
        <option>Bar Projects</option>
        <option>Bathroom Projects</option>
        <option>Build in Closet Projects</option>
        <option>Koi Pond Projects</option>
        <option>Painting Projects</option>
        <option>Patio Projects</option>
        <option>Renovation Projects</option>
      </select>
      <div class="help-block with-errors"></div>
    </div>
  </div>
  <div class="col-md-12">
    <div class="form-group">
      <label for="form_message"></label>
      <textarea name="message" class="form-control" placeholder="Your Message*" rows="9" required data-error="Please,leave us a message."></textarea>
      <div class="help-block with-errors"></div>
    </div>
  </div>

  <div class="col-md-4 col-md-offset-4">
    <label></label>
    <button name="submit" type="submit" class="btn btn-dark btn-block btn-md btn-panel-form" data-loading-text="<span class='fa fa-spinner fa-spin'></span>Loading ...">Submit Form<!-- <i class="ion-android-arrow-forward"></i>--></button>
  </div>


</form>

<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/

require 'PHPMailer-master/PHPMailerAutoload.php';

/*
*  CONFIGURE EVERYTHING HERE
*/

// an email address that will be in the From field of the email.
/*$fromEmail = '';*/
$fromEmail = $_POST['email'];
$fromName = $_POST['name'];



/**Add Subject in header area of contact form**/

// an email address that will receive the email with the output of the form
$sendToEmail = 'demo@demo.com';
$sendToName = 'BH & SONS';

// subject of the email
/*$subject = 'bh & Sons contact form';*/
$subject = $_POST['subject'];

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Specific Project', 'message' => 'Message');

// message that will be displayed when everything is OK :)
$okMessage = '<strong>Contact form successfully submitted. Thank you, I will get back to you soon!</strong>';

// If something goes wrong, we will display this message.
$errorMessage = '<strong>There was an error while submitting the form. Please try again later</strong>';

/*
*  LET'S DO THE SENDING
*/

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);

try
{
    
    if(count($_POST) == 0) throw new \Exception('Form is empty');
    
    $emailTextHtml = "<h1>BH & SONS Contact Form!</h1><hr>";
    $emailTextHtml .= "<table>";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email
        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
/*    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a nice day,<br>Kind Regards,<br></p>";*/
    
    $mail = new PHPMailer(true);

    $mail->setFrom($fromEmail, $fromName, 0);
    $mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
/*    $mail->addReplyTo($_POST['email']);*/
    
    $mail->isHTML(true);

    $mail->Subject = $subject;
    $mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
    
    
    if(!$mail->send()) {
        throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
    }
    
    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    // $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}


// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    
    header('Content-Type: application/json');
    
    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

//This is what was send by the hosting company, I have absolutely no Idea on how to implement this?

<%@ LANGUAGE="VBSCRIPT" %>
<% option explicit %>
<% Response.Buffer = True %>

<!--
'*********************************************************************** 
'                         COPYRIGHT NOTICE								 
'   Code Example  :Self Submitting "Contact Us" Form Using CDOSYS
'   Author     :   Christopher Williams of								 
'                  www.CJWSoft.com and www.PowerASP.com					 
'																		 
' You can use this code anywhere as long as this copyright notice		 
' remains with the code													 
'															 
'   (c) Copyright 2000 - 2008 by CJWSoft / PowerASP	 All rights reserved 
'
' If you like this code please check out some of our ASP Based Applications
' such as ASPProtect and ASPBanner..  www.aspprotect.com / www.aspbanner.com
'
'*********************************************************************** 
-->

<%
'Declaring Variables
Dim smtpserver,youremail,yourpassword,ContactUs_Name,ContactUs_Email
Dim ContactUs_Subject,ContactUs_Body,Action,IsError
	
' Edit these 3 values accordingly
smtpserver = "hiro.aserv.co.za"
youremail = "bhsons@bhsons.co.za"
yourpassword = "g5G7tr5p"
	
' Grabbing variables from the form post
ContactUs_Name = Request("name")
ContactUs_Email = Request("email")
ContactUs_Subject = Request("subject")
ContactUs_Body = Request("message")
Action = Request("Action")
	
' Used to check that the email entered is in a valid format
Function IsValidEmail(Email)
	Dim ValidFlag,BadFlag,atCount,atLoop,SpecialFlag,UserName,DomainName,atChr,tAry1
	ValidFlag = False
		If (Email <> "") And (InStr(1, Email, "@") > 0) And (InStr(1, Email, ".") > 0) Then
			atCount = 0
			SpecialFlag = False
			For atLoop = 1 To Len(Email)
			atChr = Mid(Email, atLoop, 1)
				If atChr = "@" Then atCount = atCount + 1
				If (atChr >= Chr(32)) And (atChr <= Chr(44)) Then SpecialFlag = True
				If (atChr = Chr(47)) Or (atChr = Chr(96)) Or (atChr >= Chr(123)) Then SpecialFlag = True
				If (atChr >= Chr(58)) And (atChr <= Chr(63)) Then SpecialFlag = True
				If (atChr >= Chr(91)) And (atChr <= Chr(94)) Then SpecialFlag = True
			Next
			If (atCount = 1) And (SpecialFlag = False) Then
				BadFlag = False
				tAry1 = Split(Email, "@")
				UserName = tAry1(0)
				DomainName = tAry1(1)
			If (UserName = "") Or (DomainName = "") Then BadFlag = True
			If Mid(DomainName, 1, 1) = "." then BadFlag = True
			If Mid(DomainName, Len(DomainName), 1) = "." then BadFlag = True
				ValidFlag = True
			End If
		End If
		If BadFlag = True Then ValidFlag = False
		IsValidEmail = ValidFlag
End Function
%>

<html>

<head>
<title>Contact Us Form ( Powered By www.CJWSoft.com )</title>
</head>

<body style="font-family: Arial; font-size: 12px">

<%
If Action = "SendEmail" Then
	
	' Here we quickly check/validate the information entered
	' These checks could easily be improved to look for more things
	If IsValidEmail(ContactUs_Email) = "False" Then
		IsError = "Yes"
		Response.Write("<font color=""red"">You did not enter a valid email address.</font><br>")
	End If
	
	If ContactUs_Name = "" Then
		IsError = "Yes"
		Response.Write("<font color=""red"">You did not enter a Name.</font><br>")
	End If
	
	If ContactUs_Subject = "" Then
	IsError = "Yes"
		Response.Write("<font color=""red"">You did not enter a Subject.</font><br>")
	End If
	
	If ContactUs_Body = "" Then
		IsError = "Yes"
		Response.Write("<font color=""red"">You did not enter a Body.</font><br>")
	End If
	
End If
	
' If there were no input errors and the action of the form is "SendEMail" we send the email off
If Action = "SendEmail" And IsError <> "Yes" Then
	
	Dim strBody
	
	' Here we create a nice looking html body for the email
	strBody = strBody & "<font face=""Arial"">Contact Us Form submitted at " & Now() &  vbCrLf & "<br><br>"
	strBody = strBody & "From http://" & Request.ServerVariables("HTTP_HOST") &  vbCrLf & "<br>"
	strBody = strBody & "IP " & Request.ServerVariables("REMOTE_ADDR") & vbCrLf & "<br>"
	strBody = strBody & "Name" & " : " & " " & Replace(ContactUs_Name,vbCr,"<br>") & "<br>"
	strBody = strBody & "Email" & " : " & " " & Replace(ContactUs_Email,vbCr,"<br>") & "<br>"
	strBody = strBody & "Subject" & " : " & " " & Replace(ContactUs_Subject,vbCr,"<br>") & "<br>"
	strBody = strBody & "<br>" & Replace(ContactUs_Body,vbCr,"<br>") & "<br>"
	strBody = strBody & "</font>"
	
	     
	'This section provides the configuration information for the remote SMTP server.



'Create the e-mail server object
Dim objCDOSYSMail
Dim objCDOSYSCon
Set objCDOSYSMail = Server.CreateObject("CDO.Message")
Set objCDOSYSCon = Server.CreateObject ("CDO.Configuration")
'Outgoing SMTP server
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "hiro.aserv.co.za"
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCDOSYSCon.Fields("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objCDOSYSCon.Fields.Update 'Update the CDOSYS Configuration
Set objCDOSYSMail.Configuration = objCDOSYSCon
objCDOSYSMail.From = ContactUs_Email
objCDOSYSMail.To = youremail
objCDOSYSMail.Subject = ContactUs_Subject
objCDOSYSMail.HTMLBody = strBody
objCDOSYSMail.Send
'Close the server mail object
Set objCDOSYSMail = Nothing
Set objCDOSYSCon = Nothing
     
	


</body>

</html>

html代码的最后一部分是Contact_us.asp,托管公司希望提供给我什么。我只是不知道如何实现这一目标。希望有人可以帮助我。

0 个答案:

没有答案