0
votes

I am using PHPMailer in order to build a contact form and I am looking for a variable ($msg) to display a success or failure message depending on if the end user has correctly filled out the form or not. The ($msg) variable echo's succesfully if the form is completed correctly however, the $(msg) variable does not echo if the user does not fill out the form correctly and instead I receive a fatal error which reads as follows:

Fatal error: Uncaught PHPMailer\PHPMailer\Exception: Invalid address: (Reply-To): in /home/k4piavsj0bsc/public_html/phpmailer/src/PHPMailer.php:1004 Stack trace: #0 /home/k4piavsj0bsc/public_html/phpmailer/src/PHPMailer.php(973): PHPMailer\PHPMailer\PHPMailer->addOrEnqueueAnAddress('Reply-To', '', '') #1 /home/k4piavsj0bsc/public_html/contactForm.php(18): PHPMailer\PHPMailer\PHPMailer->addReplyTo('') #2 /home/k4piavsj0bsc/public_html/contactForm.php(30): sendemail('info@purplelime...', '', '', '') #3 /home/k4piavsj0bsc/public_html/index.php(9): include('/home/k4piavsj0...') #4 {main} thrown in /home/k4piavsj0bsc/public_html/phpmailer/src/PHPMailer.php on line 1004

Here's my code, does anyone have any ideas how I get the ($msg) variable to display if the end user has not completed the form or it has failed from the server side?

<?php

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

$msg = "";

if (isset($_POST['submit'])) {
    require 'phpmailer/src/Exception.php';
    require 'phpmailer/src/PHPMailer.php';
    require 'phpmailer/src/SMTP.php';

    function sendemail ($to, $reply, $subject, $body) {
        $mail = new PHPMailer(true);
        $mail->setFrom('[email protected]', 'PLT Contact Form - Email');
        $mail->addAddress($to);
        $mail->addReplyTo($reply);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->IsHTML(false);

        return $mail->send();
    }

    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];

    if (sendemail('[email protected]', $email, $subject, $body)) {
        $msg = 'Email has been sent, Thank you!';
    } else
        $msg = 'Email failed, please try again later';

  }

?>


<html>

<title>Contact Form Using PHPMailer</title>


<body>

    <div id="contactInnerWrapper">
        <a href="#"><span id="close">&times;</span></a>
        <h1 id="h1contactForm">Get in touch</h1>
            <form method="post" action="contactForm.php">
                <label for="email">Email address:</label><br>
                <input  type="email" name="email"  placeholder="Enter email" id="email">
                <label for="subject">Subject:</label>
                <input  type="text" name="subject" id="subject"><br>
                <label for="body">What would you like to ask us?</label><br>
                <textarea  type="text" name="body" rows="7" id="content"></textarea>
                <button type="submit" name="submit" id="submit" value="send">Submit</button>
            </form>
            <br><br>
            <?php echo $msg; ?>
    </div>

    <script type="text/javascript" src="general.js"></script>

 </body>

</html>
2
Do your question (in bold font) does have anything in common with that error above? I would say “Invalid address” is a clear enough – pass a valid email address into $_POST['email'] and you will see a result. Would be be better though, to check if the given email address is a valid onefeeela
Adding some data validation might do the trick. Never assume that you get all the data you need in the format you expect from the user. Rule of thumb, never trust user data.Magnus Eriksson
Also surround the call to sendemail with try, catch PHPMailer\PHPMailer\Exception and set the error message on the catch clauseTheofanis
Use Try catch for better error handling : try { // your code } catch (Exception $e) { echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; }prakash tank
Thanks for all the feedback, I'm very new to PHP so all the suggestions you are providing are very much appreciated but unfortunately I am unable to understand some of the terminologies you are referring to. Could I ask that some code is provided so that I can see where I am going wrong and can try and get it to work :)Coder

2 Answers

1
votes

Change the last if statement to this

$email = filter_var($email, FILTER_SANITIZE_EMAIL); // 
if (filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($subject) && !empty($body)) {
    try {
        if (sendemail('[email protected]', $email, $subject, $body))
            $msg = 'Email has been sent, Thank you!';
        else
            $msg = 'Error sending email';
    }catch(Excpetion $e) {
        $msg = 'Sending email failed, error: '.$e->getMessage();
    }
} else
    $msg = 'Email failed, incomplete/invalid data';
  1. Remove all illegal characters from email with FILTER_SANITIZE_EMAIL.
  2. The FILTER_VALIDATE_EMAIL filter validates an e-mail address.
  3. Check if not empty body and subject.
  4. Try sending the email and on fatal error properly catch it and return an explanatory message.
  5. If sendemail function return correctly set success message or else set error message.
0
votes

I think the following code will help you understand and solve your problem.

$email = isset($_POST['email']) ? $_POST['email']:'';
$subject = isset($_POST['subject']) ? $_POST['subject']:'';
$body = isset($_POST['body']) ? $_POST['body']:'';

$is_valid_email = filter_var($email, FILTER_VALIDATE_EMAIL);

$status = false;
if ($email!='' && $is_valid_email==true && $subject!='' && $body!='') {
    $status = sendemail('[email protected]', $email, $subject, $body)
}
if($status==true){
    $msg = 'Email has been sent, Thank you!';
} else
    $msg = 'Email failed, please try again later';
}