0

I just launched a website for a client and I for some reason the contact form does not work. I get the message "could not instantiate mail fucntion" I used the same code that I used on a previous website which works fine. I hope someone could help me on this.

I am using phpmailer. I am also wondering could it also be the clients webhost who prevents me from sending mail?

<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 = '[email protected]';
$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'];
}

7
  • do you have installed postfix on your server???
    – Parth Shah
    Jun 18, 2018 at 12:05
  • probably not, how does one install this on the server?
    – Frana
    Jun 18, 2018 at 12:08
  • 1
  • 1
    Very likely your web host doesn’t allow you to send mail. Check with them before spinning your wheels on this. Also, if you don’t control the server (with root access), you won’t be able to install postfix.
    – elixenide
    Jun 18, 2018 at 12:10
  • I appreciate this. I contacted them, shall hear what they say, otherwise go the smtp route
    – Frana
    Jun 18, 2018 at 12:14

2 Answers 2

0

Please check https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#could-not-instantiate-mail-function documentation regarding specific error you are describing.

They mention there.

This means that your PHP installation is not configured to call the mail() function correctly (e.g. sendmail_path is not set correctly in your php.ini), or you have no local mail server installed and configured. To fix this you need to do one or more of these things:

Install a local mail server (e.g. postfix). Ensure that your sendmail_path points at the sendmail binary (usually /usr/sbin/sendmail) in your php.ini. Note that on Ubuntu/Debian you may have multiple .ini files in /etc/php5/mods-available and possibly other locations. Use isSendmail() and set the path to the sendmail binary in PHPMailer ($mail->Sendmail = '/usr/sbin/sendmail';). Use isSMTP() and send directly using SMTP.

0

So I spoke with the hosting they said I should use the CDOSYS to send mail, looks like the clients hosting package does not allow the sendmail function.

How would I implement CDOSYS towards my original contact form. Kinda sucks having to change to a different method. I am not fimiliar with CDOSYS at all. Is there a way to implement this system to my own contact form? obviously I shall then remove the php and use CDOSYS instead.

<%@ 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 = "[email protected]"
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>

This code is what was send to me by the hosting and I have no idea how I am going to make this work, and don't want the form to submit on the same page. Hope someone can assist me with this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.