无法发送邮件,收到邮件:无法实例化邮件功能

时间:2018-06-18 11:59:46

标签: php html phpmailer

我刚为客户推出了一个网站,由于某些原因,我的联系表格不起作用。我收到消息"无法实例化邮件功能"我使用了我在之前网站上使用的相同代码。 我希望有人可以帮助我。

我正在使用phpmailer。我也想知道它也可能是阻止我发送邮件的客户端虚拟主机吗?



<form method="POST" role="form" action="contact-2.php" class="contact-form row">
  <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="exampleFormControlSelect2" required data-error="Specific Project Required">
        <option>Overall Bar Projects</option>
        <option>Bar Ruimsig</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>

//Contact 2 php
<?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'];
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

请查看https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#could-not-instantiate-mail-function文档,了解您所描述的具体错误。

他们在那里提到。

这意味着您的PHP安装未配置为正确调用mail()函数(例如,在php.ini中未正确设置sendmail_path),或者您没有安装和配置本地邮件服务器。要解决此问题,您需要执行以下一项或多项操作:

安装本地邮件服务器(例如postfix)。 确保sendmail_path指向php.ini中的sendmail二进制文件(通常是/ usr / sbin / sendmail)。请注意,在Ubuntu / Debian上,您可能在/ etc / php5 / mods-available中有多个.ini文件,可能还有其他位置。 使用isSendmail()并在PHPMailer中设置sendmail二进制文件的路径($ mail-&gt; Sendmail =&#39; / usr / sbin / sendmail&#39 ;;)。 使用isSMTP()并使用SMTP直接发送。

答案 1 :(得分:0)

因此,我与托管人员交谈,他们说我应该使用CDOSYS发送邮件,看起来客户端托管程序包不允许sendmail功能。

如何对原始联系表实施CDOSYS。 Kinda很烂,不得不改用其他方法。我根本不熟悉CDOSYS。有没有办法按照我自己的联系方式实施该系统?显然,我然后将删除php并改用CDOSYS。

<%@ 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 = "info@alhemygroup.co.za"
yourpassword = "info123"
	
' Grabbing variables from the form post
ContactUs_Name = Request("ContactUs_Name")
ContactUs_Email = Request("ContactUs_Email")
ContactUs_Subject = Request("ContactUs_Subject")
ContactUs_Body = Request("ContactUs_Body")
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
     
	
' change the success messages below to say or do whatever you like
' you could do a response.redirect or offer a hyperlink somewhere.. etc etc
%>
            <font size="2">Your message as seen below has been sent. Thank You !!
              <br><br>
              <font color="blue">
                <% =Replace(ContactUs_Body,vbCr,"<br>") %>
              </font>
            </font>
            <% Else %>

              <form action="contact_us.asp" method="POST">
                <input type="hidden" name="Action" value="SendEmail">
                <font size="2">Contact Us:</font>
                <br><br>
                <table border="0" cellspacing="1">
                  <tr>
                    <td valign="top">
                      Name:
                    </td>
                    <td colspan="2">
                      <input type="text" name="ContactUs_Name" size="35" value="<% =ContactUs_Name %>">
                    </td>
                  </tr>
                  <tr>
                    <td valign="top">
                      Email:
                    </td>
                    <td colspan="2">
                      <input type="text" name="ContactUs_Email" size="35" value="<% =ContactUs_Email %>">
                    </td>
                  </tr>
                  <tr>
                    <td valign="top">
                      Subject:
                    </td>
                    <td colspan="2">
                      <input type="text" name="ContactUs_Subject" value="<% =ContactUs_Subject %>" size="35">
                    </td>
                  </tr>
                  <tr>
                    <td valign="top">
                      Message:
                    </td>
                    <td valign="top">
                      <textarea rows="10" name="ContactUs_Body" cols="40"><% =ContactUs_Body %></textarea>
                    </td>
                  </tr>
                  <tr>
                    <td valign="top">&nbsp;

                    </td>
                    <td colspan="2">
                      <input type="submit" value="Send Message">
                    </td>
                  </tr>
                </table>
              </form>

              <% End If %>

                <p>If you like this contact form code please check out some of our applications such as <a target="_blank" href="http://www.aspprotect.com">
ASPProtect</a> and <a target="_blank" href="http://www.aspbanner.com">ASPBanner</a>.</p>

        </body>

        </html>

这段代码是托管人发送给我的,我不知道如何进行此工作,也不希望表单在同一页面上提交。希望有人可以帮助我