Gmail phpmailer 測試範例

Gmail phpmailer 測試範例
提醒一下 近來的資料必須過濾 以防攻擊

<?php
exit;
// composer require phpmailer/phpmailer

error_reporting(0);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
?>

<h1> Gmail Test</h1><hr/>

<?php
// example
$input = array('username','password','from_mail','from_name','to_mail','to_mame','subject','message');
foreach ($input as $key => $value) {
    if ($_POST[$value]) {
        $$value = $_POST[$value];
        $send = true;
    }else{
        $send = false;
        break;
    }
}

if ($send) {
    phpmailer_sendmail($username,$password,$from_mail,$from_name,$to_mail,$to_mame,$subject,$message);
}else{
    echo '<form action="#" method="POST">';
    foreach ($input as $key => $value) {
        echo '<p>'.$value.': <input name="'.$value.'"/></p>';
    }
    echo '<input type="submit">';
    echo '</form>';
}

function phpmailer_sendmail($username,$password,$from_mail,$from_name,$to_mail,$to_mame,$subject,$message)
{
    require 'vendor/autoload.php';

    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
    try {
        $mail->Username = $username; //Gamil帳號
        $mail->Password = $password; //Gmail密碼
        $mail->setFrom($from_mail, $from_name);

        //Server settings
        // $mail->SMTPDebug = 2;                                 // Enable verbose debug output
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 465;                                    // TCP port to connect to
        $mail->CharSet = "utf-8"; //郵件編碼

        //Recipients
        $mail->addAddress($to_mail,$to_mame);     // Add a recipient
        // $mail->addReplyTo('[email protected]', 'Information');
        // $mail->addCC('[email protected]');
        // $mail->addBCC('[email protected]');

        //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 = $message; //郵件內容
        // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *