Phpmailer script not working

Website URL

https://codewebsolutions.in

Error Message

An unexpected error occurs while sending mails from website.

Other Information

I’m using a custom php script configured with phpmailer but it’s not working. As of my knowledge infinityfree supports phpmailer only. Here’s my script:

/*-------------------------------------------------
	PHPMailer Initialization
---------------------------------------------------*/

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';


/*-------------------------------------------------
	Receiver's Email
---------------------------------------------------*/

$toemails = array();

$toemails[x] = array(
	'email' => '[email protected]', // Your Email Address
	'name' => 'Jay' // Your Name
);


/*-------------------------------------------------
	Sender's Email
---------------------------------------------------*/

$fromemail = array(
	'email' => '[email protected]', // Company's Email Address (preferably currently used Domain Name)
	'name' => 'New Entry - Contact Form' // Company Name
);


/*-------------------------------------------------
	reCaptcha
---------------------------------------------------*/

// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = '*******************************************';

/*-------------------------------------------------
	PHPMailer Initialization
---------------------------------------------------*/

$mail = new PHPMailer();

/* Add your SMTP Codes after this Line */
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '[email protected]';                 // SMTP username
    $mail->Password = '***********';                           // SMTP password
    $mail->SMTPSecure = 'tls';                           // Enable TLS encryption,
    $mail->Port = 587; 

// End of SMTP


/*-------------------------------------------------
	Form Messages
---------------------------------------------------*/

$message = array(
	'success'			=> 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.',
	'error'				=> 'Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.',
	'error_bot'			=> 'Bot Detected! Form could not be processed! Please Try Again!',
	'error_unexpected'	=> 'An <strong>unexpected error</strong> occured. Please Try Again later.',
	'captcha_invalid'	=> 'Captcha not Validated! Please Try Again!',
	'captcha_error'		=> 'Captcha not Submitted! Please Try Again.'
);


/*-------------------------------------------------
	SPAM Protection Settings
---------------------------------------------------*/

$spam_keywords = array(
	'viagra',
	'cialis',
	'levitra'
);

$allowed_urls = 1;


