0

EDIT number 2: I have tried phpmailer instead of mail() function. Please, take a look at the code below. I have created a few email accounts to test the code, none worked: yahoo, gmail, yandex. I am posting one the code that contains one of those accounts including real password. Please, help to get through this. I have the whole pset ready and I have been doing my best to solve the email issue for a second day. I am among less comfortable. I have even tried it with the harvard's address - the one show in the walkthrough froshims-3. https://courses.edx.org/courses/course-v1:HarvardX+CS50+X/courseware/4112040f92094edeba0e5e49b7f1fffe/67c3d981b20f41a69692839397966f2a/

In some instances I get

SMTP Error: Could not connect to SMTP host. Message could not be sent.
Mailer Error: SMTP Error: Could not connect to SMTP host.

In others I get error indicating that authentication failed.

    <?php

        // configuration
        require("../includes/config.php");
        require("libphp-phpmailer/class.phpmailer.php");

        if (isset($_SESSION["id"]))
        {
            $row = CS50::query("SELECT username, email FROM users WHERE id = ?", $_SESSION["id"]);
            $email = $row[0]["email"];
            $name = $row[0]["username"];

            /***
            // wanted to have a secure link, but for now commenting it out
            $salt = "3453#2K:90k≈“π631%380‘“HJK0D*7WPJ987NU";
        // Create the unique user password reset key
        $password = hash('sha512', $salt.$email);
        // url to reset password
        $reset_url = "https://ide50-alla.cs50.io/new_password.php?q=".$password;
        ***/

        $reset_url = "https://ide50-alla.cs50.io/new_password.php";
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "tls";

        $mail->Host = "smtp.gmail.com";
        $mail->Port = 587;
        $mail->Username = "allduc.vitale@gmail.com";
        $mail->Password = "audrey777"; 
        $mail->SetFrom("allduc.vitale@gmail.com");

        $mail->AddAddress($email); 
        $mail->Subject = "Requested link from CS50 Finance web page"; 
        $mail->Body = "Dear $name,\n\nYou have requested to reset your password for CS50 Finance web page.
                       \n\nTo reset your password, please click the link below.\n\n".$reset_url."\n\nThank you!"; 

        if(!$mail->Send())
        {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo;
            apologize("Couldn't send email");
        }
        else
        {
            // render form
            render("email_link_form.php", ["email" => $email]);
        }

    }
    else
    {
        redirect("login.php");
    }

?>

EDIT: my question is not truly a duplicate, because I am asking for help on finding mistakes in my code. But reading about phpmailer() I have realized that mail() function simply doesn't work correctly in many instances.

I am struggling with pset7, but in a happy way because, although it's a hard task, I have learned a lot. Now I am doing reset password part. I am among less comfortable, but happy to learn this fascinating stuff. I will be grateful for help. Please, take a look at the code below. I don't see why mail() function doesn't send an email. I have checked all variables from query(), all are fine, and all display correct values, but email doesn't arrive.

http://php.net/manual/en/function.mail.php

<?php

    // configuration
    require("../includes/config.php");

    if (isset($_SESSION["id"]))
    {
        $row = CS50::query("SELECT username, email FROM users WHERE id = ?", $_SESSION["id"]);
        $email = $row[0]["email"];
        $name = $row[0]["username"];

        $salt = "3453#2K:90k≈“π631%380‘“HJK0D*7WPJ987NU";
        // Create the unique user password reset key
        $password = hash('sha512', $salt.$email);

        // url to reset password
        $reset_url = "https://ide50-name.cs50.io/new_password.php?q=".$password;
        $email_subject = "Requested link from CS50 Finance web page";
        //email the url
        $email_body = "Dear $name,\n\nYou have requested to reset your password for CS50 Finance web page.
                       \n\nTo reset your password, please click the link below.\n\n".$reset_url."\n\nThank you!";

        if(mail($email, $email_subject, $email_body))
        {               
           // render form
           render("email_link_form.php", ["email" => $email]);
        }
    }
    else
    {
        redirect("login.php");
    }

?>

Thank you very much!

1
1

