การส่งเมล์ผ่านบริการของ gmail ด้วย phpmailer

โค้ดนี้สามารถส่งเมล์โดยใช้ service ของ gmail ได้ ซึ่งจะมีข้อดีคือเมล์ของเราจะไม่ไปอยู่ที่ Junk แน่ๆ เพราะ ชื่อของ gmail เป็นประกัน และนอกจากนี้ โค้ดนี้ยังเป็นตัวอย่างการส่งเมล์โดยการเข้ารหัสแบบ ssl อีกด้วยครับ สามารถประยุกต์ใช้กับการส่งแบบ ssl บนเว็บของเราเองได้ด้วย
<?php
        require_once ('class.phpmailer.php');

        $mail = new PHPMailer(true);
        $mail->IsSMTP(); // telling the class to use SMTP
        try {
            $mail->Encoding = "quoted-printable";
            $mail->CharSet = "utf-8";
          
            // send mail by gmail
            $mail->SMTPAuth = true; // enable SMTP authentication
            $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
            $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
            $mail->Port = 465; // set the SMTP port for the GMAIL server
            $mail->Username = $gmail_username; // GMAIL username
            $mail->Password = $gmail_password; // GMAIL password
           
            $mail->AddReplyTo($mailform, $mailform);
            $mail->AddAddress($mailto, $mailto);
            $mail->SetFrom($mailform, $mailform);
            $mail->Subject = $subject;
            $mail->MsgHTML($msg);
            $mail->Send();
        }
        catch (phpmailerException$e) {
            echo $e->errorMessage(); //Pretty error messages from PHPMailer
        }
        catch (Exception $e) {
            echo $e->getMessage(); //Boring error messages from anything else!
        }
?>

ในตัวอย่างหากคุณต้องการจะส่งเมล์ผ่านบริการของ gmail (หรือเว็บเราเอง แบบ ssl) คุณจะต้องมี username และ password ก่อนถึงจะส่งได้นะครับ ซึ่งถ้าเป็น gmail ก็หมายความว่าคุณต้องมี email ของ gmail เป็นสมบัติส่วนตัว ซึ่งคุณจะต้องใช้ ชื่อและรหัสผ่านของคุณกำหนดให้กับโค้ด ครับ

ข้อจำกัดของการส่งผ่านบริการของ gmail ก็อยู่ที่ส่งไ้ด้ไม่เกิน 100 เมล์ต่อวันครับ แต่ก็คงเพียงพอสำหรับการใช้งานทั่วไป

โค้ดนี้จะส่งเมล์เป็นแบบ UTF-8 โดยไม่มีปัญหาเรื่องภาษาทั้ง yahoo gmail และ hotmail นะครับ (เท่าที่ผมทดสอบ ซึ่งผมใช้อยู่บนเว็บ) คุณสามารถดาวน์โหลด โค้ด phpmailer ได้จากบนเว็บนี้แหละครับ
ผู้เขียน goragod โพสต์เมื่อ 06 ก.ค. 2552 เปิดดู 19,874 ป้ายกำกับ PHPMailerEmail
^