Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send emails through PHP to GMail?

Tags:

php

email

I'm guessing that this:

<?php

    $emailTo = '[email protected]';
    $subject = 'I hope this works!';
    $body = 'Blah';
    $headers='From: [email protected]'

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

?>

is not going to cut it. I searched for ways that I can send to email with SMTP auth and mail clients and programs such as PHPMailer, but I don't have a concise and direct answer yet thats helpful. Basically, I want a way to send emails to gmail, hotmail, etc (which will be my email) from another email (sender) through a form on my website

Questions:

  1. Do I need to download a 3rd party library to this?
  2. If not, how can I change the code above to make it work.

Thanks!

like image 644
John Doe Avatar asked Aug 04 '16 21:08

John Doe


People also ask

How can I send an email using PHP?

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters. mail( to, subject, message, headers, parameters );

Does PHPMailer need SMTP?

For PHPMailer to be able to send emails from your PHP app, you will need to connect it to an SMTP server.


1 Answers

Use PHPMailer library.It is better than use mail native function because in PHPMailer you can use user authentication to avoid to send the email to spam.You can use this library without to configure a mail server. You can download in this link https://github.com/PHPMailer/PHPMailer

See an example:

$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   = "[email protected]";  // username
$mail->Password   = "yourpassword";            // password

$mail->SetFrom('[email protected]', 'Test');

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

$mail->MsgHTML('Blah');

$address = "[email protected]";
$mail->AddAddress($address, "Test");

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}
like image 94
msantos Avatar answered Oct 25 '22 05:10

msantos