smtp-gateway

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SMTP 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
smtp_request
method, the way the HTTP gateway calls
http_request
. DFINITY operates the gateways that mail for
<canister-id>.icp0.io
reaches, alongside its HTTP gateways; others can run their own, since the gateway is part of
ic-gateway
. 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
<canister-id>.icp0.io
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 (
MAIL FROM:<>
).
The protocol is specified in
candid/smtp_gateway.did
in
dfinity/ic-smtp-gateway-protocol
, and the gateway that implements it is the
smtp
module of
dfinity/ic-bn-lib
.
SMTP gateway 是一个链下邮件服务器,它接受发往某个 canister 的电子邮件,并通过调用该 canister 的
smtp_request
方法来投递邮件,就像 HTTP gateway 调用
http_request
一样。DFINITY 运营着这些 gateway,使发往
<canister-id>.icp0.io
的邮件能够送达;它也运营 HTTP gateway,其他人也可以运行自己的 gateway,因为该 gateway 属于
ic-gateway
的一部分。本 skill 中讨论的限制和发件人检查均适用于 DFINITY 的 gateway。canister 只需实现两个方法即可选择启用。无需为
<canister-id>.icp0.io
地址进行任何注册。邮件只向内流动:canister 无法通过 gateway 发送邮件,也永远不会收到退信,因为 gateway 会拒空发件人(
MAIL FROM:<>
)。
该协议在
dfinity/ic-smtp-gateway-protocol
的
candid/smtp_gateway.did
中定义,实现该协议的 gateway 是
dfinity/ic-bn-lib
的
smtp
模块。

Addressing

地址

AddressSetup
anything@<canister-id>.icp0.io
None. Every
<canister-id>.icp0.io
already has MX records pointing at the gateway.
anything@<custom-domain>
The domain must be registered as an IC custom domain (
custom-domains
skill): the gateway resolves it in the same registry as the HTTP gateway. Its MX records must also point at the gateway. A subdomain set up the standard way (
CNAME
to
<domain>.icp1.io
) inherits the gateway's MX records through the CNAME. An apex domain cannot be a CNAME, and ALIAS or CNAME flattening only produces A/AAAA records, so publish the hosts that
dig +short MX boundary.dfinity.network
lists as your MX records, and keep them in sync. Do not publish
MX boundary.dfinity.network
itself: mail servers would connect to that name's own addresses, which do not accept mail.
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 (
    user
    ) arrives verbatim: case,
    +tag
    suffixes and quotes are kept. Match it case-insensitively unless you have a reason not to. The gateway rejects non-ASCII local parts itself.
  • Handing mail to another canister. Before calling the addressed canister, the gateway fetches
    https://<canister-id>.icp0.io/.well-known/ic-smtp-canister-id
    . 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
    static-site
    recipe, add a file
    .well-known/ic-smtp-canister-id
    containing only the backend's canister ID to the uploaded directory (
    .well-known/
    is uploaded without extra configuration).
