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

如何通过Python的smtplib发送邮件并自动包含Gmail签名?

通过Python发送Gmail邮件时自动附加签名的解决方案

问题描述

我使用Gmail账号通过Python的smtplib发送邮件,已在Gmail网页端配置好签名,但通过脚本发送的邮件并未显示该签名。使用的Python脚本如下:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Gmail credentials
gmail_user = "myemail@gmail.com"
gmail_password = "myapppassword"

# Email subject and body
subject = "Awesome Email"
body = """Hi There,

I hope this message finds you well.

I'm sending you a bulk email with my Gmail signature

Best regards,
Dustin
"""

# Function to send emails
def send_emails(recipients):
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(gmail_user, gmail_password)

        for recipient in recipients:
            msg = MIMEMultipart()
            msg["From"] = gmail_user
            msg["To"] = recipient
            msg["Subject"] = subject
            msg.attach(MIMEText(body, "plain"))
            server.sendmail(gmail_user, recipient, msg.as_string())

        server.quit()
        print("Emails sent successfully!")
    except Exception as e:
        print(f"Error: {e}")

# List of recipient emails
recipients = ["recipient1@example.com", "recipient2@example.com"]

# Trigger the email sending
send_emails(recipients)

原因说明

Gmail网页端/客户端的签名属于账号本地配置,smtplib仅通过SMTP协议发送你构造的原始邮件内容,不会主动调用Gmail的签名附加逻辑,因此不会自动带上账号配置的签名。

解决方案

方法1:手动将签名添加到邮件内容中

这是最简单高效的方案,直接把Gmail里的签名内容追加到邮件body即可,支持纯文本和HTML两种格式:

纯文本格式修改示例

# 把Gmail签名内容复制到这里
signature = """
--
Dustin
Senior Developer
Email: myemail@gmail.com
Website: example.com
"""

# 将签名追加到原body末尾
body = f"""Hi There,

I hope this message finds you well.

I'm sending you a bulk email with my Gmail signature

Best regards,
Dustin
{signature}
"""

HTML格式示例(适配富文本签名)

如果你的签名包含字体样式、图片或链接,建议用HTML构造邮件:

from email.mime.text import MIMEText

# 带格式的HTML签名
html_signature = """
<br>
--<br>
<b>Dustin</b><br>
Senior Developer<br>
<a href="mailto:myemail@gmail.com">myemail@gmail.com</a><br>
<img src="https://example.com/my-signature-logo.png" alt="Personal Logo">
"""

# 组合邮件正文与签名
html_body = f"""<p>Hi There,</p>
<p>I hope this message finds you well.</p>
<p>I'm sending you a bulk email with my Gmail signature</p>
<p>Best regards,<br>Dustin</p>
{html_signature}
"""

# 构造邮件时指定HTML格式
msg.attach(MIMEText(html_body, "html"))

方法2:通过Gmail API自动获取并附加签名

如果需要动态同步Gmail账号中修改的签名,可通过Gmail API拉取签名内容,再插入到邮件中:

  1. 前置配置:在Google Cloud控制台创建项目,启用Gmail API,生成OAuth2凭证(客户端ID和密钥,保存为credentials.json)。
  2. 安装依赖:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
  1. 实现代码:
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64

# 权限范围:读取签名+发送邮件
SCOPES = ['https://www.googleapis.com/auth/gmail.settings.basic', 'https://www.googleapis.com/auth/gmail.send']

def get_gmail_service():
    creds = None
    # 读取已保存的凭证
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 无有效凭证则重新登录授权
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 保存凭证供下次使用
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

def get_gmail_signature(service):
    # 获取默认发件地址的签名
    profile = service.users().getProfile(userId='me').execute()
    default_address = profile['emailAddress']
    send_as = service.users().settings().sendAs().get(userId='me', sendAsEmail=default_address).execute()
    return send_as['signature']

def send_email_with_signature(service, recipient, subject, body):
    signature = get_gmail_signature(service)
    # 组合正文与签名
    html_body = f"{body}<br><br>{signature}"
    
    msg = MIMEMultipart()
    msg['From'] = 'me'
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.attach(MIMEText(html_body, 'html'))
    
    # 转换为Gmail API要求的Base64格式
    raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()
    message = {'raw': raw_message}
    
    service.users().messages().send(userId='me', body=message).execute()

# 主执行逻辑
if __name__ == '__main__':
    service = get_gmail_service()
    recipients = ["recipient1@example.com", "recipient2@example.com"]
    subject = "Awesome Email"
    body = """<p>Hi There,</p>
<p>I hope this message finds you well.</p>
<p>I'm sending you a bulk email with my Gmail signature</p>
<p>Best regards,<br>Dustin</p>"""
    
    for recipient in recipients:
        send_email_with_signature(service, recipient, subject, body)
    print("Emails sent successfully!")

总结

  • 若签名长期不变,手动添加到邮件内容是最优选择,无需额外依赖和配置。
  • 若需动态同步Gmail账号的签名设置,使用Gmail API是唯一可行方案,但需完成OAuth2授权配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:48:11