smtp-gateway
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSMTP Gateway (Inbound Email)
SMTP Gateway(入站电子邮件)
What This Is
这是什么
An SMTP gateway is an off-chain mail server that accepts email addressed to a canister and delivers it by calling the canister's method, the way the HTTP gateway calls . DFINITY operates the gateways that mail for reaches, alongside its HTTP gateways; others can run their own, since the gateway is part of . The limits and sender checks in this skill are those of DFINITY's gateways. A canister opts in by implementing two methods. There is nothing to register for addresses. Mail flows in only: a canister cannot send email through the gateway, and it never receives bounce messages either, because the gateway rejects the null sender ().
smtp_requesthttp_request<canister-id>.icp0.ioic-gateway<canister-id>.icp0.ioMAIL FROM:<>The protocol is specified in in , and the gateway that implements it is the module of .
candid/smtp_gateway.diddfinity/ic-smtp-gateway-protocolsmtpdfinity/ic-bn-libSMTP gateway 是一个链下邮件服务器,它接受发往某个 canister 的电子邮件,并通过调用该 canister 的 方法来投递邮件,就像 HTTP gateway 调用 一样。DFINITY 运营着这些 gateway,使发往 的邮件能够送达;它也运营 HTTP gateway,其他人也可以运行自己的 gateway,因为该 gateway 属于 的一部分。本 skill 中讨论的限制和发件人检查均适用于 DFINITY 的 gateway。canister 只需实现两个方法即可选择启用。无需为 地址进行任何注册。邮件只向内流动:canister 无法通过 gateway 发送邮件,也永远不会收到退信,因为 gateway 会拒空发件人()。
smtp_requesthttp_request<canister-id>.icp0.ioic-gateway<canister-id>.icp0.ioMAIL FROM:<>该协议在 的 中定义,实现该协议的 gateway 是 的 模块。
dfinity/ic-smtp-gateway-protocolcandid/smtp_gateway.diddfinity/ic-bn-libsmtpAddressing
地址
| Address | Setup |
|---|---|
| None. Every |
| The domain must be registered as an IC custom domain ( |
How the gateway routes a recipient:
- If the first DNS label of the recipient's domain parses as a principal, that is the canister. Otherwise the exact domain is looked up among registered custom domains. No match:
550 5.1.1 Unknown recipient domain. - The domain arrives lowercased. The local part () arrives verbatim: case,
usersuffixes and quotes are kept. Match it case-insensitively unless you have a reason not to. The gateway rejects non-ASCII local parts itself.+tag - Handing mail to another canister. Before calling the addressed canister, the gateway fetches . If that returns a 2xx response whose body (whitespace-trimmed) is a principal, every SMTP call goes to that principal instead. Any failure falls back to the addressed canister, and either result is cached for 10 minutes. Use this when a frontend canister owns the domain and a backend canister handles mail: with the
https://<canister-id>.icp0.io/.well-known/ic-smtp-canister-idrecipe, add a filestatic-sitecontaining only the backend's canister ID to the uploaded directory (.well-known/ic-smtp-canister-idis uploaded without extra configuration)..well-known/
| 地址 | 设置 |
|---|---|
| 无需设置。每个 |
| 域名必须注册为 IC 自定义域名( |
gateway 路由收件人的方式如下:
- 如果收件人域名的第一个 DNS label 可解析为 principal,那么该 principal 就是目标 canister。否则,会在已注册的自定义域名中查找完全匹配的域名。没有匹配项时返回:
550 5.1.1 Unknown recipient domain. - 域名到达时会被转为小写。本地部分()会原样到达:大小写、
user后缀和引号都会保留。除非有特殊原因,否则应不区分大小写地进行匹配。gateway 本身会拒绝非 ASCII 本地部分。+tag - 将邮件移交给另一个 canister。 在调用目标 canister 之前,gateway 会获取 。如果响应状态为 2xx,且去除首尾空白后的正文是一个 principal,那么所有 SMTP 调用都会转交给该 principal。任何失败都会回退到最初的目标 canister。无论最终使用哪个结果,都会缓存 10 分钟。当 frontend canister 拥有域名而 backend canister 负责处理邮件时,可以使用此方式:对于
https://<canister-id>.icp0.io/.well-known/ic-smtp-canister-idrecipe,只需在上传目录中添加static-site文件,其中仅包含 backend 的 canister ID(无需额外配置即可上传.well-known/ic-smtp-canister-id)。.well-known/
The Protocol
协议
| Method | Required | When the gateway calls it |
|---|---|---|
| Yes (see Pitfall 4) | Once per |
| Yes | After |
| No | Chunked upload for messages over the ~2 MiB ingress limit. Read |
What each call carries:
| Field | | |
|---|---|---|
| | |
| | Headers and raw body |
| | A new UUIDv7 for every SMTP transaction |
The wire types are defined in . The Rust crate exports them, and the Motoko example below declares them field for field. is (a does not decode), the variant labels are exactly and , and carries an empty record, not .
candid/smtp_gateway.didcodenat64nat32OkErrOknull| 方法 | 是否必需 | gateway 何时调用 |
|---|---|---|
| 是(见问题 4) | 每个 |
| 是 | 在 |
| 否 | 用于上传超过约 2 MiB ingress 限制的消息。实现这些方法前请阅读 |
每次调用所携带的内容:
| 字段 | | |
|---|---|---|
| | |
| | Headers 和原始 body |
| | 每个 SMTP transaction 都会生成一个新的 UUIDv7 |
线路类型在 中定义。Rust crate 会导出这些类型,下面的 Motoko 示例也逐字段声明了它们。 是 (使用 将无法解码),variant labels 必须恰好为 和 ,并且 携带一个空 record,而不是 。
candid/smtp_gateway.didcodenat64nat32OkErrOknullReply Codes Are the Interface
回复码就是协议接口
The gateway acts on the class of : 500–599 is permanent and anything else is temporary. Traps and call failures are temporary too, except two that are permanent: the method is not exported, or the request is too large for one ingress message.
SmtpRequestError.codeDuring , from :
RCPT TOsmtp_request_validate| Canister result | The sending server sees |
|---|---|
| |
| |
| |
| |
| Method not exported | |
| Trap or call failure | |
After , from :
DATAsmtp_request| Canister result | The sending server sees | Then |
|---|---|---|
| | Delivered |
| | The sender gets a bounce |
| | The sending server retries later |
| Trap, call failure, or no reply within 90 s | | Retried |
Codes to use. Permanent: 550 no such mailbox (reserved, never for anything else), 501 a required field is missing, 552 message, headers or recipient list too large, 554 content rejected, 530 caller not authorized. Temporary: 450 try again later, 452 out of storage.
gateway 根据 的类别采取行动:500–599 表示永久错误,其他任何代码都表示临时错误。Trap 和调用失败也属于临时错误,但有两个例外:方法未导出,或请求对于单条 ingress 消息而言过大,这两种情况属于永久错误。
SmtpRequestError.code在 阶段,来自 的结果如下:
RCPT TOsmtp_request_validate| Canister 结果 | 发送服务器看到的内容 |
|---|---|
| |
| 仅针对该收件人返回 |
| |
| |
| 方法未导出 | |
| Trap 或调用失败 | |
在 之后,来自 的结果如下:
DATAsmtp_request| Canister 结果 | 发送服务器看到的内容 | 后续处理 |
|---|---|---|
| | 已投递 |
| | 发件人会收到退信 |
| | 发送服务器稍后会重试 |
| Trap、调用失败或 90 秒内未回复 | | 重试 |
应使用的代码。永久错误:550 表示邮箱不存在(已保留,不能用于其他任何情况),501 表示缺少必填字段,552 表示消息、headers 或收件人列表过大,554 表示内容被拒绝,530 表示调用方未获授权。临时错误:450 表示稍后重试,452 表示存储空间不足。
Mistakes That Break Mail Delivery
会破坏邮件投递的问题
-
Trapping instead of returning. A trap is reported as a temporary failure, so the sending server retries for days before it gives up with an unhelpful error. Every rejection must be a returned
Err. Traps hide inErr,unwrap(), out-of-range slicing,expect()inside a multi-byte character, a nestedString::truncateborrow, and in Motoko inRefCellunderflow and array indexing.Nat -
Reporting a permanent problem with a non-5xx code. Only 500–599 bounces. A deterministic rejection sent as 4xx, or as any code outside 400–599, is retried until the sender's server gives up, and the sender never learns why.
-
Using 550 for anything except "unknown mailbox". From, 550 becomes
smtp_request_validateand your text is dropped. Use another 5xx code (552, 554) for policy rejections so that your message reaches the sender.550 5.1.2 Mailbox does not exist. -
Skipping. The gateway calls it on every
smtp_request_validateand treats a missing method as a permanent "does not support SMTP protocol" rejection of every recipient. Implement both methods. (RCPT TOis genuinely optional: a missing method just means no chunked upload.)smtp_capabilities -
Requiringor
messageinmessage_id. It receives onlysmtp_request_validate, with exactly one recipient. Requiring the other fields rejects every recipient.envelope -
Trusting Candid to validate the request. Everyfield is
SmtpRequest, so any record argument decodes into it, with all fieldsopt. Check each field you need and return 501 when it is missing.null -
Forgetting that anyone can call the SMTP methods. They are public: any principal can call them directly with any envelope, headers and body, bypassing every check a gateway makes. To restrict who delivers mail, check the caller's principal. For example, to accept mail only through the DFINITY-operated gateway, allow only(plus controllers, for testing), as both examples do. For another gateway, ask its operator for its principal, or don't restrict callers. Reject with 530, never by trapping, because the gateway would retry. Either way, bound every input (Internet Identity allows 100 headers, 8 KiB per header value, 64 bytes per local part) and cap stored mail.
ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae -
Trusting the sender's address. DFINITY's gateways reject mail that fails SPF for the envelope sender's domain, and mail whose DKIM signatures all fail. They do accept senders without an SPF record and unsigned mail, they do not check that the signing domain matches(no DMARC), and no result reaches the canister (
Fromis alwaysgateway_flags). Sonull, andFromfor domains without SPF, is still whatever the client claimed. If the sender's identity matters, verify DKIM inside the canister, as Internet Identity does: relaxed header canonicalization (names arrive normalized, soenvelope.fromcannot be verified); the public key fetched with DNS-over-HTTPS outcalls (simpleskill) and accepted only when several resolvers agree; the signing domainhttps-outcallsaligned withd=; duplicateFrom,FromorSubjectheaders rejected, since a duplicate header can smuggle content past the signature.DKIM-Signature -
Expecting clean, decoded header values. Each value is the raw text after the colon: the leading space, the trailingor
\r\n, folded continuation lines and\nencoded words are all left in. Trim before comparing, decode encoded words yourself if you display them, and match header names case-insensitively: names the gateway recognizes arrive in canonical case (=?UTF-8?B?...?=asfRoM). Order and duplicates are preserved; a header whose value is not valid UTF-8 is dropped.From -
Expecting a parsed body.holds the raw bytes after the header block, with CRLF line endings, and no MIME processing. Mail from a normal client is usually
bodywith base64 or quoted-printable parts: you receive the boundaries and encoded parts, not plain text.multipart/alternative -
Deduplicating on. It identifies one SMTP transaction, not one email: when the sending server retries, the retry gets a new
message_id. Delivery is at-least-once. A lost reply after you stored the mail, the 90-second delivery timeout, or a failure at another canister receiving the same message (the gateway fails the whole message and the sender retries for every recipient) all lead to redelivery. If duplicates matter, deduplicate on the RFC 5322message_idheader (chosen by the sender, so scope it per sender) or make processing idempotent.Message-ID -
Awaiting inside. The gateway keeps the SMTP session open while it waits and gives up after 90 seconds. That is reported as temporary and retried, so if your call did finish, the mail arrives twice. Every
smtp_requestis also an interleaving point (awaitskill). Accept synchronously and defer slow work, for example to a timer. Internet Identity stores the message and finishes its DKIM key lookups after it has replied.canister-security -
Long or multi-line error messages. Theis copied into the SMTP reply line: on
messageit is cut at about 224 bytes without stripping CR or LF, and a delivery reply over about 220 bytes can be dropped. Use short, single-line ASCII and never echo request content.RCPT TO -
Leaking secrets through error codes. Everytells the caller something, and a 5xx also sends a bounce to the claimed sender. If mail carries secrets such as verification codes, return
Errfor unknown or invalid content and record the outcome internally. Internet Identity returnsOkonly for malformed requests, more than one recipient, and unknown mailboxes.Err -
Keeping mail on the heap, or configuration in stable variables. Heap state is lost on upgrade, so store mail in stable memory (skill). In a Motoko
stable-memorythe opposite applies: a plainpersistent actoris stable and keeps its first-install value, so a mailbox list or limit you change in code has no effect after an upgrade. Declare configurationlet.transient let
-
返回之前发生 Trap。 Trap 会被报告为临时失败,因此发送服务器可能持续重试数天,最终才以含义不明确的错误放弃。每次拒绝都必须通过返回
Err完成。Trap 可能隐藏在Err、unwrap()、越界切片、在多字节字符内部调用expect()、嵌套String::truncate借用等位置;在 Motoko 中还可能出现在RefCell下溢和数组索引中。Nat -
使用非 5xx 代码报告永久问题。 只有 500–599 会触发退信。将确定性拒绝报告为 4xx,或报告为 400–599 范围之外的任何代码,都会导致重试,直到发件服务器放弃,而发件人始终无法得知原因。
-
将 550 用于“未知邮箱”以外的情况。 在中,550 会变成
smtp_request_validate,并且你的文本会被丢弃。对于策略性拒绝,应使用其他 5xx 代码(如 552、554),以便将原因传达给发件人。550 5.1.2 Mailbox does not exist. -
跳过。 gateway 会在每个
smtp_request_validate阶段调用它,并将方法缺失视为永久的“does not support SMTP protocol”拒绝,从而拒绝所有收件人。必须实现这两个方法。(RCPT TO确实是可选的:方法缺失只意味着不支持分块上传。)smtp_capabilities -
在中要求提供
smtp_request_validate或message。 它只会收到message_id,其中恰好包含一个收件人。要求提供其他字段会导致所有收件人都被拒绝。envelope -
信任 Candid 验证请求。 每个字段都是
SmtpRequest,因此任何 record 参数都可以解码为该类型,并且所有字段均为opt。应检查所需的每个字段,缺少时返回 501。null -
忘记任何人都可以调用 SMTP 方法。 这些方法是公开的:任何 principal 都可以直接使用任意 envelope、headers 和 body 调用它们,绕过 gateway 执行的每项检查。若要限制由谁投递邮件,应检查调用方 principal。例如,如果只接受通过 DFINITY 运营的 gateway 投递的邮件,可以仅允许(测试时还可允许 controllers),两个示例均采用此方式。对于其他 gateway,应向其运营方询问 principal,或者不限制调用方。应返回 530 进行拒绝,绝不能通过 trap 拒绝,否则 gateway 会重试。无论采用哪种方式,都必须限制每项输入的大小(Internet Identity 允许 100 个 headers、每个 header value 8 KiB、每个本地部分 64 字节),并限制已存储邮件的容量。
ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae -
信任发件人的地址。 DFINITY 的 gateway 会拒绝 envelope sender 域名未通过 SPF 检查的邮件,以及所有 DKIM signatures 均验证失败的邮件。它们仍会接受没有 SPF record 的发件人和未签名的邮件,不会检查签名域名是否与一致(没有 DMARC),并且任何检查结果都不会传递给 canister(
From始终为gateway_flags)。因此,对于没有 SPF 的域名,null和From仍然只是客户端声称的内容。如果发件人身份很重要,应像 Internet Identity 一样在 canister 内验证 DKIM:使用 relaxed header canonicalization(header 名称到达时已标准化,因此无法验证envelope.from);通过 DNS-over-HTTPS outcalls(simpleskill)获取公钥,并且仅在多个 resolver 达成一致时才接受;签名域名https-outcalls必须与d=对齐;拒绝重复的From、From或Subjectheaders,因为重复 header 可能让内容绕过签名验证。DKIM-Signature -
期望 header values 已被清理和解码。 每个 value 都是冒号后的原始文本:前导空格、末尾的或
\r\n、折行 continuation lines,以及\nencoded words 都会原样保留。比较前应先执行 trim,如果需要展示,应自行解码 encoded words,并且匹配 header 名称时应不区分大小写:gateway 识别的 header 名称会以 canonical case 到达(=?UTF-8?B?...?=会变成fRoM)。顺序和重复项都会保留;value 不是有效 UTF-8 的 header 会被丢弃。From -
期望 body 已被解析。保存 header block 之后的原始字节,使用 CRLF 行尾,并且没有经过 MIME 处理。普通客户端发送的邮件通常是
body,并包含 base64 或 quoted-printable parts:收到的是 boundaries 和编码后的 parts,而不是纯文本。multipart/alternative -
根据去重。 它标识的是一次 SMTP transaction,而不是一封电子邮件:发送服务器重试时,重试消息会获得新的
message_id。投递语义是 at-least-once。在存储邮件后丢失回复、触发 90 秒投递超时,或者另一个接收同一消息的 canister 发生失败(gateway 会使整封消息失败,并向每个收件人对应的发件人发起重试),都可能导致重复投递。如果重复消息值得关注,可以根据 RFC 5322message_idheader 去重(该值由发件人选择,因此应按发件人限定范围),或者让处理逻辑具备幂等性。Message-ID -
在中执行
smtp_request。 gateway 会保持 SMTP 会话开启并等待,90 秒后放弃等待。这会被报告为临时错误并触发重试,因此如果调用最终完成,邮件将到达两次。每个await同时也是一次 interleaving point(awaitskill)。应同步接受请求,并将耗时工作推迟处理,例如交给 timer。Internet Identity 会先存储消息,完成 DKIM key lookups 后再回复。canister-security -
错误消息过长或包含多行。会被复制到 SMTP reply line:在
message阶段,它会在约 224 bytes 处被截断,且不会去除 CR 或 LF;超过约 220 bytes 的投递回复可能会被丢弃。应使用简短的单行 ASCII 文本,绝不要回显请求内容。RCPT TO -
通过错误代码泄露秘密。 每个都会向调用方透露某些信息,而 5xx 还会向声称的发件人发送退信。如果邮件包含验证码等秘密,对于未知或无效内容应返回
Err,并在内部记录结果。Internet Identity 仅在请求格式错误、收件人超过一个或邮箱未知时返回Ok。Err -
将邮件保留在 heap 中,或将配置保存在 stable variables 中。 Heap state 会在升级时丢失,因此应将邮件存储在 stable memory(skill)中。在 Motoko
stable-memory中则恰好相反:普通persistent actor是 stable 的,并会保留首次安装时的值,因此在代码中修改邮箱列表或限制后,升级不会应用这些变更。应将配置声明为let。transient let
Implementation
实现
Both examples accept mail for and only through the DFINITY-operated gateway (and from controllers, for testing; this restriction is optional, see Pitfall 7), store each message, and apply the pitfalls above. and share one envelope check because the query may be stale by the time the update runs.
support@hello@smtp_request_validatesmtp_request两个示例都仅通过 DFINITY 运营的 gateway 接受发往 和 的邮件(测试时也允许 controllers;此限制是可选的,见问题 7),存储每封邮件,并处理上述问题。 和 共用一项 envelope 检查,因为 query 执行时得到的状态可能在 update 执行前已经过期。
support@hello@smtp_request_validatesmtp_requestRust
Rust
The crate provides the protocol types. It builds for .
ic-smtp-gateway-protocolwasm32-unknown-unknowntoml
[package]
name = "backend"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
candid = "0.10"
ic-cdk = "0.20"
ic-smtp-gateway-protocol = "0.1"Deploy it with the recipe as canister ( skill).
@dfinity/rust@v3.3.0backendicp-clirust
use std::{cell::RefCell, collections::BTreeMap};
use ic_cdk::{
api::{is_controller, msg_caller, time},
query, update,
};
use ic_smtp_gateway_protocol::{
Envelope, Header, SmtpOk, SmtpRequest, SmtpRequestError, SmtpResponse,
};
/// Principal of DFINITY's SMTP gateways; gateways run by others have their own.
const SMTP_GATEWAY: &str = "ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae";
/// Local parts this canister accepts mail for.
const MAILBOXES: &[&str] = &["support", "hello"];
// Bounds on what one request may cost this canister.
const MAX_RECIPIENTS: usize = 10;
const MAX_HEADERS: usize = 100;
const MAX_BODY_BYTES: usize = 100_000;
const MAX_STORED: usize = 10_000;
#[allow(dead_code)] // read by your application logic
struct Mail {
envelope_from: String, // unauthenticated: see pitfalls
subject: String,
headers: Vec<Header>,
body: Vec<u8>, // raw RFC 5322 body bytes, MIME not decoded
received_at: u64,
}
thread_local! {
// Heap only for brevity: use stable structures in production.
static INBOX: RefCell<BTreeMap<String, Mail>> = RefCell::default();
}
/// Keep `message` short, single-line ASCII: the gateway copies it into the
/// SMTP reply line.
fn err(code: u64, message: &str) -> SmtpResponse {
SmtpResponse::Err(SmtpRequestError {
code,
message: message.to_string(),
})
}
/// Optional: accept mail only through DFINITY's gateways (plus
/// controllers, for testing). Drop this check to accept any gateway. Return
/// 530 rather than trapping, which would read as a temporary failure.
fn check_caller() -> Result<(), SmtpResponse> {
let caller = msg_caller();
if caller.to_text() == SMTP_GATEWAY || is_controller(&caller) {
Ok(())
} else {
Err(err(530, "unauthorized caller"))
}
}
/// Header names are case-insensitive. Values arrive as the raw text after the
/// colon: leading space and line ending included, RFC 2047 not decoded.
fn header<'a>(headers: &'a [Header], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case(name))
.map(|h| h.value.trim())
}
fn is_mailbox(user: &str) -> bool {
MAILBOXES.iter().any(|m| m.eq_ignore_ascii_case(user))
}
/// Shared by both entry points: smtp_request must re-check everything
/// smtp_request_validate checked, because the state may have changed since.
fn check_envelope(env: &Envelope) -> Result<(), SmtpResponse> {
if env.to.is_empty() {
return Err(err(501, "no recipients"));
}
if env.to.len() > MAX_RECIPIENTS {
return Err(err(552, "too many recipients"));
}
if env.to.iter().any(|rcpt| !is_mailbox(&rcpt.user)) {
return Err(err(550, "no such mailbox"));
}
Ok(())
}
/// Called once per RCPT TO, with only `envelope` set (exactly one recipient).
/// Never require `message` or `message_id` here.
#[query]
fn smtp_request_validate(req: SmtpRequest) -> SmtpResponse {
if let Err(rejected) = check_caller() {
return rejected;
}
let Some(env) = req.envelope else {
return err(501, "envelope is required");
};
match check_envelope(&env) {
Ok(()) => SmtpResponse::Ok(SmtpOk {}),
Err(rejected) => rejected,
}
}
/// Delivery. Synchronous on purpose: no `.await`, so no interleaving and no
/// risk of running into the gateway's delivery timeout.
#[update]
fn smtp_request(req: SmtpRequest) -> SmtpResponse {
if let Err(rejected) = check_caller() {
return rejected;
}
// Every SmtpRequest field is `opt`, so ANY record decodes into this type.
// Check presence yourself and never unwrap: a trap reads as a temporary
// failure, and the sending server retries it until it gives up.
let (Some(env), Some(msg), Some(id)) = (req.envelope, req.message, req.message_id) else {
return err(501, "envelope, message and message_id are required");
};
if let Err(rejected) = check_envelope(&env) {
return rejected;
}
if msg.headers.len() > MAX_HEADERS {
return err(552, "too many headers");
}
if msg.body.len() > MAX_BODY_BYTES {
return err(552, "message too large");
}
INBOX.with_borrow_mut(|inbox| {
if inbox.len() >= MAX_STORED {
return err(452, "mailbox full"); // transient: the sender retries later
}
// `message_id` is unique per SMTP transaction, NOT per email: a retry
// by the sending server arrives with a new one. Storing under it
// avoids overwrites; it does not deduplicate.
inbox.entry(id).or_insert_with(|| Mail {
envelope_from: format!("{}@{}", env.from.user, env.from.domain),
subject: header(&msg.headers, "Subject")
.unwrap_or_default()
.to_string(),
headers: msg.headers,
body: msg.body,
received_at: time(),
});
SmtpResponse::Ok(SmtpOk {})
})
}
#[query]
fn inbox_size() -> u64 {
INBOX.with_borrow(|inbox| inbox.len() as u64)
}
ic_cdk::export_candid!();ic-smtp-gateway-protocolwasm32-unknown-unknowntoml
[package]
name = "backend"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
candid = "0.10"
ic-cdk = "0.20"
ic-smtp-gateway-protocol = "0.1"使用 recipe 将其部署为名为 的 canister( skill)。
@dfinity/rust@v3.3.0backendicp-clirust
use std::{cell::RefCell, collections::BTreeMap};
use ic_cdk::{
api::{is_controller, msg_caller, time},
query, update,
};
use ic_smtp_gateway_protocol::{
Envelope, Header, SmtpOk, SmtpRequest, SmtpRequestError, SmtpResponse,
};
/// Principal of DFINITY's SMTP gateways; gateways run by others have their own.
const SMTP_GATEWAY: &str = "ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae";
/// Local parts this canister accepts mail for.
const MAILBOXES: &[&str] = &["support", "hello"];
// Bounds on what one request may cost this canister.
const MAX_RECIPIENTS: usize = 10;
const MAX_HEADERS: usize = 100;
const MAX_BODY_BYTES: usize = 100_000;
const MAX_STORED: usize = 10_000;
#[allow(dead_code)] // read by your application logic
struct Mail {
envelope_from: String, // unauthenticated: see pitfalls
subject: String,
headers: Vec<Header>,
body: Vec<u8>, // raw RFC 5322 body bytes, MIME not decoded
received_at: u64,
}
thread_local! {
// Heap only for brevity: use stable structures in production.
static INBOX: RefCell<BTreeMap<String, Mail>> = RefCell::default();
}
/// Keep `message` short, single-line ASCII: the gateway copies it into the
/// SMTP reply line.
fn err(code: u64, message: &str) -> SmtpResponse {
SmtpResponse::Err(SmtpRequestError {
code,
message: message.to_string(),
})
}
/// Optional: accept mail only through DFINITY's gateways (plus
/// controllers, for testing). Drop this check to accept any gateway. Return
/// 530 rather than trapping, which would read as a temporary failure.
fn check_caller() -> Result<(), SmtpResponse> {
let caller = msg_caller();
if caller.to_text() == SMTP_GATEWAY || is_controller(&caller) {
Ok(())
} else {
Err(err(530, "unauthorized caller"))
}
}
/// Header names are case-insensitive. Values arrive as the raw text after the
/// colon: leading space and line ending included, RFC 2047 not decoded.
fn header<'a>(headers: &'a [Header], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case(name))
.map(|h| h.value.trim())
}
fn is_mailbox(user: &str) -> bool {
MAILBOXES.iter().any(|m| m.eq_ignore_ascii_case(user))
}
/// Shared by both entry points: smtp_request must re-check everything
/// smtp_request_validate checked, because the state may have changed since.
fn check_envelope(env: &Envelope) -> Result<(), SmtpResponse> {
if env.to.is_empty() {
return Err(err(501, "no recipients"));
}
if env.to.len() > MAX_RECIPIENTS {
return Err(err(552, "too many recipients"));
}
if env.to.iter().any(|rcpt| !is_mailbox(&rcpt.user)) {
return Err(err(550, "no such mailbox"));
}
Ok(())
}
/// Called once per RCPT TO, with only `envelope` set (exactly one recipient).
/// Never require `message` or `message_id` here.
#[query]
fn smtp_request_validate(req: SmtpRequest) -> SmtpResponse {
if let Err(rejected) = check_caller() {
return rejected;
}
let Some(env) = req.envelope else {
return err(501, "envelope is required");
};
match check_envelope(&env) {
Ok(()) => SmtpResponse::Ok(SmtpOk {}),
Err(rejected) => rejected,
}
}
/// Delivery. Synchronous on purpose: no `.await`, so no interleaving and no
/// risk of running into the gateway's delivery timeout.
#[update]
fn smtp_request(req: SmtpRequest) -> SmtpResponse {
if let Err(rejected) = check_caller() {
return rejected;
}
// Every SmtpRequest field is `opt`, so ANY record decodes into this type.
// Check presence yourself and never unwrap: a trap reads as a temporary
// failure, and the sending server retries it until it gives up.
let (Some(env), Some(msg), Some(id)) = (req.envelope, req.message, req.message_id) else {
return err(501, "envelope, message and message_id are required");
};
if let Err(rejected) = check_envelope(&env) {
return rejected;
}
if msg.headers.len() > MAX_HEADERS {
return err(552, "too many headers");
}
if msg.body.len() > MAX_BODY_BYTES {
return err(552, "message too large");
}
INBOX.with_borrow_mut(|inbox| {
if inbox.len() >= MAX_STORED {
return err(452, "mailbox full"); // transient: the sender retries later
}
// `message_id` is unique per SMTP transaction, NOT per email: a retry
// by the sending server arrives with a new one. Storing under it
// avoids overwrites; it does not deduplicate.
inbox.entry(id).or_insert_with(|| Mail {
envelope_from: format!("{}@{}", env.from.user, env.from.domain),
subject: header(&msg.headers, "Subject")
.unwrap_or_default()
.to_string(),
headers: msg.headers,
body: msg.body,
received_at: time(),
});
SmtpResponse::Ok(SmtpOk {})
})
}
#[query]
fn inbox_size() -> u64 {
INBOX.with_borrow(|inbox| inbox.len() as u64)
}
ic_cdk::export_candid!();Motoko
Motoko
There is no Motoko package for the protocol: declare the types yourself, field for field, as below. needs under .
mops.tomlcore = "2.5.0"[dependencies]motoko
import Char "mo:core/Char";
import Map "mo:core/Map";
import Principal "mo:core/Principal";
import Text "mo:core/Text";
import Time "mo:core/Time";
persistent actor Inbox {
// --- Protocol types: a field-for-field projection of candid/smtp_gateway.did ---
// Names and labels are the wire format: keep `#Ok`/`#Err` capitalised,
// `code : Nat64`, and `#Ok` carrying the empty record `{}`.
public type Header = { name : Text; value : Text };
public type Message = { headers : [Header]; body : Blob };
public type Address = { user : Text; domain : Text };
public type Envelope = { from : Address; to : [Address] };
public type SmtpRequest = {
message : ?Message;
envelope : ?Envelope;
gateway_flags : ?[Text];
message_id : ?Text;
};
public type SmtpRequestError = { code : Nat64; message : Text };
public type SmtpResponse = { #Ok : {}; #Err : SmtpRequestError };
// --- Application state ---
type Mail = {
envelopeFrom : Address; // unauthenticated: see pitfalls
subject : Text;
headers : [Header];
body : Blob; // raw RFC 5322 body bytes, MIME not decoded
receivedAt : Int;
};
// Configuration is `transient`: a plain `let` in a persistent actor is
// stable and would keep its first-install value across upgrades.
// Principal of DFINITY's SMTP gateways; gateways run by others have their own.
transient let smtpGateway = Principal.fromText("ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae");
// Local parts this canister accepts mail for.
transient let mailboxes : [Text] = ["support", "hello"];
// Bounds on what one request may cost this canister.
transient let maxRecipients = 10;
transient let maxHeaders = 100;
transient let maxBodyBytes = 100_000;
transient let maxStored = 10_000;
let inbox = Map.empty<Text, Mail>(); // stable: survives upgrades
// Keep `message` short, single-line ASCII: the gateway copies it into the
// SMTP reply line.
func err(code : Nat64, message : Text) : SmtpResponse {
#Err({ code; message });
};
// Optional: accept mail only through DFINITY's gateways (plus
// controllers, for testing). Drop this check to accept any gateway. Return
// 530 rather than trapping, which would read as a temporary failure.
func checkCaller(caller : Principal) : ?SmtpResponse {
if (caller == smtpGateway or Principal.isController(caller)) null else ?err(530, "unauthorized caller");
};
// Header names are case-insensitive. Values arrive as the raw text after the
// colon: leading space and line ending included, RFC 2047 not decoded.
func header(headers : [Header], name : Text) : ?Text {
let wanted = name.toLower();
for (h in headers.vals()) {
if (h.name.toLower() == wanted) return ?h.value.trim(#predicate(Char.isWhitespace));
};
null;
};
func isMailbox(user : Text) : Bool {
let u = user.toLower();
for (m in mailboxes.vals()) { if (m == u) return true };
false;
};
// Shared by both entry points: smtp_request must re-check everything
// smtp_request_validate checked, because the state may have changed since.
func checkEnvelope(env : Envelope) : ?SmtpResponse {
if (env.to.size() == 0) return ?err(501, "no recipients");
if (env.to.size() > maxRecipients) return ?err(552, "too many recipients");
for (rcpt in env.to.vals()) {
if (not isMailbox(rcpt.user)) return ?err(550, "no such mailbox");
};
null;
};
// Called once per RCPT TO, with only `envelope` set (exactly one recipient).
// Never require `message` or `message_id` here.
public shared query ({ caller }) func smtp_request_validate(req : SmtpRequest) : async SmtpResponse {
switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} };
let ?env = req.envelope else return err(501, "envelope is required");
switch (checkEnvelope(env)) {
case (?rejected) rejected;
case null #Ok({});
};
};
// Delivery. No `await` in here: no interleaving, and no risk of running
// into the gateway's delivery timeout.
public shared ({ caller }) func smtp_request(req : SmtpRequest) : async SmtpResponse {
switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} };
// Every SmtpRequest field is `opt`, so ANY record decodes into this type.
// Check presence yourself and never trap: a trap reads as a temporary
// failure, and the sending server retries it until it gives up.
let (?env, ?msg, ?id) = (req.envelope, req.message, req.message_id) else {
return err(501, "envelope, message and message_id are required");
};
switch (checkEnvelope(env)) {
case (?rejected) return rejected;
case null {};
};
if (msg.headers.size() > maxHeaders) return err(552, "too many headers");
if (msg.body.size() > maxBodyBytes) return err(552, "message too large");
if (Map.size(inbox) >= maxStored) return err(452, "mailbox full"); // transient
// `message_id` is unique per SMTP transaction, NOT per email: a retry by
// the sending server arrives with a new one. Storing under it avoids
// overwrites; it does not deduplicate.
if (not Map.containsKey(inbox, Text.compare, id)) {
Map.add(
inbox,
Text.compare,
id,
{
envelopeFrom = env.from;
subject = switch (header(msg.headers, "Subject")) {
case (?s) s;
case null "";
};
headers = msg.headers;
body = msg.body;
receivedAt = Time.now();
},
);
};
#Ok({});
};
public query func inboxSize() : async Nat { Map.size(inbox) };
};该协议没有 Motoko package:应像下面这样逐字段自行声明类型。 的 中需要设置 。
mops.toml[dependencies]core = "2.5.0"motoko
import Char "mo:core/Char";
import Map "mo:core/Map";
import Principal "mo:core/Principal";
import Text "mo:core/Text";
import Time "mo:core/Time";
persistent actor Inbox {
// --- Protocol types: a field-for-field projection of candid/smtp_gateway.did ---
// Names and labels are the wire format: keep `#Ok`/`#Err` capitalised,
// `code : Nat64`, and `#Ok` carrying the empty record `{}`.
public type Header = { name : Text; value : Text };
public type Message = { headers : [Header]; body : Blob };
public type Address = { user : Text; domain : Text };
public type Envelope = { from : Address; to : [Address] };
public type SmtpRequest = {
message : ?Message;
envelope : ?Envelope;
gateway_flags : ?[Text];
message_id : ?Text;
};
public type SmtpRequestError = { code : Nat64; message : Text };
public type SmtpResponse = { #Ok : {}; #Err : SmtpRequestError };
// --- Application state ---
type Mail = {
envelopeFrom : Address; // unauthenticated: see pitfalls
subject : Text;
headers : [Header];
body : Blob; // raw RFC 5322 body bytes, MIME not decoded
receivedAt : Int;
};
// Configuration is `transient`: a plain `let` in a persistent actor is
// stable and would keep its first-install value across upgrades.
// Principal of DFINITY's SMTP gateways; gateways run by others have their own.
transient let smtpGateway = Principal.fromText("ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae");
// Local parts this canister accepts mail for.
transient let mailboxes : [Text] = ["support", "hello"];
// Bounds on what one request may cost this canister.
transient let maxRecipients = 10;
transient let maxHeaders = 100;
transient let maxBodyBytes = 100_000;
transient let maxStored = 10_000;
let inbox = Map.empty<Text, Mail>(); // stable: survives upgrades
// Keep `message` short, single-line ASCII: the gateway copies it into the
// SMTP reply line.
func err(code : Nat64, message : Text) : SmtpResponse {
#Err({ code; message });
};
// Optional: accept mail only through DFINITY's gateways (plus
// controllers, for testing). Drop this check to accept any gateway. Return
// 530 rather than trapping, which would read as a temporary failure.
func checkCaller(caller : Principal) : ?SmtpResponse {
if (caller == smtpGateway or Principal.isController(caller)) null else ?err(530, "unauthorized caller");
};
// Header names are case-insensitive. Values arrive as the raw text after the
// colon: leading space and line ending included, RFC 2047 not decoded.
func header(headers : [Header], name : Text) : ?Text {
let wanted = name.toLower();
for (h in headers.vals()) {
if (h.name.toLower() == wanted) return ?h.value.trim(#predicate(Char.isWhitespace));
};
null;
};
func isMailbox(user : Text) : Bool {
let u = user.toLower();
for (m in mailboxes.vals()) { if (m == u) return true };
false;
};
// Shared by both entry points: smtp_request must re-check everything
// smtp_request_validate checked, because the state may have changed since.
func checkEnvelope(env : Envelope) : ?SmtpResponse {
if (env.to.size() == 0) return ?err(501, "no recipients");
if (env.to.size() > maxRecipients) return ?err(552, "too many recipients");
for (rcpt in env.to.vals()) {
if (not isMailbox(rcpt.user)) return ?err(550, "no such mailbox");
};
null;
};
// Called once per RCPT TO, with only `envelope` set (exactly one recipient).
// Never require `message` or `message_id` here.
public shared query ({ caller }) func smtp_request_validate(req : SmtpRequest) : async SmtpResponse {
switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} };
let ?env = req.envelope else return err(501, "envelope is required");
switch (checkEnvelope(env)) {
case (?rejected) rejected;
case null #Ok({});
};
};
// Delivery. No `await` in here: no interleaving, and no risk of running
// into the gateway's delivery timeout.
public shared ({ caller }) func smtp_request(req : SmtpRequest) : async SmtpResponse {
switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} };
// Every SmtpRequest field is `opt`, so ANY record decodes into this type.
// Check presence yourself and never trap: a trap reads as a temporary
// failure, and the sending server retries it until it gives up.
let (?env, ?msg, ?id) = (req.envelope, req.message, req.message_id) else {
return err(501, "envelope, message and message_id are required");
};
switch (checkEnvelope(env)) {
case (?rejected) rejected;
case null {};
};
if (msg.headers.size() > maxHeaders) return err(552, "too many headers");
if (msg.body.size() > maxBodyBytes) return err(552, "message too large");
if (Map.size(inbox) >= maxStored) return err(452, "mailbox full"); // transient
// `message_id` is unique per SMTP transaction, NOT per email: a retry by
// the sending server arrives with a new one. Storing under it avoids
// overwrites; it does not deduplicate.
if (not Map.containsKey(inbox, Text.compare, id)) {
Map.add(
inbox,
Text.compare,
id,
{
envelopeFrom = env.from;
subject = switch (header(msg.headers, "Subject")) {
case (?s) s;
case null "";
};
headers = msg.headers;
body = msg.body;
receivedAt = Time.now();
},
);
};
#Ok({});
};
public query func inboxSize() : async Nat { Map.size(inbox) };
};Chunked Upload (Optional)
分块上传(可选)
A message whose encoded exceeds 2 MiB cannot be delivered with one ingress call. The gateway then uploads it with and finalizes it with , but only when returns both and . Otherwise the sender gets a permanent error, and your canister is unaffected. DFINITY's gateways accept at most 1,996,800 bytes per message (header block and body) and rejects larger mail with , so nearly everything it accepts fits one : implement chunked upload only if you need it. The obligations are strict: verify each chunk's SHA-256 before storing it, bound the layout before allocating, derive the commit digest from the bytes you stored (SHA-256 over the concatenated per-chunk SHA-256 digests in index order, not over the body: the crate's ; a mismatch is 554), and keep the commit verdict so a repeated commit or a status query returns it. Read for the checklist, the gateway's behavior, and where to find the reference implementation.
SmtpRequestsmtp_upload_chunksmtp_upload_commitsmtp_capabilitiesupload_protocol_version >= 1max_message_size > 0550 5.5.0 ... does not support chunked upload552 5.3.4smtp_requestbody_sha256()references/chunked-upload.md如果编码后的 超过 2 MiB,就无法通过单次 ingress call 投递。此时 gateway 会使用 上传消息,并通过 完成最终处理,但仅当 同时返回 和 时才会执行。否则,发件人会收到永久错误 ,你的 canister 不会受到影响。DFINITY 的 gateway 每封消息最多接受 1,996,800 bytes(header block 和 body),更大的邮件会以 拒绝,因此它接受的大多数邮件都能通过单次 投递:仅在确有需要时才实现分块上传。相关要求非常严格:存储每个 chunk 前必须验证其 SHA-256;分配内存前必须限制 layout;commit digest 必须根据已存储的字节计算(按索引顺序拼接各 chunk 的 SHA-256 digests 后再计算 SHA-256,而不是对 body 计算:即 crate 中的 ;不匹配时返回 554);还必须保存 commit verdict,使重复 commit 或 status query 返回相同结果。有关检查清单、gateway 行为以及参考实现位置,请阅读 。
SmtpRequestsmtp_upload_chunksmtp_upload_commitsmtp_capabilitiesupload_protocol_version >= 1max_message_size > 0550 5.5.0 ... does not support chunked upload552 5.3.4smtp_requestbody_sha256()references/chunked-upload.mdDeploy & Test
部署与测试
There is no local SMTP gateway. Test by making the gateway's two calls yourself. Your identity deployed the canister, so it is a controller and passes the caller check:
bash
icp network start -d
icp deploy backend本地没有 SMTP gateway。应通过自行发起 gateway 的两次调用来测试。由于你的 identity 部署了该 canister,因此它是 controller,可以通过调用方检查:
bash
icp network start -d
icp deploy backend1. RCPT TO for a known mailbox. Expected: (variant { Ok = record {} })
1. RCPT TO for a known mailbox. Expected: (variant { Ok = record {} })
icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } } })'
icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } } })'
2. RCPT TO for an unknown mailbox. Expected: Err with code = 550 : nat64
2. RCPT TO for an unknown mailbox. Expected: Err with code = 550 : nat64
icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "nobody"; domain = "example.icp0.io" } } } })'
icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "nobody"; domain = "example.icp0.io" } } } })'
3. Delivery, with header values as raw as the gateway sends them.
3. Delivery, with header values as raw as the gateway sends them.
Expected: (variant { Ok = record {} })
Expected: (variant { Ok = record {} })
icp canister call backend smtp_request '(record {
envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } };
message = opt record {
headers = vec { record { name = "From"; value = " Alice alice@example.com\r\n" }; record { name = "Subject"; value = " Hello\r\n" } };
body = blob "Hi there!\r\n";
};
message_id = opt "0193f0a1-2b3c-7d4e-8f90-a1b2c3d4e5f6";
})'
icp canister call backend smtp_request '(record {
envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } };
message = opt record {
headers = vec { record { name = "From"; value = " Alice alice@example.com\r\n" }; record { name = "Subject"; value = " Hello\r\n" } };
body = blob "Hi there!\r\n";
};
message_id = opt "0193f0a1-2b3c-7d4e-8f90-a1b2c3d4e5f6";
})'
4. Delivery without message_id. Expected: Err with code = 501 : nat64, not a trap
4. Delivery without message_id. Expected: Err with code = 501 : nat64, not a trap
icp canister call backend smtp_request '(record { envelope = opt record { from = record { user = "a"; domain = "b.c" }; to = vec { record { user = "support"; domain = "x" } } }; message = opt record { headers = vec {}; body = blob "" } })'
icp canister call backend smtp_request '(record { envelope = opt record { from = record { user = "a"; domain = "b.c" }; to = vec { record { user = "support"; domain = "x" } } }; message = opt record { headers = vec {}; body = blob "" } })'
5. Expected: (1 : nat64). The Motoko example names this inboxSize and returns nat.
5. Expected: (1 : nat64). The Motoko example names this inboxSize and returns nat.
icp canister call backend inbox_size '()'
icp canister call backend inbox_size '()'
6. A caller that is neither the gateway nor a controller. Expected: Err with code = 530 : nat64
6. A caller that is neither the gateway nor a controller. Expected: Err with code = 530 : nat64
icp canister call --identity anonymous backend smtp_request_validate '(record {})'
undefinedicp canister call --identity anonymous backend smtp_request_validate '(record {})'
undefinedVerify It Works on Mainnet
在 Mainnet 上验证
bash
icp deploy -e ic backend
CANISTER_ID=$(icp canister status backend -e ic --id-only)bash
icp deploy -e ic backend
CANISTER_ID=$(icp canister status backend -e ic --id-only)1. Mail for the canister routes to the gateway. Expected: one or more MX hosts.
1. Mail for the canister routes to the gateway. Expected: one or more MX hosts.
dig +short MX "$CANISTER_ID.icp0.io"
dig +short MX "$CANISTER_ID.icp0.io"
2. Send a mail to support@<CANISTER_ID>.icp0.io from any mail account, then:
2. Send a mail to support@<CANISTER_ID>.icp0.io from any mail account, then:
icp canister call -e ic backend inbox_size '()'
| Symptom at the sender | Cause |
|---|---|
| `550 5.1.3 Permanent error: Canister <id> does not support SMTP protocol` | `smtp_request_validate` is not exported, misnamed, or not a query, or the `.well-known/ic-smtp-canister-id` handoff names a canister without it |
| `550 5.1.2 Mailbox does not exist.` | `smtp_request_validate` returned 550. Check the local-part match, including case. |
| `550 5.1.3 Permanent error: unauthorized caller` | The caller check does not accept the gateway principal (Pitfall 7) |
| `550 5.1.1 Unknown recipient domain.` | The custom domain is not registered, or the address is not `<canister-id>.icp0.io` |
| Delivery delayed, then a bounce after days | The canister traps, or returns a code outside 500–599, or takes longer than 90 s. Call it directly to see which. |
| `552 5.3.4 Message too big` | The message exceeds the gateway's size limit (see Chunked Upload) |icp canister call -e ic backend inbox_size '()'
| 发件方看到的现象 | 原因 |
|---|---|
| `550 5.1.3 Permanent error: Canister <id> does not support SMTP protocol` | `smtp_request_validate` 未导出、名称错误,或者不是 query,或者 `.well-known/ic-smtp-canister-id` 指向了一个不具备该方法的 canister |
| `550 5.1.2 Mailbox does not exist.` | `smtp_request_validate` 返回了 550。检查本地部分的匹配情况,包括大小写。 |
| `550 5.1.3 Permanent error: unauthorized caller` | 调用方检查未接受 gateway principal(问题 7) |
| `550 5.1.1 Unknown recipient domain.` | 自定义域名未注册,或者地址不是 `<canister-id>.icp0.io` |
| 投递延迟,并在数日后收到退信 | canister 发生 trap、返回 500–599 之外的代码,或耗时超过 90 秒。可直接调用它以查明原因。 |
| `552 5.3.4 Message too big` | 消息超过 gateway 的大小限制(参见“分块上传”) |