skip to Main Content

I’m using PHP Mailer for Mail send process. when i use that i have recieving one error message which is
Error:
Admin: Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server

all data recieving into database when comming to this part: if ($conn) { $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); if (!$stmt->execute()) { echo "Error: Unable to insert data into the database."; exit(); } $stmt->close(); } else { echo "Error: Unable to connect to the database."; exit(); }
But the problem is occuring when send the email for Admin. Give me a solution and let me know what is happening there, and i have set correct all the credentials.

My full code

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

error_reporting(E_ALL);
ini_set('display_errors', 1);

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (!empty($_POST['username']) && !empty($_POST['email'])) {
            $name = $_POST['username'];
            $mail = $_POST['email'];
            // Save data to the database
            $conn = Connection();
            if ($conn) {
                $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
                $stmt->bind_param("ss", $name, $email);
                if (!$stmt->execute()) {
                    echo "Error: Unable to insert data into the database.";
                    exit();
                }
                $stmt->close();
            } else {
                echo "Error: Unable to connect to the database.";
                exit();
            }

            // Send email to admin
            try {
                $mailAdmin = new PHPMailer(true);
                $mailAdmin->isSMTP();
                $mailAdmin->Host = 'smtp.gmail.com';
                $mailAdmin->SMTPAuth = true;
                $mailAdmin->Username = '[email protected]';
                $mailAdmin->Password = 'my authentication key';
                $mailAdmin->SMTPSecure = 'ssl';
                $mailAdmin->Port = 465;

                $mailAdmin->setFrom('[email protected]', 'HIII');
                $mailAdmin->addAddress('[email protected]');
                $mailAdmin->addReplyTo($email, $name);
                $mailAdmin->isHTML(true);
                $mailAdmin->Subject = "New One Arrived";
                $mailAdmin->Body = "A new form submission has been received.<br><br>
                Name: $name<br>Email: $email<br>";

                $mailAdmin->send();
            } catch (Exception $e) {
                echo 'Admin: Message could not be sent. Mailer Error: ', $mailAdmin->ErrorInfo;
                exit();
            }

            // Send thank you email to user
            try {
                $mailUser = new PHPMailer(true);
                $mailUser->isSMTP();
                $mailUser->Host = 'smtp.gmail.com';
                $mailUser->SMTPAuth = true;
                $mailUser->Username = '[email protected]';
                $mailUser->Password = 'my authentication key';
                $mailUser->SMTPSecure = 'ssl';
                $mailUser->Port = 465;

                $mailUser->setFrom('[email protected]', 'HIII');
                $mailUser->addAddress($email);
                $mailUser->isHTML(true);
                $mailUser->Subject = "Thank You for Your Enquiry";
                $mailUser->Body = "Dear $name,<br><br>";

                $mailUser->send();
            } catch (Exception $e) {
                echo 'User: Message could not be sent. Mailer Error: ', $mailUser->ErrorInfo;
                exit();
            }

            // Redirect to dashboard only if both emails are sent successfully
            //if ($adminEmailSent && $userEmailSent) {
            header('Location: dashboard.php');
            exit();
        } else {
            echo 'An error occurred while processing your request.';
        }
    }

2