/*-------------------------------------------------
	Form Processor
---------------------------------------------------*/

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	$prefix		= !empty($_POST['prefix']) ? $_POST['prefix'] : '';
	$submits	= $_POST;
	$botpassed	= false;


	$message_form					= !empty($submits['message']) ? $submits['message'] : array();
	$message['success']				= !empty($message_form['success']) ? $message_form['success'] : $message['success'];
	$message['error']				= !empty($message_form['error']) ? $message_form['error'] : $message['error'];
	$message['error_bot']			= !empty($message_form['error_bot']) ? $message_form['error_bot'] : $message['error_bot'];
	$message['error_unexpected']	= !empty($message_form['error_unexpected']) ? $message_form['error_unexpected'] : $message['error_unexpected'];
	$message['captcha_invalid']	= !empty($message_form['captcha_invalid']) ? $message_form['captcha_invalid'] : $message['captcha_invalid'];
	$message['captcha_error']		= !empty($message_form['captcha_error']) ? $message_form['captcha_error'] : $message['captcha_error'];


	/*-------------------------------------------------
		SPAM Protection
	---------------------------------------------------*/

	function spam_keyword_check($submitted, $spamwords)
	{
		if (is_array($submitted)) {
			return false;
		}
		if (!is_array($spamwords)) $spamwords = array($spamwords);
		foreach ($spamwords as $spamstring) {
			if (($position = stripos($submitted, $spamstring)) !== false) return $position;
		}
		return false;
	}

	function spam_url_check($submitted)
	{
		if (is_array($submitted)) {
			return false;
		}

		$pattern = "/(http|https)\:\/\/(www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

		if (preg_match_all($pattern, $submitted, $urls)) {
			return count($urls);
		}

		return false;
	}

	foreach ($submits as $spam_submit) {
		if (spam_keyword_check($spam_submit, $spam_keywords) || spam_url_check($spam_submit) > $allowed_urls) {
			// A successful message is displayed to the submitter that makes him think that the Form has been sent so that he cannot modify the keywords to prevent SPAM
			echo '{ "alert": "success", "message": "' . $message['success'] . '" }';
			exit;
		}
	}


	/*-------------------------------------------------
		reCaptcha
	---------------------------------------------------*/

	if (isset($submits['g-recaptcha-response']) && !isset($submits['h-captcha-response'])) {

		$recaptcha_data = array(
			'secret' => $recaptcha_secret,
			'response' => $submits['g-recaptcha-response']
		);

		$recap_verify = curl_init();
		curl_setopt($recap_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
		curl_setopt($recap_verify, CURLOPT_POST, true);
		curl_setopt($recap_verify, CURLOPT_POSTFIELDS, http_build_query($recaptcha_data));
		curl_setopt($recap_verify, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($recap_verify, CURLOPT_RETURNTRANSFER, true);
		$recap_response = curl_exec($recap_verify);

		$g_response = json_decode($recap_response);

		if ($g_response->success !== true) {
			echo '{ "alert": "error", "message": "' . $message['captcha_invalid'] . '" }';
			exit;
		}
	}


	$mail->Subject = !empty($submits['subject']) ? $submits['subject'] : 'Form Response from your Website';
	$mail->SetFrom($fromemail['email'], $fromemail['name']);

	if (!empty($replyto)) {
		if (count($replyto) > 1) {
			$replyto_e = $submits[$replyto[0]];
			$replyto_n = $submits[$replyto[1]];
			$mail->AddReplyTo($replyto_e, $replyto_n);
		} elseif (count($replyto) == 1) {
			$replyto_e = $submits[$replyto[0]];
			$mail->AddReplyTo($replyto_e);
		}
	}

	foreach ($toemails as $toemail) {
		$mail->AddAddress($toemail['email'], $toemail['name']);
	}

	/*-------------------------------------------------
		All Processing for Fields starting
	---------------------------------------------------*/

	$underscore = array();

	foreach ($submits as $name => $value) {
		if (strpos($name, '_') === 0) {
			$underscore[] = $name;
		}
	}

	$unsets = array('prefix', 'subject', 'replyto', 'template', 'html_title', 'message', 'autoresponder', 'ar_subject', 'ar_title', 'ar_message', 'ar_footer', $prefix . 'botcheck', 'g-recaptcha-response', 'h-captcha-response', 'force_recaptcha', $prefix . 'submit');

	$unsets = $unsets + $underscore;

	foreach ($unsets as $unset) {
		unset($submits[$unset]);
	}

	$fields = array();

	foreach ($submits as $name => $value) {
		if (empty($value)) {
			continue;
		}

		$name = str_replace($prefix, '', $name);
		$name = function_exists('mb_convert_case') ? mb_convert_case($name, MB_CASE_TITLE, "UTF-8") : ucwords($name);

		if (is_array($value)) {
			$value = implode(', ', $value);
		}

		$fields[$name] = nl2br(filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS));
	}

	$files = $_FILES;

	foreach ($files as $file => $filevalue) {
		if (is_array($filevalue['name'])) {
			$filecount = count($filevalue['name']);

			for ($f = 0; $f < $filecount; $f++) {
				if (isset($_FILES[$file]) && $_FILES[$file]['error'][$f] == UPLOAD_ERR_OK) {
					$mail->IsHTML(true);
					$mail->AddAttachment($_FILES[$file]['tmp_name'][$f], $_FILES[$file]['name'][$f]);
				}
			}
		} else {
			if (isset($_FILES[$file]) && $_FILES[$file]['error'] == UPLOAD_ERR_OK) {
				$mail->IsHTML(true);
				$mail->AddAttachment($_FILES[$file]['tmp_name'], $_FILES[$file]['name']);
			}
		}
	}

	$response = array();

	foreach ($fields as $fieldname => $fieldvalue) {
		if ($template == 'text') {
			$response[] = $fieldname . ': ' . $fieldvalue;
		} else {
			$fieldname = '<tr>
								<td style="font-size: 16px; line-height: 24px; font-weight: bold; padding: 0 0 5px 0;" align="left">' . $fieldname . '</td>
							</tr>';
			$fieldvalue = '<tr>
								<td style="font-size: 16px; line-height: 24px; color: #777777; padding: 0 15px 30px 0;" align="left">' . $fieldvalue . '</td>
							</tr>';
			$response[] = $fieldname . $fieldvalue;
		}
	}

	$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

	$html_before = '<table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" bgcolor="#eeeeee" style="width: 100%; height: 100%; padding: 50px 0 50px 0;">
				<tr>
					<td align="center" valign="top">
						<table border="0" cellpadding="0" cellspacing="0" width="84%" bgcolor="#ffffff" style="width: 84%;">
							<tr>
								<td align="center" valign="top">
									';

	$html_after = '</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>';

	if ($template == 'text') {
		$body = implode("<br>", $response) . $referrer;
	} else {
		$html = $html_before . '<!-- / Header -->
									<table border="0" cellpadding="0" cellspacing="0" width="84%" style="width: 84%;">
										<tr>
											<td style="padding: 30px 0 30px 0; border-bottom: solid 1px #eeeeee; font-size: 30px; font-weight: bold; text-decoration: none; color: #000000;" align="left">
												' . $html_title . '
											</td>
										</tr>
									</table>

									<!-- / Sub-Header -->
									<table border="0" cellpadding="0" cellspacing="0" width="84%" style="width: 84%; padding: 60px 0 30px 0;"">
										' . implode('', $response) . '
									</table>

									<!-- / Footer -->
									<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center">
										<tr>
											<td align="center">
												<table border="0" cellpadding="0" cellspacing="0" width="84%" align="center" style="border-top: 1px solid #eeeeee; width: 84%;">
													<tr>
														<td style="color: #d5d5d5; text-align: center; font-size: 12px; padding: 30px 0 30px 0; line-height: 22px;">' . strip_tags($referrer) . '</td>
													</tr>
												</table>
											</td>
										</tr>
									</table>
									' . $html_after;

		$body = $html;
	}

					<!-- / Sub-Header -->
					<table border="0" cellpadding="0" cellspacing="0" width="84%" style="width: 84%; padding: 60px 0 30px 0;"">
						<tr>
							<td style="font-size: 16px; line-height: 26px; color: #777777; padding: 0 15px 30px 0;" align="left">' . $ar_message . '</td>
						</tr>
					</table>

					<!-- / Footer -->
					<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center">
						<tr>
							<td align="center">
								<table border="0" cellpadding="0" cellspacing="0" width="84%" align="center" style="border-top: 1px solid #eeeeee; width: 84%;">
									<tr>
										<td style="color: #d5d5d5; text-align: center; font-size: 12px; padding: 30px 0 30px 0; line-height: 22px;">' . $ar_footer . '</td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
					' . $html_after;

		$autoresponder->MsgHTML($ar_body);
		$autoresponder->CharSet = "UTF-8";
	}

	$mail->MsgHTML($body);
	$mail->CharSet = "UTF-8";
	$sendEmail = $mail->Send();

	if ($sendEmail == true):

		if ($autores && !empty($replyto_e)) {
			$send_arEmail = $autoresponder->Send();
		}

		echo '{ "alert": "success", "message": "' . $message['success'] . '" }';
	else:
		echo '{ "alert": "error", "message": "' . $message['error'] . '<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo . '" }';
	endif;
} else {
	echo '{ "alert": "error", "message": "' . $message['error_unexpected'] . '" }';
}