地址设置
anything@<canister-id>.icp0.io
无需设置。每个
<canister-id>.icp0.io
都已经拥有指向 gateway 的 MX records。
anything@<custom-domain>
域名必须注册为 IC 自定义域名(
custom-domains
skill):gateway 会在与 HTTP gateway 相同的注册表中解析它。其 MX records 也必须指向 gateway。以标准方式配置的子域名(
CNAME
到
<domain>.icp1.io
)通过 CNAME 继承 gateway 的 MX records。顶级域名不能是 CNAME,而 ALIAS 或 CNAME flattening 只生成 A/AAAA records,因此应将
dig +short MX boundary.dfinity.network
列出的主机发布为 MX records,并保持同步。不要发布
MX boundary.dfinity.network
本身:邮件服务器会连接到该名称自身的地址,而这些地址不接受邮件。
gateway 路由收件人的方式如下:
  • 如果收件人域名的第一个 DNS label 可解析为 principal,那么该 principal 就是目标 canister。否则,会在已注册的自定义域名中查找完全匹配的域名。没有匹配项时返回:
    550 5.1.1 Unknown recipient domain.
  • 域名到达时会被转为小写。本地部分(
    user
    )会原样到达:大小写、
    +tag
    后缀和引号都会保留。除非有特殊原因,否则应不区分大小写地进行匹配。gateway 本身会拒绝非 ASCII 本地部分。
  • 将邮件移交给另一个 canister。 在调用目标 canister 之前,gateway 会获取
    https://<canister-id>.icp0.io/.well-known/ic-smtp-canister-id
    。如果响应状态为 2xx,且去除首尾空白后的正文是一个 principal,那么所有 SMTP 调用都会转交给该 principal。任何失败都会回退到最初的目标 canister。无论最终使用哪个结果,都会缓存 10 分钟。当 frontend canister 拥有域名而 backend canister 负责处理邮件时,可以使用此方式:对于
    static-site
    recipe,只需在上传目录中添加
    .well-known/ic-smtp-canister-id
    文件,其中仅包含 backend 的 canister ID(无需额外配置即可上传
    .well-known/
    )。

The Protocol

协议

MethodRequiredWhen the gateway calls it
smtp_request_validate : (SmtpRequest) -> (SmtpResponse) query
Yes (see Pitfall 4)Once per
RCPT TO
, before the message is transferred
smtp_request : (SmtpRequest) -> (SmtpResponse)
YesAfter
DATA
, once per destination canister, listing all recipients that resolved to it
smtp_capabilities
,
smtp_upload_chunk
,
smtp_upload_commit
,
smtp_upload_status
,
smtp_upload_abort
NoChunked upload for messages over the ~2 MiB ingress limit. Read
references/chunked-upload.md
before implementing these.
What each call carries:
Field
smtp_request_validate
smtp_request
envelope
MAIL FROM
address and exactly one recipient
MAIL FROM
address and every recipient for this canister (at most 10 per session)
message
null
Headers and raw body
message_id
null
A new UUIDv7 for every SMTP transaction
The wire types are defined in
candid/smtp_gateway.did
. The Rust crate exports them, and the Motoko example below declares them field for field.
code
is
nat64
(a
nat32
does not decode), the variant labels are exactly
Ok
and
Err
, and
Ok
carries an empty record, not
null
.
方法是否必需gateway 何时调用
smtp_request_validate : (SmtpRequest) -> (SmtpResponse) query
是(见问题 4)每个
RCPT TO
调用一次,在传输邮件之前
smtp_request : (SmtpRequest) -> (SmtpResponse)
是在
DATA
之后,每个目标 canister 调用一次,并列出所有解析到它的收件人
smtp_capabilities
、
smtp_upload_chunk
、
smtp_upload_commit
、
smtp_upload_status
、
smtp_upload_abort
否用于上传超过约 2 MiB ingress 限制的消息。实现这些方法前请阅读
references/chunked-upload.md
。
每次调用所携带的内容:
字段
smtp_request_validate
smtp_request
envelope
MAIL FROM
地址和恰好一个收件人
MAIL FROM
地址,以及该 canister 的所有收件人(每个会话最多 10 个)
message
null
Headers 和原始 body
message_id
null
每个 SMTP transaction 都会生成一个新的 UUIDv7
线路类型在
candid/smtp_gateway.did
中定义。Rust crate 会导出这些类型,下面的 Motoko 示例也逐字段声明了它们。
code
是
nat64
(使用
nat32
将无法解码),variant labels 必须恰好为
Ok
和
Err
,并且
Ok
携带一个空 record,而不是
null
。

Reply Codes Are the Interface

回复码就是协议接口

