When the mail server says no
Task: an order must be saved even when the confirmation e-mail cannot be sent — and the visitor should hear about it, not get an error page.
By default a q:mail the server does not take stops the action with the server's reason. onerror="continue" lets the action go on and puts the outcome in <name>_result: success, and error.message when it failed.
This recipe points at a mail server that is not there, so every message fails — as it does when the real server is down:
# Recipe: an order is saved even when the confirmation e-mail cannot be sent.
# The mail server here is deliberately unreachable (nothing listens on port 9),
# so every q:mail fails — as it does when the real server is down.
paths:
components: ./components
migrations: ./migrations
datasources:
db:
driver: sqlite
database: ./data/orders.db
mail:
host: 127.0.0.1
port: 9
tls: false
timeout: 2
from: shop@example.comCREATE TABLE orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
item TEXT NOT NULL
);<q:component name="Order">
<q:action name="order" method="POST">
<q:param name="email" type="email" required="true" />
<q:param name="item" required="true" />
<q:query name="saved" datasource="db">
INSERT INTO orders (email, item) VALUES (:email, :item)
<q:param name="email" value="{email}" type="string" />
<q:param name="item" value="{item}" type="string" />
</q:query>
<!-- onerror="continue": a refused message does not undo the order -->
<q:mail name="confirmation" to="{email}" subject="Your order: {item}"
type="text" onerror="continue">We received your order for {item}.</q:mail>
<q:if condition="confirmation_result.success">
<q:redirect url="/" flash="Ordered {item}. A confirmation is on its way." />
</q:if>
<q:redirect url="/" flash="Ordered {item}. We could not send the confirmation e-mail." />
</q:action>
<h1>Order</h1>
<q:if condition="flash"><p class="flash">{flash}</p></q:if>
<form method="POST" action="/?action=order">
<input name="email" type="email" />
<input name="item" />
<button>Order</button>
</form>
</q:component>The order is inserted before the mail, and the flash says which way it went. The test checks both — the row is there, and the visitor was told:
<q:test name="the order is saved and the visitor told the e-mail failed" page="/">
<test:submit action="order" email="ana@example.com" item="Blue mug" />
<test:expect redirect="/" flash="Ordered Blue mug. We could not send the confirmation e-mail." />
<test:expect table="orders" count="1" where="email = 'ana@example.com' AND item = 'Blue mug'" />
</q:test>tests/order.test.q
PASS the order is saved and the visitor told the e-mail failed
1 passed, 0 failedIn development, host: log avoids the failure altogether; onerror="continue" is for the day the real server is down. More in Files & Mail.
Tested: this page imports the files of examples/cookbook/files-and-mail/mail-server-refuses/, and the result above comes from running them.