OK, I want you to try exactly what I did:

  1. Execute the following to make sure you have git installed, and wait for the command to finish

    sudo apt-get install git
    
  2. Execute the following to get the latest version of PHPMailer and save it to your $HOME directory (you can change the path if you want, but just to be sure...)

    git clone https://github.com/PHPMailer/PHPMailer.git "$HOME/PHPMailer"
    cd $HOME/PHPMailer
    
  3. Then execute the following to create a file named mail.php that will hold our code:

    gedit mail.php
    

    and paste the following code as is:

    <?php
    require 'PHPMailerAutoload.php';
    
    $mail = new PHPMailer;
    
    $mail->SMTPDebug = 3;                               // Enable verbose debug output
    
    $mail->isSMTP();                                    // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';                     // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                             // Enable SMTP authentication
    $mail->Username = 'allduc.vitale@gmail.com';        // SMTP username
    $mail->Password = 'audrey777';                      // SMTP password
    $mail->SMTPSecure = 'tls';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                  // TCP port to connect to
    
    $mail->setFrom('allduc.vitale@gmail.com');
    $mail->addAddress('allduc.vitale@gmail.com');       // Add a recipient (it's OK to use your email for the test)
    
    $mail->isHTML(true);                                // Set email format to HTML
    
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
    if(!$mail->send()) {
        echo 'Message could not be sent.'."\n";
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent'."\n";
    }
    ?>
    

    save and close the file.

  4. Now open a Chrome tab, and log in to this Gmail account. It's important to do so, so that Google can validate your location
  5. Go back to the command line and execute the following:

    php mail.php
    

If at any point you receive an error let me know in the comments. :)


PHPMailer's GitHub page: https://github.com/PHPMailer/PHPMailer

19
  • 1
    Thank you very much! I will do that. Question for now: are we talking about the cs50.io terminal, and installing the latest git version there, or on my machine? If on my one, then I am planning to run the whole pset7 on it today and see if the phpmailer code works. I am on Mac OS; have upgraded from 10.7.5 to 10.11 a week ago especially for this pset & for final project, because I had huge problems setting up AMP on 10.7.5. Now everything is fine, I just need to figure out how to run the pset on my machine, instead of cs50.io ) I will follow your recommendations and be back. – Vitale Aug 5 '16 at 3:12
  • I haven't used the cs50.io much, except from the first time it came out and I tried it, but if I remember correct it didn't have Chrome. You can try both and see the results. – ChrisG Aug 5 '16 at 4:06
  • I have tried the code in IDE, but got an error: Warning: require(PHPMailerAutoload.php): failed to open stream: No such file or directory in /home/ubuntu/workspace/pset7/public/email_link.php on line 6 and Fatal error: require(): Failed opening required 'PHPMailerAutoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/ubuntu/workspace/pset7/public/email_link.php on line 6. But I haven't run git commands suggested by you in the cloud. – Vitale Aug 6 '16 at 6:31
  • 2
    I have deleted my two previous comments because I have figured out my mistake: it was in the require part which should have been written as require __DIR__ . "/PHPMailer/PHPMailerAutoload.php";; that way the path to PHPMailerAutoload.php is correct ) It worked! The mail is sent, from my machine. And it arrived! )) What a relief. Now I have to figure out how to run the whole pset7 on my machine to test the whole thing. Thank you so much for helping me out and for your great patience! – Vitale Aug 6 '16 at 10:41
  • 1
    yes, indeed ) I have made an unsuccessful attempt ))) I am so curious about how CS50 team checks this pset - this is one of the most interesting parts of the course. I assume all checks are automatic; it would be a truly great learning experience to understand how these checks work. At least I am happy that all other parts of the code work, and this email one also works, although on my machine, thanks to your great help and support! Thank you very much! – Vitale Aug 8 '16 at 18:22
0

So many interesting questions in comments, but not as many answers! Here are a few. All of my advice pertains solely to the Cloud 9 CS50 IDE, not to your Mac OS X installation.

Disregard Java errors. You don't need to get the JDK from Oracle's TechNet.

In UBUNTU, you should install software with apt-get install, not apt.

But you don't need to install git in the CS50 IDE, because it's already installed. Test this:

which git

Yup, already installed. :)

But also, you don't need to get the latest PHPMailer from GitHub, because that should also be pre-installed in the CS50 IDE, as @Vitale suspected. (At least, it was for me.)

@Vitale: I'm glad you got everything (mostly!) figured out. I'm not going to spend too much time trying to figure out what went wrong in the first place, since I believe you have completed the assignment and moved on.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .