How to send emails via PHP to GMail?

I guess this is:

<?php

    $emailTo = 'user1@gmail.com';
    $subject = 'I hope this works!';
    $body = 'Blah';
    $headers='From: user@gmail.com'

    mail($emailTo, $subject, $body, $headers);

?>

not going to cut it. I was looking for ways that I can send email using SMTP authenticators and email clients and programs like PHPMailer, but I don't have a short and direct answer, but it is useful. Basically, I want to send emails to gmail, hotmail, etc. (Which will be my letter) from another sender (email) through a form on my website

Questions:

  • Do I need to download a third-party library?
  • If not, how can I change the code above to make it work.

Thank!

+4
source share
1 answer

PHPMailer. , mail, PHPMailer , . , . https://github.com/PHPMailer/PHPMailer

. :

$mail             = new PHPMailer();

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 
$mail->Host       = "smtp.gmail.com";      // SMTP server
$mail->Port       = 587;                   // SMTP port
$mail->Username   = "yourusername@gmail.com";  // username
$mail->Password   = "yourpassword";            // password

$mail->SetFrom('user@gmail.com', 'Test');

$mail->Subject    = "I hope this works!";

$mail->MsgHTML('Blah');

$address = "test@test.com";
$mail->AddAddress($address, "Test");

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}
+4

Source: https://habr.com/ru/post/1650232/


All Articles