How to send mail with PHP and Use SMTP GMail

  • 0

send email with php
source: http://www.otallu.com
This time I want to share about send email using PHP and without Framework,
for send email I'm using SMTP from gmail.

This is the steps for send email using php:
  1. Download PHPMailer library on here
  2. Save Library in same place with send_email.php

    A Simple Example for send_email.php

    <?php

    //SMTP needs accurate times, and the PHP time zone MUST be set
    //This should be done in your php.ini, but this is how to do it if you don't have access to that
    date_default_timezone_set('Etc/UTC');

    require 'PHPMailerAutoload.php';

    $mail = new PHPMailer();
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 2;
    $mail->Debugoutput = 'html';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;

    // Set to access your Gmail account
    $mail->Username = "youremail@gmail.com";
    $mail->Password = "yourgmailpassword";

    $mail->setFrom('user@example.com', 'first last'); //Set who the message is to be sent from
    $mail->addReplyTo('user@example.com', 'first last'); //Set an alternative reply-to address
    $mail->addAddress('email@example.com', 'first last'); //Set who the message is to be sent $mail->Subject = 'PHPMailer GMail SMTP test';
    $mail->Body = 'This is a plain-text message body';
    $mail->addAttachment('images/phpmailer_mini.gif'); //Attach an image file

    //send the message, check for errors
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
    ?>
  3. Save file as send_email.php
  4. Call file send_email.php ex: localhost/send_email.php
  5. If success it will show "Message sent!" and if failed it will show "Mailer Error: error message"
 
Hope this useful for you guys!

Thanks

- AR

No comments:

Post a Comment