Answers


  1. Maybe your server cannot connect to smtp.gmail.com on port 465

    You can change to port 587 with $mailAdmin->SMTPSecure = 'tls';

    If it still doesn’t work, I think your server or country doesn’t allow connecting to google servers …

    Login or Signup to reply.
  2. First off, Welcome to Stack Overflow! Let’s talk about some PHP principles before I post code that works in my env 🙂

    I see you are importing files manually, explicitly typing out import. I’m on the internals mailing list where we discuss changes that are request to be made (php is written in C), and this topic has been bouncing around this month: there is an RFC that was published this morning for static class, which at the time of writing is not a part of PHP, but I do believe it will pass the vote. Why though? It is extremely common to have a function that does not need the context or concepts of object-oriented programming. Still, in PHP, a design decision was made that functions declared in a file not wrapped in namespace XYZ{} or begins with a namespace XYZ; should be in the global scope. This makes dynamically loading PHP files only when needed impossible for un-namespaced functions. If every file in your application is loaded into memory for every request, then it will be very slow. So static classes are coming strictly because of autoloading principles.

    The community also follows PHP-FIG; don’t let anyone tell you differently. Specifically, PSR-4 talks about autoloading and how to namespace your files.

    But let’s not re-invent the wheel, no, PHP users also use composer. It’s like npm, pip, dnf, apt, brew, choco, etc. It lets the PHP community use open source code super quickly… You probably manually downloaded the PHP-Mailer but really you should have defined it in your composer.json file. The example above uses version:

    {
     "description": "The best MVC framework",
     "minimum-stability": "dev",
     "prefer-stable": true,
     "license": "MIT",
     "autoload": {
       "psr-4": {
         "MilesSystems\": "milessystems/",
         "MilesSystems\Configuration\": "milessystems/configuration/",
         "MilesSystems\Tables\": "milessystems/tables/"
       }
     },
     "scripts": {
       "apache:linkApplication": [
         "mkdir -p ./logs/httpd/",
         "rm /usr/local/var/www",
         "ln -s $(pwd) /usr/local/var/www",
         "@apache:restart:mac"
       ],
       "apache:restart:mac": "sudo brew services restart httpd"
     },
     "require": {
       "carbonorm/carbonphp": "dev-lts",
       "phpmailer/phpmailer": "^6.9.1"
     }
    }
    
    <?php
    
    namespace MilesSystems;
    
    use CarbonPHPErrorThrowableHandler;
    use PHPMailerPHPMailerPHPMailer;
    use Throwable;
    
    class Email
    {
        public static function sendMail(string $email, string $subject, string $message): void
        {
    
            try {
    
                ob_start(null, 512);
    
                $mail = new PHPMailer(true);
    
                $mail->SMTPDebug = 1;
    
                $mail->isSMTP();
    
                $mail->Host = 'smtp.gmail.com';
    
                $mail->Port = 587;
    
                $mail->SMTPAuth = true;
    
                $mail->Username = $_ENV['GOOGLE_SMTP_USERNAME'];
    
                // @link https://myaccount.google.com/apppasswords
                // this is App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. You'll only need to enter it once so you don't need to remember it.
                // @link https://support.google.com/accounts/answer/185833?hl=en
                $mail->Password = $_ENV['GOOGLE_SMTP_PASSWORD'];
    
                $mail->SMTPSecure = 'tls';
    
                //Recipients
                $mail->setFrom('[email protected]', 'Richard Miles');
    
                $mail->addReplyTo('[email protected]', 'Richard Miles');          // there address
    
                $mail->addAddress($email);
    
                // Attachments
                //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
                //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    
                //Content
                $mail->isHTML();
    
                $mail->Subject = $subject;
    
                $mail->Body = self::emailTemplate($email, $subject, $message);
    
                $mail->AltBody = htmlentities($mail->Body);
    
                // $mail->addBCC('[email protected]');
    
                $mail->send();
    
                unset($mail);
    
            } catch (Throwable $e) {
    
                ThrowableHandler::generateLog($e);
    
            } finally {
    
                ob_end_clean();
    
            }
    
        }
    
    
        private static function emailTemplate(string $email, string $subject, string $message): string
        {
            return /** @lang HTML */ <<<TEMPLATE
    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
    <head>
        <meta charset="utf-8"> <!-- utf-8 works for most cases -->
        <meta name="viewport" content="width=device-width"> <!-- Forcing initial-scale shouldn't be necessary -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Use the latest (edge) version of IE rendering engine -->
        <meta name="x-apple-disable-message-reformatting">  <!-- Disable auto-scale in iOS 10 Mail entirely -->
        <title></title> <!-- The title tag shows in email notifications, like Android 4.4. -->
    
        <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
    
        <!-- CSS Reset : BEGIN -->
        <style>
    
            /* What it does: Remove spaces around the email design added by some email clients. */
            /* Beware: It can remove the padding / margin and add a background color to the compose a reply window. */
            html,
    body {
        margin: 0 auto !important;
        padding: 0 !important;
        height: 100% !important;
        width: 100% !important;
        background: #f1f1f1;
    }
    
    /* What it does: Stops email clients resizing small text. */
    * {
        -ms-text-size-adjust: 100%;
        -webkit-text-size-adjust: 100%;
    }
    
    /* What it does: Centers email on Android 4.4 */
    div[style*="margin: 16px 0"] {
        margin: 0 !important;
    }
    
    /* What it does: Stops Outlook from adding extra spacing to tables. */
    table,
    td {
        mso-table-lspace: 0pt !important;
        mso-table-rspace: 0pt !important;
    }
    
    /* What it does: Fixes webkit padding issue. */
    table {
        border-spacing: 0 !important;
        border-collapse: collapse !important;
        table-layout: fixed !important;
        margin: 0 auto !important;
    }
    
    /* What it does: Uses a better rendering method when resizing images in IE. */
    img {
        -ms-interpolation-mode:bicubic;
    }
    
    /* What it does: Prevents Windows 10 Mail from underlining links despite inline CSS. Styles for underlined links should be inline. */
    a {
        text-decoration: none;
    }
    
    /* What it does: A work-around for email clients meddling in triggered links. */
    *[x-apple-data-detectors],  /* iOS */
    .unstyle-auto-detected-links *,
    .aBn {
        border-bottom: 0 !important;
        cursor: default !important;
        color: inherit !important;
        text-decoration: none !important;
        font-size: inherit !important;
        font-family: inherit !important;
        font-weight: inherit !important;
        line-height: inherit !important;
    }
    
    /* What it does: Prevents Gmail from displaying a download button on large, non-linked images. */
    .a6S {
        display: none !important;
        opacity: 0.01 !important;
    }
    
    /* What it does: Prevents Gmail from changing the text color in conversation threads. */
    .im {
        color: inherit !important;
    }
    
    /* If the above doesn't work, add a .g-img class to any image in question. */
    img.g-img + div {
        display: none !important;
    }
    
    /* What it does: Removes right gutter in Gmail iOS app: https://github.com/TedGoas/Cerberus/issues/89  */
    /* Create one of these media queries for each additional viewport size you'd like to fix */
    
    /* iPhone 4, 4S, 5, 5S, 5C, and 5SE */
    @media only screen and (min-device-width: 320px) and (max-device-width: 374px) {
        u ~ div .email-container {
            min-width: 320px !important;
        }
    }
    /* iPhone 6, 6S, 7, 8, and X */
    @media only screen and (min-device-width: 375px) and (max-device-width: 413px) {
        u ~ div .email-container {
            min-width: 375px !important;
        }
    }
    /* iPhone 6+, 7+, and 8+ */
    @media only screen and (min-device-width: 414px) {
        u ~ div .email-container {
            min-width: 414px !important;
        }
    }
    
        </style>
    
        <!-- CSS Reset : END -->
    
        <!-- Progressive Enhancements : BEGIN -->
        <style>
    
            .primary{
        background: #30e3ca;
    }
    .bg_white{
        background: #ffffff;
    }
    .bg_light{
        background: #fafafa;
    }
    .bg_black{
        background: #000000;
    }
    .bg_dark{
        background: rgba(0,0,0,.8);
    }
    .email-section{
        padding:2.5em;
    }
    
    /*BUTTON*/
    .btn{
        padding: 10px 15px;
        display: inline-block;
    }
    .btn.btn-primary{
        border-radius: 5px;
        background: #30e3ca;
        color: #ffffff;
    }
    .btn.btn-white{
        border-radius: 5px;
        background: #ffffff;
        color: #000000;
    }
    .btn.btn-white-outline{
        border-radius: 5px;
        background: transparent;
        border: 1px solid #fff;
        color: #fff;
    }
    .btn.btn-black-outline{
        border-radius: 0px;
        background: transparent;
        border: 2px solid #000;
        color: #000;
        font-weight: 700;
    }
    
    h1,h2,h3,h4,h5,h6{
        font-family: 'Lato', sans-serif;
        color: #000000;
        margin-top: 0;
        font-weight: 400;
    }
    
    body{
        font-family: 'Lato', sans-serif;
        font-weight: 400;
        font-size: 15px;
        line-height: 1.8;
        color: rgba(0,0,0,.4);
    }
    
    a{
        color: #30e3ca;
    }
    
    table{
    }
    /*LOGO*/
    
    .logo h1{
        margin: 0;
    }
    .logo h1 a{
        color: red;
        font-size: 24px;
        font-weight: 700;
        font-family: 'Lato', sans-serif;
    }
    
    /*HERO*/
    .hero{
        position: relative;
        z-index: 0;
    }
    
    .hero .text{
        color: rgba(0,0,0,.3);
    }
    .hero .text h2 p{
        color: #000;
        font-size: 40px;
        margin-bottom: 0;
        font-weight: 400;
        line-height: 1.4;
    }
    .hero .text h3{
        font-size: 24px;
        font-weight: 300;
    }
    .hero .text h2 span{
        font-weight: 600;
        color: #30e3ca;
    }
    
    
    /*HEADING SECTION*/
    .heading-section{
    }
    .heading-section h2{
        color: #000000;
        font-size: 28px;
        margin-top: 0;
        line-height: 1.4;
        font-weight: 400;
    }
    .heading-section .subheading{
        margin-bottom: 20px !important;
        display: inline-block;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 2px;
        color: rgba(0,0,0,.4);
        position: relative;
    }
    .heading-section .subheading::after{
        position: absolute;
        left: 0;
        right: 0;
        bottom: -10px;
        content: '';
        width: 100%;
        height: 2px;
        background: #30e3ca;
        margin: 0 auto;
    }
    
    .heading-section-white{
        color: rgba(255,255,255,.8);
    }
    .heading-section-white h2{
        font-family: 
        line-height: 1;
        padding-bottom: 0;
    }
    .heading-section-white h2{
        color: #ffffff;
    }
    .heading-section-white .subheading{
        margin-bottom: 0;
        display: inline-block;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 2px;
        color: rgba(255,255,255,.4);
    }
    
    
    ul.social{
        padding: 0;
    }
    ul.social li{
        display: inline-block;
        margin-right: 10px;
    }
    
    /*FOOTER*/
    
    .footer{
        border-top: 1px solid rgba(0,0,0,.05);
        color: rgba(0,0,0,.5);
    }
    .footer .heading{
        color: #000;
        font-size: 20px;
    }
    .footer ul{
        margin: 0;
        padding: 0;
    }
    .footer ul li{
        list-style: none;
        margin-bottom: 10px;
    }
    .footer ul li a{
        color: rgba(0,0,0,1);
    }
    
    
    @media screen and (max-width: 500px) {
    
    
    }
    
    
        </style>
    
    
    </head>
    
    <body width="100%" style="margin: 0; padding: 0 !important; mso-line-height-rule: exactly; background-color: #f1f1f1;">
        <center style="width: 100%; background-color: #f1f1f1;">
        <div style="display: none; font-size: 1px;max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden; mso-hide: all; font-family: sans-serif;">
        </div>
        <div style="max-width: 600px; margin: 0 auto;" class="email-container">
            <!-- BEGIN BODY -->
          <table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto;">
            <tr>
              <td valign="top" class="bg_white" style="padding: 1em 2.5em 0 2.5em;">
                <table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td class="logo" style="text-align: center;">
                            <h1><a href="#">Miles Systems LLC</a></h1>
                          </td>
                    </tr>
                </table>
              </td>
              </tr><!-- end tr -->
              <tr>
              <td valign="middle" class="hero bg_white" style="padding: 3em 0 2em 0;">
                <img src="https://systems.miles.systems/TruncatedIcosahedron.svg" alt="" style="width: 300px; max-width: 600px; height: auto; margin: auto; display: block;">
              </td>
              </tr><!-- end tr -->
                    <tr>
              <td valign="middle" class="hero bg_white" style="padding: 2em 0 4em 0;">
                <table>
                    <tr>
                        <td>
                            <div class="text" style="padding: 0 2.5em; text-align: center;">
                                <h2>Thank you for subscribing!</h2>
                                <h3>You can reply to this email with any questions :)</h3>
                                <p>$message</p>
                                <h3>Hope you have a blessed day :)</h3>
                            </div>
                        </td>
                    </tr>
                </table>
              </td>
              </tr><!-- end tr -->
          <!-- 1 Column Text + Button : END -->
          </table>
          <table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto;">
            <tr>
              <td valign="middle" class="bg_light footer email-section">
                <table>
                    <tr>
                    <td valign="top" width="33.333%" style="padding-top: 20px;">
                      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                        <tr>
                          <td style="text-align: left; padding-right: 10px;">
                            <h3 class="heading">About</h3>
                            <p>We are committed to client success, developing industry leaders, and encouraging lifelong wellness.</p>
                          </td>
                        </tr>
                      </table>
                    </td>
                    <td valign="top" width="33.333%" style="padding-top: 20px;">
                      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                        <tr>
                          <td style="text-align: left; padding-left: 5px; padding-right: 5px;">
                            <h3 class="heading">Contact Info</h3>
                            <ul>
                                        <li><span class="text">Highlands Ranch, CO 80129 United States</span></li>
                                        <li><span class="text">+1 (817) 789-3294</span></a></li>
                                      </ul>
                          </td>
                        </tr>
                      </table>
                    </td>
                    <td valign="top" width="33.333%" style="padding-top: 20px;">
                      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
                        <tr>
                          <td style="text-align: left; padding-left: 10px;">
                            <h3 class="heading">Useful Links</h3>
                            <ul>
                                        <li><a href="https://miles.systems/">Miles Systems LLC</a></li>
                                        <li><a href="https://carbonorm.dev/">CarbonORM</a></li>
                                        <li><a href="https://www.linkedin.com/in/richardtmiles/">LinkedIn</a></li>
                                      </ul>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                </table>
              </td>
            </tr><!-- end: tr -->
            <tr>
              <td class="bg_light" style="text-align: center;">
                <p>No longer want to receive these email?</p>
              </td>
            </tr>
          </table>
    
        </div>
      </center>
    </body>
    </html>
    
    
    TEMPLATE;
    
    
        }
    
    
    }
    

    Shameless plug my ThrowableHandler.php that will handle anything that can be caught in PHP.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search