The gateway acts on the class of
SmtpRequestError.code
: 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.
During
RCPT TO
, from
smtp_request_validate
:
Canister resultThe sending server sees
Ok
250 2.1.5 OK
Err
with code 550
550 5.1.2 Mailbox does not exist.
for that recipient only (your
message
is dropped)
Err
with another 500–599 code
550 5.1.3 Permanent error: <message>
Err
with any other code
451 4.4.3 Temporary error: <message>
Method not exported
550 5.1.3 Permanent error: Canister <id> does not support SMTP protocol
Trap or call failure
451 4.4.3 Temporary error: ...
After
DATA
, from
smtp_request
:
Canister resultThe sending server seesThen
Ok
250
Delivered
Err
with a 500–599 code
550 5.5.0 Permanent delivery error: <message>
The sender gets a bounce
Err
with any other code
450 4.5.0 Temporary delivery error: <message>
The sending server retries later
Trap, call failure, or no reply within 90 s
450 ...
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 根据
SmtpRequestError.code
的类别采取行动:500–599 表示永久错误,其他任何代码都表示临时错误。Trap 和调用失败也属于临时错误,但有两个例外:方法未导出,或请求对于单条 ingress 消息而言过大,这两种情况属于永久错误。
在
RCPT TO
阶段,来自
smtp_request_validate
的结果如下:
Canister 结果发送服务器看到的内容
Ok
250 2.1.5 OK
Err
且代码为 550
仅针对该收件人返回
550 5.1.2 Mailbox does not exist.
(你的
message
会被丢弃)
Err
且代码为其他 500–599
550 5.1.3 Permanent error: <message>
Err
且代码为其他任何值
451 4.4.3 Temporary error: <message>
方法未导出
550 5.1.3 Permanent error: Canister <id> does not support SMTP protocol
Trap 或调用失败
451 4.4.3 Temporary error: ...
在
DATA
之后,来自
smtp_request
的结果如下:
Canister 结果发送服务器看到的内容后续处理
Ok
250
已投递
Err
且代码为 500–599
550 5.5.0 Permanent delivery error: <message>
发件人会收到退信
Err
且代码为其他任何值
450 4.5.0 Temporary delivery error: <message>
发送服务器稍后会重试
Trap、调用失败或 90 秒内未回复
450 ...
重试
应使用的代码。永久错误:550 表示邮箱不存在(已保留,不能用于其他任何情况),501 表示缺少必填字段,552 表示消息、headers 或收件人列表过大,554 表示内容被拒绝,530 表示调用方未获授权。临时错误:450 表示稍后重试,452 表示存储空间不足。

Mistakes That Break Mail Delivery

