ppowell777 Posted Saturday at 05:41 PM Share Posted Saturday at 05:41 PM 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 Quote Link to comment https://forums.phpfreaks.com/topic/328176-using-mail-causes-554-error-requires-sending-email-server-username-and-password/ Share on other sites More sharing options...
ppowell777 Posted Sunday at 12:11 AM Author Share Posted Sunday at 12:11 AM 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; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/328176-using-mail-causes-554-error-requires-sending-email-server-username-and-password/#findComment-1654416 Share on other sites More sharing options...
Strider64 Posted Sunday at 11:19 AM Share Posted Sunday at 11:19 AM (edited) 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 Sunday at 11:20 AM by Strider64 Quote Link to comment https://forums.phpfreaks.com/topic/328176-using-mail-causes-554-error-requires-sending-email-server-username-and-password/#findComment-1654443 Share on other sites More sharing options...
ppowell777 Posted Sunday at 06:52 PM Author Share Posted Sunday at 06:52 PM 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. Quote Link to comment https://forums.phpfreaks.com/topic/328176-using-mail-causes-554-error-requires-sending-email-server-username-and-password/#findComment-1654457 Share on other sites More sharing options...
gizmola Posted Monday at 05:44 PM Share Posted Monday at 05:44 PM There is no way for anyone to help you, when we have no information about the mail server you are trying to connect to. GoDaddy provides email servers for you to use: https://www.godaddy.com/en-in/help/mail-server-addresses-and-ports-for-business-email-24071 It appears you are using some other service. There's additional information here: https://www.godaddy.com/en-in/help/send-form-mail-using-an-smtp-relay-server-953 Ordinarily using an smtp client is a superior solution for sending mail, but with GoDaddy, using mail() is probably best, as they have already setup the MTA on the server to deposit your outbound mail into their mail system. For local development, the best practice these days is to use a local email testing tool. There's a number of these tools, but from what I've seen with Container wrapper tools like DDEV, Mailpit seems to be the preferred solution. You need some way of differentiating environments to make this type of thing work, as the configuration for a development or QA environment is not going to be the same for a production environment. Quote Link to comment https://forums.phpfreaks.com/topic/328176-using-mail-causes-554-error-requires-sending-email-server-username-and-password/#findComment-1654494 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.