Send Bulk Emails (Python Script) #15
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 文件路径: .github/workflows/send-emails.yml | |
| # 描述: 优化为高效的批处理模式,每批发送4封邮件,一个批次完成后立刻开始下一个。 | |
| name: Send Bulk Emails (Python Script - Batch Mode) | |
| on: | |
| workflow_dispatch: | |
| jobs: | |
| # 第一步:准备收件人批次 | |
| prepare-recipient-batches: | |
| runs-on: ubuntu-latest | |
| outputs: | |
| matrix: ${{ steps.set-matrix.outputs.matrix }} | |
| steps: | |
| - uses: actions/checkout@v4 | |
| - name: Prepare recipient batches | |
| id: set-matrix | |
| run: | | |
| # 核心逻辑:这里的 jq 命令会将收件人列表分割成每组4个的小数组(批次) | |
| echo "matrix=$(grep -v '^$' recipients.csv | jq -Rsc 'split("\n") | map(split(",")) | map(select(.[0] and .[0] != "")) | map({email: .[0], name: .[1]}) | [range(0; length; 4) as $i | .[$i:$i+4]]')" >> $GITHUB_OUTPUT | |
| # 第二步:按批次发送邮件 | |
| send-mail-batch: | |
| needs: prepare-recipient-batches | |
| runs-on: ubuntu-latest | |
| strategy: | |
| # 确保批次之间是串行执行的(一次处理一个批次) | |
| max-parallel: 1 | |
| matrix: | |
| # matrix.batch 现在是收件人对象的一个数组,例如 [{email:"a", name:"n1"}, {email:"b", name:"n2"}, ...] | |
| batch: ${{ fromJson(needs.prepare-recipient-batches.outputs.matrix) }} | |
| fail-fast: false | |
| steps: | |
| - uses: actions/checkout@v4 | |
| - name: "Send email for batch of ${{ fromJson(tojson(matrix.batch)) && fromJson(tojson(matrix.batch)).length || 0 }} recipients" | |
| env: | |
| # 将 secrets 传递给脚本 | |
| MAIL_USERNAME: ${{ secrets.MAIL_USERNAME }} | |
| MAIL_PASSWORD: ${{ secrets.MAIL_PASSWORD }} | |
| # 将当前批次的收件人列表(JSON格式)传递给脚本 | |
| RECIPIENT_BATCH_JSON: ${{ toJSON(matrix.batch) }} | |
| run: | | |
| echo "Processing a new batch..." | |
| # 使用 jq 解析 JSON 数组,并用一个 while 循环为批次中的每个收件人发送邮件 | |
| # & 符号让 python 脚本在后台并行运行 | |
| echo "$RECIPIENT_BATCH_JSON" | jq -c '.[]' | while read -r recipient; do | |
| email=$(echo "$recipient" | jq -r '.email') | |
| name=$(echo "$recipient" | jq -r '.name') | |
| echo "--> Queuing email for: $name <$email>" | |
| # 在后台运行 Python 脚本 | |
| python send_email.py "$email" "$name" "b5a5723ca5a99989de0439dc64f6e1a303db1b83_2_1380x920.jpeg" & | |
| done | |
| # wait 命令会等待这个批次所有在后台运行的 python 脚本全部执行完毕 | |
| wait | |
| echo "Batch finished." | |