|
| 1 | +--- |
| 2 | +title: 通過 OAuth 使用 Gmail 和 git send-email 設置指南 |
| 3 | +date: 2025-04-03 |
| 4 | +--- |
| 5 | + |
| 6 | +## :whale: 背景 |
| 7 | +Gmail 已不再支持使用普通的 SMTP 用戶名和密碼 (smtpUser/smtpPass) 進行認證,必須使用 OAuth 2.0 來授權第三方應用程序訪問 Gmail。 |
| 8 | + |
| 9 | +## :whale: 設置步驟 |
| 10 | + |
| 11 | +### 1. 安裝 Go 語言環境 |
| 12 | +```bash |
| 13 | +# 下載並解壓 Go 到 /usr/local |
| 14 | +sudo tar -C /usr/local -xzf go1.x.x.linux-amd64.tar.gz |
| 15 | + |
| 16 | +# 設置環境變量 (添加到 ~/.bashrc 或 ~/.zshrc) |
| 17 | +export GOPATH=$HOME/go |
| 18 | +export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin |
| 19 | + |
| 20 | +# 應用環境變量 |
| 21 | +source ~/.bashrc # 或 source ~/.zshrc |
| 22 | + |
| 23 | +# 驗證安裝 |
| 24 | +go version |
| 25 | +``` |
| 26 | + |
| 27 | +### 2. 在 Google Cloud 創建 OAuth 憑證 |
| 28 | +1. 訪問 Google Cloud Console |
| 29 | +2. 創建新項目 |
| 30 | +3. 配置 OAuth 同意畫面 |
| 31 | +4. 添加測試用戶 (您的 Gmail 地址) |
| 32 | +5. 添加 `https://mail.google.com/` 作為範圍 (在 "API & Services" > "OAuth consent screen" > "Add or Remove Scopes") |
| 33 | +6. 創建 OAuth 憑證並下載 JSON 文件 |
| 34 | + |
| 35 | +### 3. 設置憑證文件 |
| 36 | +```bash |
| 37 | +# 創建配置目錄並設置權限 |
| 38 | +mkdir -p ${XDG_CONFIG_HOME:-${HOME}/.config}/sendgmail |
| 39 | +chmod 0700 ${XDG_CONFIG_HOME:-${HOME}/.config}/sendgmail |
| 40 | + |
| 41 | +# 移動並重命名憑證文件 |
| 42 | +mv 下載的憑證.json ${XDG_CONFIG_HOME:-${HOME}/.config}/sendgmail/config.json |
| 43 | + |
| 44 | +# 設置文件權限 |
| 45 | +chmod 0600 ${XDG_CONFIG_HOME:-${HOME}/.config}/sendgmail/config.json |
| 46 | +``` |
| 47 | + |
| 48 | +### 4. 安裝 sendgmail 工具 |
| 49 | +```bash |
| 50 | +go install github.com/google/gmail-oauth2-tools/go/sendgmail@latest |
| 51 | +``` |
| 52 | + |
| 53 | +### 5. 設置 sendgmail |
| 54 | +```bash |
| 55 | +# 使用完整路徑 |
| 56 | +$GOPATH/bin/sendgmail -sender=您的郵箱@gmail.com -setup |
| 57 | + |
| 58 | +# 或者如果 $GOPATH/bin 已在 PATH 中 |
| 59 | +sendgmail -sender=您的郵箱@gmail.com -setup |
| 60 | +``` |
| 61 | + |
| 62 | +### 6. 配置 git send-email 使用 sendgmail |
| 63 | +在 `.gitconfig` 文件中添加: |
| 64 | +``` |
| 65 | +[sendemail] |
| 66 | + smtpserver = /home/您的用戶名/go/bin/sendgmail |
| 67 | + smtpserveroption = -sender=您的郵箱@gmail.com |
| 68 | +``` |
| 69 | + |
| 70 | +## :whale: 注意事項 |
| 71 | +- 您需要定期刷新 OAuth 令牌(通常 sendgmail 會自動處理) |
| 72 | +- 如果遇到驗證問題,可能需要重新運行 sendgmail 設置步驟 |
| 73 | +- 確保將 OAuth 憑證文件保存在安全位置,並使用正確的權限保護 |
| 74 | + |
| 75 | +## :whale: 參考資料 |
| 76 | + |
| 77 | +- https://github.com/google/gmail-oauth2-tools/tree/master/go/sendgmail |
0 commit comments