0

I am unable to send an email in PHP using PHPMailer and don't know what part of my code is wrong. My code is below:

<?php
$msg = "";

if (isset($_POST['submit'])) {
  require 'vendor/autoload.php';

  function sendemail($to, $from, $fromName, $body) {
    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);
    $mail->Subject = 'Feedback';
    $mail->Body = $body;
    $mail->isHTML(false);

    return $mail->send();
  }

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

  if (sendemail('draysondw@gmail.com', $email, $name, $body)) {
    $msg = 'Email sent!';
  }
  else {
    $msg = 'Email Failed!';
  }
}  ?>
<html>
<head>
  <meta charset="utf-8">
  <title>Feedback Form</title>
</head>
<body>
  <form method="post" action="index.php">
    Name: <input type="text" name="name" required><br>
    Email: <input type="text" name="email" required><br>
    Message: <textarea name="body"></textarea><br>
    <input type="submit" name="submit" value="Send Feedback">
  </form>
  <br>
  <?php echo $msg; ?>
</body>
</html>

Could you please help me to figure out what I am doing wrong to fix the email sending?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35

1 Answers1

0

Don't do this:

$mail->setFrom($from, $fromName);

That's forgery and will either result in send failure, rejections or spam filtering of your messages. Do this instead:

$mail->setFrom($to);
$mail->addReplyTo($from, $fromName);

That way you're not forging the from address, but replies will still go to the submitter.

I also recommend reading the troubleshooting guide which deals with exactly this issue and many others.

Synchro
  • 35,538
  • 15
  • 81
  • 104