You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用带全域权限的服务账户通过Gmail API自定义From字段(Python)

问题

我有一个通过Gmail API发送邮件的Web应用,使用具备全域访问权限的服务账户模拟用户账户user@site.com发送邮件。邮件发送正常,但希望设置自定义"From"字段(如"Custom From" <custom.from@site.com>)。不过在MIMEText消息中设置的From标签被覆盖,收到的邮件仍显示From为user@site.com。怀疑是服务账户模拟时覆盖了MIME消息字段,请问能否修改此行为?是否API内置了反伪造机制?

相关代码:

import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from googleapiclient.discovery import build
from google.oauth2 import service_account

creds = service_account.Credentials.from_service_account_file(
            'path/to/service/account/file.json', 
            scopes=['https://www.googleapis.com/auth/gmail.send'])
creds = creds.with_subject('user@site.com')  ## 模拟用户

service = build('gmail', 'v1', credentials=creds)

msg = MIMEMultipart('alternative')
msg.attach(MIMEText("<h1>Test message</h1>", 'html'))
msg.attach(MIMEText("Test message", 'plain'))
msg['Subject'] = 'Test subject'
msg['Bcc'] = 'recipient@recipient.com'

msg['reply-to'] = 'custom.from@site.com'  ## 这个设置正常生效
msg['From'] = '"Custom From" <custom.from@site.com>'  ## 被覆盖的自定义From字段

create_message = {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()}
service.users().messages().send(userId="me", body=create_message).execute()

收到的邮件内容片段:

...
MIME-Version: 1.0
reply-to: custom.from@site.com
From: user@site.com
...
解决方案

Gmail API确实内置了反伪造机制,当通过服务账户模拟用户发送邮件时,会强制将From字段设置为被模拟的用户账户(user@site.com)。这是为了符合SPF、DKIM等邮件认证规范,避免邮件被收件方标记为垃圾邮件或伪造邮件。

要实现自定义发件人显示效果,有两种可行方法:

方法一:为被模拟用户添加邮件别名

若你有权限操作user@site.com的Gmail账户,可将custom.from@site.com添加为该账户的官方别名:

  1. 登录user@site.com的Gmail账号
  2. 进入「设置」>「账号和导入」>「发送邮件为」>「添加另一个邮箱地址」
  3. 按照流程完成邮箱验证,将custom.from@site.com添加为有效别名

添加完成后,再通过API发送邮件时,设置的自定义From字段(别名)将不会被覆盖,收件人会看到"Custom From" <custom.from@site.com>作为发件人。

方法二:自定义显示名称+回复地址组合

如果无法添加别名,可保留From字段为user@site.com,但自定义显示名称,同时配合Reply-To字段引导回复到目标邮箱:
修改代码中的From字段为:

msg['From'] = '"Custom From" <user@site.com>'

同时保留已设置的msg['reply-to'] = 'custom.from@site.com',这样收件人看到的发件人显示为「Custom From」,回复时邮件会自动发送到custom.from@site.com。

内容的提问来源于stack exchange,提问作者cambridgecircus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:31:11