Jump to content

Using mail() causes 554 error, requires sending email server username and password


Recommended Posts

I am writing a simple PHP script that will retrieve feedback entries from a MySQL database and send the information to an email address. I am using mail(), but I suspect that this is too simple for what I need to do.

<?php

	function setupMailServerConnection() {
		try {
			ini_set('SMTP', SMTP_HOST);
			ini_set('smtp_port', SMTP_PORT);
			ini_set('sendmail_from', FROMEMAIL);
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' setupMailServerConnection() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			throw $e;
		}
	}

	function generateBodyHeader($json) {
		return 'From: ' .
			   $json->first_name .
			   ' ' .
			   $json->last_name .
			   '<' .
			   $json->email .
			   '>\\r\\n\\r\\n';
	}

	function doMail($jsonArray) {
		$result = '0';
		$headers = '';
		$json;
		setupMailServerConnection();
		try {
			foreach ($jsonStrArray as $row) {
				$json = json_decode($row);
				$headers = 'From: ' . FROMEMAIL;
				$msg = str_replace('\\n.', '\\n..', $json->question);
				if (!mail(TO_EMAIL, $json->email_subject, generateBodyHeader($json) . wordwrap($msg, 70), $headers)) {
					$result = '-1';
					break;
				}
			}
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' doMail() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			$result = '-1';
		} finally {
			return $result;
		}
	}

Unfortunately, this constantly throws a 554 error "Email rejected".  I know my values are correct, because I have the exact same functionality in an off-site Java application that successfully works every time, however, it allows for the sending of the email server username and password, both of which I have, but I don't know how to send them using mail() or how to set them in setupMailServerConnection() using ini_set().

So, basically, I want the equivalent of this Java line in PHP:

	private void doMail() 
			throws AuthenticationFailedException, AddressException, MessagingException,
				   SQLException, UnsupportedEncodingException, Exception {
		String name = "";
		StringBuilder sb = new StringBuilder();
		MimeMessage message = new MimeMessage(this.session);  
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(FeedbackMailer.toEmail));
		for (FeedbackBean bean : this) {
			sb.append(StringUtilities.cleanXSS(StringUtilities.stripHTML(bean.getFirstName())))
			  .append(" ")
			  .append(StringUtilities.cleanXSS(StringUtilities.stripHTML(bean.getLastName())));
			name = sb.toString();
			sb.delete(0, sb.length());
			message.setFrom(new InternetAddress(FeedbackMailer.dummyFromEmail, name));  
		    message.setSubject(StringUtilities.cleanXSS(StringUtilities.stripHTML(bean.getEmailSubject())));
		    sb.append("From: ")
		      .append(name)
		      .append(" <")
		      .append(StringUtilities.cleanXSS(StringUtilities.stripHTML(bean.getEmail())))
		      .append(">")
		      .append(StringUtilities.NEW_LINE)
		      .append(StringUtilities.NEW_LINE)
		      .append(StringUtilities.cleanXSS(StringUtilities.stripHTML(bean.getQuestion())));
		    message.setText(sb.toString());  
		    Transport.send(message, FeedbackMailer.user, FeedbackMailer.password);
		    sb.delete(0, sb.length());
		}
	}

Any help appreciated.

Thanks

I changed tactics and am now using PHPMailer instead, however, I am getting the weirdest warning ever:

 

Quote

PHP Warning: Undefined array key "addToCSV" in C:\inetpub\wwwroot\cma_dev\globals\libz\PHPMailer-FE_v4.11\_lib\phpmailer-fe.php on line 325

I have no idea why this is happening, although I suspect it may be expecting $_POST['addToCSV'], which it won't get, because the data to mail never comes from a form post but from a database table query, so, basically, there is no $_POST

Here is the code:

<?php
	/*set_error_handler(function(int $errno, string $errstr) {
	    if (strpos($errstr, 'Undefined array key') === false && strpos($errstr, 'Undefined variable') === false) {
	        return false;
	    } else {
	        return true;
	    }
	}, E_WARNING);*/
	
	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\Exception;
   	header('Access-Control-Allow-Origin: *');	
	require('./globals/libz/PHPMailer-FE_v4.11/_lib/phpmailer-fe.php');
	require('./globals/includes/constants.php');
	require('./globals/includes/functions.php');
	require('./feedback/includes/constants.php');
	require('./feedback/includes/globals.php');
	require('./feedback/includes/functions.php');
	require('./feedback/includes/delivery.php');

?>

<?php
	function setupMailServerConnection() {
		$mailer = null;
		try {
			echo 'Q1<br />';
			$mailer = new PHPMailer(true); // It dies here without error message nor error logging, it just.. dies (only if set_error_handler() is uncommented out
			echo 'Q2<br />';
			$mailer->isSMTP();
			echo 'Q3<br />';
			$mailer->Host = SMTP_HOST;
			$mailer->Port = SMTP_PORT;
			$mailer->SMTPAuth = true;
			$mailer->Username = SMTP_USER;
			$mailer->Password = SMTP_PASSWORD;
			$mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
			$mailer->isHTML(false);
			$mailer->SMTPDebug = 2;
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' setupMailServerConnection() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			error_log($msg);
			throw $e;
		} finally {
			echo 'QQ: is null? ' . is_null($mailer) . '<br />';
			return $mailer;
		}
	}

	function doMail($jsonArray) {
		echo 'in doMail()<br />';
		$result = '0';
		$headers = '';
		$json = null;
		try {
			$mailer = setupMailServerConnection();
			echo 'A1<br />Is set? ' . isset($mailer) . ' Is Null? ' . is_null($mailer) . '<br />';
			if (isset($mailer) && !is_null($mailer)) {
				echo 'A2<br />';
				foreach ($GLOBALS['jsonArray'] as $row) {
					$json = json_decode($row);
					// FROM
					$mailer->setFrom(DUMMY_FROMEMAIL);
					// TO
					$mailer->addAddress(TO_EMAIL);
					// SUBJECT
					$mailer->Subject = $json->email_subject;
					// FEEDBACK SENDER EMAIL IN BODY AS "HEADER"
					$msg = generateBodyHeader($json) . str_replace('\n.', '\n..', $json->question);
					$mailer->Body = wordwrap($msg, 70);
					if (!$mail->send()) {
					    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
					} else {
					    echo 'Message has been sent';
						$result = count($GLOBALS['jsonArray']);
					}
				}
			}
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' doMail() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			$result = '-1';
		} finally {
			return $result;
		}
	}

