Minggu, 02 September 2018

Sending Email with PHP

I got a request to create a web Application with a requirement sending a Warning via E-mail. First thing I did was googling, "sending Email with PHP", "how to send Email with PHP", ect. Thanks to many website and its author that give me a lot of information how to do that. I do really thank you guys for every information that you provide on your website.

I found so many tutorial with the complete library and the example how to use it. Unfortunately, many don't work. BUT...I blame my self, I'm the one who doesn't know how to use it. Then, I stopped for a minute and try to figure it out, how is the logical steps for a web server using PHP to send an E-mail. let me straight to the point, we cannot send an E-mail just using the PHP. Maybe I'm wrong at this point, but if we really could do it, I'm sure that we should make some changes in our web server's configuration.

So, what can we do then? We create a Mail Client using PHP. 
  1. Check the mail client manual setting in your web host. If you are using cpanel, check in Email Accounts --> Connect Devices --> Set up Mail Client
  2. Download PHPMailer here. Thanks to Marcus Bointon that provides us this library.
  3. Create the autoload.php, read it here how to do it. 
Before I continue to the PHP code, lets create the autoload.php for the PHPMailer library. Here is how the autoload.php looks like:

<?php
/**
 * An example of a project-specific implementation.
 *
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 *
 *      new \Foo\Bar\Baz\Qux;
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'PHPMailer\PHPMailer';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

Put that autoload.php inside PHPMailer directory.

I am using Code Igniter, I put the PHPMailer inside the view. So I load it as a view to use the library.

This is how my function in controller looks like:

public function testMail()
{
    $this->load->view('PHPMailer/autoload');
    $this->load->view('sendMail');
}

and here is the sendMail.php


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'mail.yourHost.com';                  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@yourHost.com';                 // SMTP username
    $mail->Password = 'password';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 26;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('user@yourHost.com', 'User's Name');
    $mail->addAddress('recepient@test.com', 'Recipient Name');     // Add a recipient
    //$mail->addAddress('recepient@test.com');               // Name is optional
    $mail->addReplyTo('user@yourHost.com', 'User's Name');
    //$mail->addCC('cc@example.com');
   // $mail->addBCC('bcc@example.com');

    //Attachments
   // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Subject';
    $mail->Body    = 'write something here';
    //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

?>

You can check your SMTP Configuration on your cpanel. That is already everything.

Tidak ada komentar:

Posting Komentar