Điều kiện tiên quyết
Một dự án Google Cloud đã bật tính năng thanh toán
Một tài khoản Mailtarget có quyền truy cập API
API Vertex AI đã được kích hoạt trên dự án GCP của bạn
Đã cài đặt Python 3.10 trở lên
Một tên miền công ty do bạn sở hữu (ví dụ: yourcompany.com)
⚠️ Yêu cầu Tên miền Công ty
Bạn phải sử dụng tên miền công ty của riêng mình để gửi email (ví dụ: [email protected]). Các tên miền email miễn phí như Gmail, Yahoo, Outlook hoặc bất kỳ nhà cung cấp email công cộng nào đều không được phép sử dụng làm địa chỉ gửi email.
Tên miền của bạn có thể được lưu trữ trên bất kỳ nhà cung cấp nào — Google Workspace, Microsoft 365, Cloudflare hoặc bất kỳ nhà cung cấp dịch vụ DNS nào. Miễn là bạn sở hữu tên miền và có thể cấu hình các bản ghi DNS của nó, bạn có thể sử dụng được.
💡 Chúng tôi đặc biệt khuyên bạn nên sử dụng tên miền phụ (ví dụ: mail.yourcompany.com) hoặc một tên miền chuyên dụng mới để gửi email. Điều này giúp bảo vệ danh tiếng của tên miền chính và cung cấp cho bạn một môi trường an toàn để thử nghiệm.
Thiết lập môi trường GCP của bạn
Cài đặt Google Cloud CLI và xác thực:
# Install gcloud CLI (if not already installed)
# https://cloud.google.com/sdk/docs/install
# Authenticate
gcloud auth login
gcloud auth application-default login
# Set your project
gcloud config set project YOUR_PROJECT_ID
# Enable Vertex AI API gcloud services enable aiplatform.googleapis.comLấy mã API Mailtarget của bạn
a. Đăng nhập vào app.mailtarget.co
b. Vào Cài đặt → Mã API
c. Nhấp vào Tạo mã API
d. Sao chép mã
export MAILTARGET_API_KEY=your_api_key_here
Cài đặt các phần phụ thuộc
pip install google-cloud-aiplatform requests
Định nghĩa công cụ Mailtarget
Tạo một hàm Python mà tác nhân Vertex AI của bạn sẽ sử dụng để gửi email:
import requests
import os
def send_email(
to_email: str,
to_name: str,
subject: str,
body_html: str,
body_text: str = ""
) -> dict:
"""Send an email via Mailtarget API.
Args:
to_email: Recipient email address.
to_name: Recipient name.
subject: Email subject line.
body_html: HTML content of the email.
body_text: Plain text fallback (optional).
Returns:
dict with transmissionId on success, or error details.
"""
response = requests.post(
"https://transmission.mailtarget.co/v1/layang/transmissions",
headers={
"Authorization": f"Bearer {os.environ['MAILTARGET_API_KEY']}",
"Content-Type": "application/json"
},
json={
"to": [{"email": to_email, "name": to_name}],
"from": {
"email": "[email protected]",
"name": "Your Company"
},
"subject": subject,
"bodyHtml": body_html,
"bodyText": body_text,
"optionsAttributes": {
"openTracking": True,
"clickTracking": True,
"transactional": True
}
}
)
return response.json()Thay thế [email protected] và Your Company bằng tên miền gửi đã được xác minh và tên công ty của bạn.
Tạo tác nhân Vertex AI
Kết nối công cụ với tác nhân Vertex AI bằng cách sử dụng Bộ công cụ phát triển tác nhân (ADK) hoặc LangChain:
Phương án A: Sử dụng Google ADK
from google.adk.agents import Agent
agent = Agent(
name="email_agent",
model="gemini-2.0-flash",
description="An agent that sends emails via Mailtarget.",
instruction="""You are an email assistant. When asked to send
an email, use the send_email tool. Write professional HTML
emails with clean formatting. Always confirm the transmissionId
after sending.""",
tools=[send_email],
)
# Run the agent
response = agent.run(
"Send a welcome email to [email protected] (John Smith) "
"with a friendly onboarding message."
)
print(response)Phương án B: Sử dụng LangChain
from langchain_google_vertexai import ChatVertexAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.tools import tool
from langchain_core.prompts import ChatPromptTemplate
@tool
def send_email(to_email: str, to_name: str, subject: str,
body_html: str, body_text: str = "") -> dict:
"""Send an email via Mailtarget API."""
import requests, os
response = requests.post(
"https://transmission.mailtarget.co/v1/layang/transmissions",
headers={
"Authorization": f"Bearer {os.environ['MAILTARGET_API_KEY']}",
"Content-Type": "application/json"
},
json={
"to": [{"email": to_email, "name": to_name}],
"from": {"email": "[email protected]",
"name": "Your Company"},
"subject": subject,
"bodyHtml": body_html,
"bodyText": body_text,
"optionsAttributes": {"openTracking": True,
"clickTracking": True}
}
)
return response.json()
llm = ChatVertexAI(model="gemini-2.0-flash")
prompt = ChatPromptTemplate.from_messages([
("system", "You are an email assistant. Use the send_email "
"tool when asked to send emails."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm, [send_email], prompt)
executor = AgentExecutor(agent=agent, tools=[send_email])
result = executor.invoke({
"input": "Send a welcome email to [email protected] (John Smith) "
"with a friendly onboarding message."
})
print(result["output"])Triển khai lên Vertex AI Agent Engine (Môi trường sản xuất)
Để triển khai lên môi trường sản xuất, hãy sử dụng Vertex AI Agent Engine:
import vertexai
from vertexai import agent_engines
vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")
# Deploy the agent
remote_agent = agent_engines.create(
agent_engine=agent,
requirements=["requests"],
display_name="Mailtarget Email Agent",
)
# Query the deployed agent
session = remote_agent.create_session(user_id="user-1")
response = remote_agent.stream_query(
session=session,
message="Send a test email to [email protected]"
)
for chunk in response:
print(chunk)
🚀 Những gì bạn vừa xây dựng
Trợ lý AI Vertex của bạn giờ đây có thể tự động:
Viết nội dung email theo bất kỳ phong cách hoặc giọng điệu nào
Thiết kế email HTML với định dạng phù hợp
Gửi qua cơ sở hạ tầng sản xuất của Mailtarget
Theo dõi lượt mở và lượt nhấp chuột tự động
Mở rộng quy mô trên môi trường chạy được quản lý của Google Cloud
Điều gì đang xảy ra bên trong?
Bạn cho tác nhân biết cần gửi gì và gửi cho ai
Vertex AI viết nội dung, tạo mã HTML, gọi công cụ Mailtarget
Mailtarget xử lý việc gửi, xác thực (SPF/DKIM/DMARC), theo dõi và đảm bảo độ tin cậy
Nâng cao: Thêm nhiều công cụ Mailtarget hơn
Mở rộng khả năng của tác nhân với các chức năng bổ sung:
def list_sending_domains() -> dict:
"""List all verified sending domains in Mailtarget."""
response = requests.get(
"https://transmission.mailtarget.co/v1/domain/sending",
headers={"Authorization": f"Bearer {os.environ['MAILTARGET_API_KEY']}"}
)
return response.json()
def create_template(template_id: str, name: str, html: str) -> dict:
"""Create a reusable email template in Mailtarget."""
response = requests.post(
"https://transmission.mailtarget.co/v1/template",
headers={
"Authorization": f"Bearer {os.environ['MAILTARGET_API_KEY']}",
"Content-Type": "application/json"
},
json={"id": template_id, "name": name, "html": html}
)
return response.json()
def send_template_email(to_email: str, to_name: str,
subject: str, template_id: str,
substitution_data: dict) -> dict:
"""Send an email using a stored Mailtarget template."""
response = requests.post(
"https://transmission.mailtarget.co/v1/layang/transmissions",
headers={
"Authorization": f"Bearer {os.environ['MAILTARGET_API_KEY']}",
"Content-Type": "application/json"
},
json={
"to": [{"email": to_email, "name": to_name}],
"from": {"email": "[email protected]",
"name": "Your Company"},
"subject": subject,
"templateId": template_id,
"substitutionData": substitution_data
}
)
return response.json()
Thêm các công cụ này vào danh sách công cụ của người đại lý để có đầy đủ khả năng quản lý email.
Khắc phục sự cố
Sự cố | Khắc phục |
| Kiểm tra xem khóa API Mailtarget của bạn có chính xác và MAILTARGET_API_KEY đã được thiết lập chưa |
| Xác minh địa chỉ email người gửi sử dụng tên miền công ty đã được xác thực |
Email không đến | Kiểm tra thư mục thư rác; xác minh bản ghi SPF/DKIM cho tên miền của bạn |
Lỗi quyền truy cập Vertex AI | Đảm bảo aiplatform.googleapis.com được bật và bạn đã được xác thực |
Tác nhân không gọi được công cụ | Kiểm tra chuỗi tài liệu của hàm — Gemini sử dụng nó để quyết định khi nào gọi công cụ |
Tên miền email miễn phí bị từ chối | Sử dụng tên miền công ty của bạn — Gmail, Yahoo, Outlook, v.v. không được phép |