会破坏邮件投递的问题

  1. Trapping instead of returning
    Err
    .
    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 in
    unwrap()
    ,
    expect()
    , out-of-range slicing,
    String::truncate
    inside a multi-byte character, a nested
    RefCell
    borrow, and in Motoko in
    Nat
    underflow and array indexing.
  2. 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.
  3. Using 550 for anything except "unknown mailbox". From
    smtp_request_validate
    , 550 becomes
    550 5.1.2 Mailbox does not exist.
    and your text is dropped. Use another 5xx code (552, 554) for policy rejections so that your message reaches the sender.
  4. Skipping
    smtp_request_validate
    .
    The gateway calls it on every
    RCPT TO
    and treats a missing method as a permanent "does not support SMTP protocol" rejection of every recipient. Implement both methods. (
    smtp_capabilities
    is genuinely optional: a missing method just means no chunked upload.)
  5. Requiring
    message
    or
    message_id
    in
    smtp_request_validate
    .
    It receives only
    envelope
    , with exactly one recipient. Requiring the other fields rejects every recipient.
  6. Trusting Candid to validate the request. Every
    SmtpRequest
    field is
    opt
    , so any record argument decodes into it, with all fields
    null
    . Check each field you need and return 501 when it is missing.
  7. 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
    ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae
    (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.
  8. 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
    From
    (no DMARC), and no result reaches the canister (
    gateway_flags
    is always
    null
    ). So
    From
    , and
    envelope.from
    for 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, so
    simple
    cannot be verified); the public key fetched with DNS-over-HTTPS outcalls (
    https-outcalls
    skill) and accepted only when several resolvers agree; the signing domain
    d=
    aligned with
    From
    ; duplicate
    From
    ,
    Subject
    or
    DKIM-Signature
    headers rejected, since a duplicate header can smuggle content past the signature.
  9. Expecting clean, decoded header values. Each value is the raw text after the colon: the leading space, the trailing
    \r\n
    or
    \n
    , folded continuation lines and
    =?UTF-8?B?...?=
    encoded 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 (
    fRoM
    as
    From
    ). Order and duplicates are preserved; a header whose value is not valid UTF-8 is dropped.
  10. Expecting a parsed body.
    body
    holds the raw bytes after the header block, with CRLF line endings, and no MIME processing. Mail from a normal client is usually
    multipart/alternative
    with base64 or quoted-printable parts: you receive the boundaries and encoded parts, not plain text.
  11. Deduplicating on
    message_id
    .
    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 5322
    Message-ID
    header (chosen by the sender, so scope it per sender) or make processing idempotent.
  12. Awaiting inside
    smtp_request
    .
    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
    await
    is also an interleaving point (
    canister-security
    skill). 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.
  13. Long or multi-line error messages. The
    message
    is copied into the SMTP reply line: on
    RCPT TO
    it 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.
  14. Leaking secrets through error codes. Every
    Err
    tells the caller something, and a 5xx also sends a bounce to the claimed sender. If mail carries secrets such as verification codes, return
    Ok
    for unknown or invalid content and record the outcome internally. Internet Identity returns
    Err
    only for malformed requests, more than one recipient, and unknown mailboxes.
  15. Keeping mail on the heap, or configuration in stable variables. Heap state is lost on upgrade, so store mail in stable memory (
    stable-memory
    skill). In a Motoko
    persistent actor
    the opposite applies: a plain
    let
    is stable and keeps its first-install value, so a mailbox list or limit you change in code has no effect after an upgrade. Declare configuration
    transient let
    .
  1. 返回
    Err
    之前发生 Trap。
    Trap 会被报告为临时失败,因此发送服务器可能持续重试数天,最终才以含义不明确的错误放弃。每次拒绝都必须通过返回
    Err
    完成。Trap 可能隐藏在
    unwrap()
    、
    expect()
    、越界切片、在多字节字符内部调用
    String::truncate
    、嵌套
    RefCell
    借用等位置;在 Motoko 中还可能出现在
    Nat
    下溢和数组索引中。
  2. 使用非 5xx 代码报告永久问题。 只有 500–599 会触发退信。将确定性拒绝报告为 4xx,或报告为 400–599 范围之外的任何代码,都会导致重试,直到发件服务器放弃,而发件人始终无法得知原因。
  3. 将 550 用于“未知邮箱”以外的情况。 在
    smtp_request_validate
    中,550 会变成
    550 5.1.2 Mailbox does not exist.
    ,并且你的文本会被丢弃。对于策略性拒绝,应使用其他 5xx 代码(如 552、554),以便将原因传达给发件人。
  4. 跳过
    smtp_request_validate
    。
    gateway 会在每个
    RCPT TO
    阶段调用它,并将方法缺失视为永久的“does not support SMTP protocol”拒绝,从而拒绝所有收件人。必须实现这两个方法。(
    smtp_capabilities
    确实是可选的:方法缺失只意味着不支持分块上传。)
  5. 在
    smtp_request_validate
    中要求提供
    message
    或
    message_id
    。
    它只会收到
    envelope
    ,其中恰好包含一个收件人。要求提供其他字段会导致所有收件人都被拒绝。
  6. 信任 Candid 验证请求。 每个
    SmtpRequest
    字段都是
    opt
    ,因此任何 record 参数都可以解码为该类型,并且所有字段均为
    null
    。应检查所需的每个字段,缺少时返回 501。
  7. 忘记任何人都可以调用 SMTP 方法。 这些方法是公开的:任何 principal 都可以直接使用任意 envelope、headers 和 body 调用它们,绕过 gateway 执行的每项检查。若要限制由谁投递邮件,应检查调用方 principal。例如,如果只接受通过 DFINITY 运营的 gateway 投递的邮件,可以仅允许
    ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae
    (测试时还可允许 controllers),两个示例均采用此方式。对于其他 gateway,应向其运营方询问 principal,或者不限制调用方。应返回 530 进行拒绝,绝不能通过 trap 拒绝,否则 gateway 会重试。无论采用哪种方式,都必须限制每项输入的大小(Internet Identity 允许 100 个 headers、每个 header value 8 KiB、每个本地部分 64 字节),并限制已存储邮件的容量。
  8. 信任发件人的地址。 DFINITY 的 gateway 会拒绝 envelope sender 域名未通过 SPF 检查的邮件,以及所有 DKIM signatures 均验证失败的邮件。它们仍会接受没有 SPF record 的发件人和未签名的邮件,不会检查签名域名是否与
    From
    一致(没有 DMARC),并且任何检查结果都不会传递给 canister(
    gateway_flags
    始终为
    null
    )。因此,对于没有 SPF 的域名,
    From
    和
    envelope.from
    仍然只是客户端声称的内容。如果发件人身份很重要,应像 Internet Identity 一样在 canister 内验证 DKIM:使用 relaxed header canonicalization(header 名称到达时已标准化,因此无法验证
    simple
    );通过 DNS-over-HTTPS outcalls(
    https-outcalls
    skill)获取公钥,并且仅在多个 resolver 达成一致时才接受;签名域名
    d=
    必须与
    From
    对齐;拒绝重复的
    From
    、
    Subject
    或
    DKIM-Signature
    headers,因为重复 header 可能让内容绕过签名验证。
  9. 期望 header values 已被清理和解码。 每个 value 都是冒号后的原始文本:前导空格、末尾的
    \r\n
    或
    \n
    、折行 continuation lines,以及
    =?UTF-8?B?...?=
    encoded words 都会原样保留。比较前应先执行 trim,如果需要展示,应自行解码 encoded words,并且匹配 header 名称时应不区分大小写:gateway 识别的 header 名称会以 canonical case 到达(
    fRoM
    会变成
    From
    )。顺序和重复项都会保留;value 不是有效 UTF-8 的 header 会被丢弃。
  10. 期望 body 已被解析。
    body
    保存 header block 之后的原始字节,使用 CRLF 行尾,并且没有经过 MIME 处理。普通客户端发送的邮件通常是
    multipart/alternative
    ,并包含 base64 或 quoted-printable parts:收到的是 boundaries 和编码后的 parts,而不是纯文本。
  11. 根据
    message_id
    去重。
    它标识的是一次 SMTP transaction,而不是一封电子邮件:发送服务器重试时,重试消息会获得新的
    message_id
    。投递语义是 at-least-once。在存储邮件后丢失回复、触发 90 秒投递超时,或者另一个接收同一消息的 canister 发生失败(gateway 会使整封消息失败,并向每个收件人对应的发件人发起重试),都可能导致重复投递。如果重复消息值得关注,可以根据 RFC 5322
    Message-ID
    header 去重(该值由发件人选择,因此应按发件人限定范围),或者让处理逻辑具备幂等性。
  12. 在
    smtp_request
    中执行
    await
    。
    gateway 会保持 SMTP 会话开启并等待,90 秒后放弃等待。这会被报告为临时错误并触发重试,因此如果调用最终完成,邮件将到达两次。每个
    await
    同时也是一次 interleaving point(
    canister-security
    skill)。应同步接受请求,并将耗时工作推迟处理,例如交给 timer。Internet Identity 会先存储消息,完成 DKIM key lookups 后再回复。
  13. 错误消息过长或包含多行。
    message
    会被复制到 SMTP reply line:在
    RCPT TO
    阶段,它会在约 224 bytes 处被截断,且不会去除 CR 或 LF;超过约 220 bytes 的投递回复可能会被丢弃。应使用简短的单行 ASCII 文本,绝不要回显请求内容。
  14. 通过错误代码泄露秘密。 每个
    Err
    都会向调用方透露某些信息,而 5xx 还会向声称的发件人发送退信。如果邮件包含验证码等秘密,对于未知或无效内容应返回
    Ok
    ,并在内部记录结果。Internet Identity 仅在请求格式错误、收件人超过一个或邮箱未知时返回
    Err
    。
  15. 将邮件保留在 heap 中,或将配置保存在 stable variables 中。 Heap state 会在升级时丢失,因此应将邮件存储在 stable memory(
    stable-memory
    skill)中。在 Motoko
    persistent actor
    中则恰好相反:普通
    let
    是 stable 的,并会保留首次安装时的值,因此在代码中修改邮箱列表或限制后,升级不会应用这些变更。应将配置声明为
    transient let
    。

