2019年7月9日 星期二

使用 Gmail 的兩步驟認證下,透過 PHPMailer 發送郵件範例

到google 設定兩步驟認證
1.登入google後,找到 google帳戶,在"安全性"下會看到如下圖
未啟用兩步驟驗證的畫面

2.選擇上圖中的"兩步驟驗證"後,按下"開始使用"後,依照步驟操作完成,會得到一組16位數的密碼,此密碼會用於步驟三中的
  1. $mail->Password = '密碼';

程式碼配置與發信程式撰寫(在沒有 composer 的環境下)
一、程式碼下載
1.到 github 上下載程式碼:PHPMailer,並解壓縮
解壓縮後資料夾內容
2.將 PHPMailer 資料夾放在自己知道的路徑下,比方:/var/www/mySite/PHPMailer

二、發信程式碼撰寫
  1. <?php
  2. try {
  3. /* Set the mail encode. */
  4. CharSet = 'UTF-8';
  5.  
  6. /* Set the mail sender. */
  7. $mail->setFrom('寄件人@gmail.com', '寄件人名稱');
  8.  
  9. /* Add a recipient. */
  10. $mail->addAddress('收件人郵件地址', '收件人名稱');
  11.  
  12. /* Set the subject. */
  13. $mail->Subject = '主旨';
  14.  
  15. /* Set the mail message body. */
  16. $mail->Body = '信件內容';
  17.  
  18. /* SMTP parameters. */
  19. /* Tells PHPMailer to use SMTP. */
  20. $mail->isSMTP();
  21. /* SMTP server address. */
  22. $mail->Host = 'smtp.gmail.com';
  23.  
  24. /* Use SMTP authentication. */
  25. $mail->SMTPAuth = TRUE;
  26. /* Set the encryption system. */
  27. $mail->SMTPSecure = 'tls';
  28. /* SMTP authentication username. */
  29. $mail->Username = '寄件人@gmail.com';
  30. /* SMTP authentication password. google 兩步驟認證的密碼*/
  31. $mail->Password = '密碼';
  32. /* Set the SMTP port. */
  33. $mail->Port = 587;
  34.  
  35. /* Finally send the mail. */
  36. $mail->send();
  37.  
  38. echo "成功發送信件!";
  39. }
  40. catch (Exception $e)
  41. {
  42. echo "發送失敗!";
  43. /* PHPMailer exception. */
  44. echo $e->errorMessage();
  45. }
  46. catch (\Exception $e)
  47. {
  48. echo "發送失敗!";
  49. /* PHP exception (note the backslash to select the global namespace Exception class). */
  50. echo $e->getMessage();
  51. }
  52. ?>

參考資料/來源: https://alexwebdevelop.com/phpmailer-tutorial/ 阿力獅的教室

沒有留言:

張貼留言