?>

 

This might give you an idea/solution to your problem?
 

$database = new Database();
$pdo = $database->createPDO();
$mail = new PHPMailer(true); // Pass `true` to enable exceptions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $inputData = file_get_contents('php://input');
    $postData = json_decode($inputData, true);

    $name = $postData['name'];
    $email = $postData['email'];
    $comment = $postData['comments'];
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host = '';                     //Set the SMTP server to send through
    $mail->SMTPAuth = true;                                   //Enable SMTP authentication
    $mail->Username = '[email protected]';                     //SMTP username
    $mail->Password = EMAIL_PASSWORD;                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom( $email, $name);
    $mail->addAddress('[email protected]', 'John Pepp');     //Add a recipient
    $mail->addCC($email, $name);
    //Content
    $mail->CharSet = 'UTF-8';
    $mail->isHTML(false); // Set email format to plain text
    $mail->Subject = 'Inquiry of Clear Web Concepts LLC';
    // Format the body using newlines for readability
    $mail->Body =
        "You have received a new inquiry from your website:\n\n" .
        "Name: $name\n" .
        "Email: $email\n" .
        "Message:\n" .
        wordwrap($comment, 70) . "\n\n" .
        "Thank you,\nClear Web Concepts LLC";



    try {
        $mail->send();
        // Replace these variables with actual values based on your email sending process
        $status = 'success';
        $message = 'Email sent successfully';

        $response = array(
            'status' => $status,
            'message' => $message
        );
    } catch (Exception $e) {
        $response['status'] = 'error';
        $response['message'] = "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }

    header('Content-Type: application/json');
    echo json_encode($response);
}

 

Edited by Strider64

I spent all day and night trying to figure it out and finally did. It took a complete rewrite of the entire code to manage using PHPMailer alongside using PHPMailer.php (along with Exception.php and SMTP.php) from GitHub and not from SourceForge. 

So it works. On my development environment; it connects to the remote email server and delivers the email. On Production (a GoDaddy platform I purchase, so I have NO control over it except for some changes), however, it fails, producing this error, again, using the exact same email server:

 

Quote

SMTP ERROR: Failed to connect to server: An attempt was made to access a socket in a way forbidden by its access permissions (10013)

 

This is the updated code:

<?php

	// SEE https://php-forum.com/index.php?threads/phpmailer-wont-work-in-a-function.31532/ FOR REFERENCE
	use PHPMailer\PHPMailer\Exception;
	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\SMTP;

	function doMail($jsonArray) {
		$result = '0';
		$headers = '';
		$json = null;
		try {
			$mailer = setupMailServerConnection();
			if (isset($mailer) && !is_null($mailer)) {
				foreach ($GLOBALS['jsonArray'] as $row) {
					$json = json_decode($row);
					// FROM
					$mailer->From = DUMMY_FROMEMAIL;
					$mailer->Sender = DUMMY_FROMEMAIL;
					// TO
					$mailer->addAddress(TO_EMAIL);
					// SUBJECT
					$mailer->Subject = $json->email_subject;
					// FEEDBACK SENDER EMAIL IN BODY AS "HEADER"
					$msg = generateBodyHeader($json) . str_replace("\n.", "\n..", $json->question);
					$mailer->Body = wordwrap($msg, 70);
					if (!$mailer->send()) {
					    $msg = ERROR_MESSAGE . 'doMail() ' . ate('Y-m-d H:i:s') . $mailer->ErrorInfo;
						toLogDB($msg);
						$result = '-1';
						break;
					} else {
						$result = count($GLOBALS['jsonArray']);
					}
				}
			}
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' doMail() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			$result = '-1';
		} finally {
			return $result;
		}
	}
	
	function generateBodyHeader($json) {
		return 'From: ' .
			   $json->first_name .
			   ' ' .
			   $json->last_name .
			   ' <' .
			   $json->email .
			   ">\r\n\r\n";
	}
	
	function setupMailServerConnection() {
		$mailer = null;
		try {
			$mailer = new PHPMailer(true);
			$mailer->isSMTP();
			$mailer->Host = SMTP_HOST;
			$mailer->Port = SMTP_PORT;
			$mailer->SMTPAuth = true;
			$mailer->Username = SMTP_USER;
			$mailer->Password = SMTP_PASSWORD;
			$mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
			$mailer->isHTML(false);
		} catch (Exception $e) {
			$msg = ERROR_MESSAGE . ' setupMailServerConnection() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
			toLogDB($msg);
			error_log($msg);
			throw $e;
		} finally {
			return $mailer;
		}
	}
	
?>

 

I do not understand why I can connect to the remote email server with the same credentials and setup from my laptop with no server, but cannot connect to the same remote email server with the same credentials and setup.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.