Implementation

实现

Both examples accept mail for
support@
and
hello@
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.
smtp_request_validate
and
smtp_request
share one envelope check because the query may be stale by the time the update runs.
两个示例都仅通过 DFINITY 运营的 gateway 接受发往
support@
和
hello@
的邮件(测试时也允许 controllers;此限制是可选的,见问题 7),存储每封邮件,并处理上述问题。
smtp_request_validate
和
smtp_request
共用一项 envelope 检查,因为 query 执行时得到的状态可能在 update 执行前已经过期。

Rust

Rust

The
ic-smtp-gateway-protocol
crate provides the protocol types. It builds for
wasm32-unknown-unknown
.
toml
[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
@dfinity/rust@v3.3.0
recipe as canister
backend
(
icp-cli
skill).
rust
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-protocol
crate 提供了协议类型。它可以针对
wasm32-unknown-unknown
构建。
toml
[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"
使用
@dfinity/rust@v3.3.0
recipe 将其部署为名为
backend
的 canister(
icp-cli
skill)。
rust
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.
mops.toml
needs
core = "2.5.0"
under
[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
SmtpRequest
exceeds 2 MiB cannot be delivered with one ingress call. The gateway then uploads it with
smtp_upload_chunk
and finalizes it with
smtp_upload_commit
, but only when
smtp_capabilities
returns both
upload_protocol_version >= 1
and
max_message_size > 0
. Otherwise the sender gets a permanent
550 5.5.0 ... does not support chunked upload
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
552 5.3.4
, so nearly everything it accepts fits one
smtp_request
: 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
body_sha256()
; a mismatch is 554), and keep the commit verdict so a repeated commit or a status query returns it. Read
references/chunked-upload.md
for the checklist, the gateway's behavior, and where to find the reference implementation.
如果编码后的
SmtpRequest
超过 2 MiB,就无法通过单次 ingress call 投递。此时 gateway 会使用
smtp_upload_chunk
上传消息,并通过
smtp_upload_commit
完成最终处理,但仅当
smtp_capabilities
同时返回
upload_protocol_version >= 1
和
max_message_size > 0
时才会执行。否则,发件人会收到永久错误
550 5.5.0 ... does not support chunked upload
,你的 canister 不会受到影响。DFINITY 的 gateway 每封消息最多接受 1,996,800 bytes(header block 和 body),更大的邮件会以
552 5.3.4
拒绝,因此它接受的大多数邮件都能通过单次
smtp_request
投递:仅在确有需要时才实现分块上传。相关要求非常严格:存储每个 chunk 前必须验证其 SHA-256;分配内存前必须限制 layout;commit digest 必须根据已存储的字节计算(按索引顺序拼接各 chunk 的 SHA-256 digests 后再计算 SHA-256,而不是对 body 计算:即 crate 中的
body_sha256()
;不匹配时返回 554);还必须保存 commit verdict,使重复 commit 或 status query 返回相同结果。有关检查清单、gateway 行为以及参考实现位置,请阅读
references/chunked-upload.md
。

Deploy & 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 backend

1. 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 {})'
undefined
icp canister call --identity anonymous backend smtp_request_validate '(record {})'
undefined

Verify 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 的大小限制(参见“分块上传”) |