Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Building Websites with PHP Contact Form & Sending Email Sending Our Email

Jon Mullins
Jon Mullins
15,724 Points

swiftmailer smtp on gmail does not populate "from" field properly

Hi, I have created a contact form for my site using swiftmailer. Everything works as expected, except the "from" field contains my gmail address instead of the email the site visitor enters in the form. What's odd is the "reply to address IS set to the value entered in the form. Here is my code:

$app->post('/contact', function() use($app){
  $name = $app->request->post('name');
  $email = $app->request->post('email');
  $msg = $app->request->post('msg');
  if(!empty($name) && !empty($email) && !empty($msg)) {
      $cleanName = filter_var($name, FILTER_SANITIZE_STRING);
      $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
      $cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING);
    } else {
      //message that there was a problem
      $app->redirect('./contact');
    }

    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername('myAccount@gmail.com')
      ->setPassword('myAwesOmE_PaSsw0rd');
    $mailer = \Swift_Mailer::newInstance($transport);

    $message = \Swift_Message::newInstance();
    $message->setSubject('Email from our website');
    $message->setFrom(array(
      $cleanEmail => $cleanName
    ));
    $message->setReplyTo($cleanEmail);
    $message->setTo('theEmailWhereIW@ntTheMessage.com');
    $message->setBody($cleanMsg);

    $result = $mailer->send($message);

    if($result > 0) {
     //send a thank you message
      $app->redirect('./');
    } else {
      //send alert that the message failed to send
      //log the error
      $app->redirect('./contact');
    }

I think $message->replyTo must be given your email.