跳到正文

开发中的邮件 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 一个给支持团队发邮件的联系表单——而且你可以在没有邮件服务器的情况下开发和测试它。

使用 host: log 时,q:mail 把每封邮件写入日志,而不是发送出去。配置从环境变量读取 主机,所以生产环境只需设置 SMTP_HOST:

yaml
# Recipe: mail in development. `host: log` writes each message to the log
# instead of sending it; set SMTP_HOST in production and the same page sends.
paths:
  components: ./components

mail:
  host: ${SMTP_HOST:-log}
  from: support@example.com
xml
<q:component name="Contact">
  <q:action name="send" method="POST">
    <q:param name="email" type="email" required="true" />
    <q:param name="message" required="true" minlength="5" />
    <q:mail to="support@example.com" reply_to="{email}" subject="Contact from {email}" type="text">{message}</q:mail>
    <q:redirect url="/" flash="Thanks! We will answer {email}." />
  </q:action>

  <h1>Contact us</h1>
  <q:if condition="flash"><p class="flash">{flash}</p></q:if>
  <form method="POST" action="/?action=send">
    <input name="email" type="email" />
    <textarea name="message"></textarea>
    <button>Send</button>
  </form>
</q:component>

测试提交表单,检查访问者得到的提示,以及错误的地址在发送任何内容之前就在它的字段上被拒绝:

xml
<q:test name="a message is sent and the visitor is told" page="/">
  <test:submit action="send" email="ana@example.com" message="Where is my order?" />
  <test:expect redirect="/" flash="Thanks! We will answer ana@example.com." />
</q:test>

<q:test name="an address that is not an e-mail is refused on its field" page="/">
  <test:submit action="send" email="not-an-email" message="Where is my order?" />
  <test:expect error="email" />
</q:test>
text
tests/contact.test.q
  PASS  a message is sent and the visitor is told
  PASS  an address that is not an e-mail is refused on its field
2 passed, 0 failed

这是第一个测试"发送"的邮件——也就是 host: log 写下的内容:

text
q:mail (host: log, not sent)
From: support@example.com
To: support@example.com
Subject: Contact from ana@example.com

Where is my order?

没有 mail: 部分时,q:mail 会报错并说明原因——它从不假装已经发送。更多内容见 Files & Mail(英文)。

已测试: 本页导入了 examples/cookbook/files-and-mail/mail-in-development/ 中的文件, 上面的结果来自运行它们。

MIT 许可证 · 使用 VitePress 构建