Are you using your login password for Gmail? Or have you set up an app password?

You need to use an app password. In my experience this is the biggest cause of problems

5 Likes

Another thing to note is that if all those emails are linked to the same Gmail inbox, Google will only show the email in the sent folder, not your inbox. I would send the email from a separate Gmail inbox, or to a different inbox.

6 Likes

Is this the actual error message you see? Because the script looks custom, so I would expect that you could get a more informative error message from your software. Or maybe set $mail->SMTPDebug to a higher value, like 4, to get a bit more output as to why the connection fails?


But like @dan3008 also said: the most likely reason to me seems that you are trying to login with your Google account password, which is no longer supported. You have to enable 2FA on your Google account and then create an App-Specific Password to use SMTP.

4 Likes

@dan3008 I’m using App password

1 Like

no I’m using app password only

@Greenreader9 My receiver mail id ‘’‘[email protected]’‘’ is hosted on zoho, and I’m using SMTP of my gmail account [email protected] both are not same inbox

@Admin I have tried with changed value of 4 for SMTPDebug but still getting the same error

Have you tried anything else to get a more useful error message? Or maybe even set the SMTP debug log even higher to try and get more output?

4 Likes

Gmail may require login. Why not use mail function of php, much simpler and easier to customize.

the PHP function mail() is blocked on the free hosting unfortunaitly.

6 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.