packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits. Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
This commit is contained in:
commit
306b143104
72 changed files with 10915 additions and 0 deletions
132
email/README.md
Normal file
132
email/README.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
# @weft/email
|
||||
|
||||
Email for Weft: sending through Resend and Postmark, MIME messages with attachments, and templates that render to HTML and
|
||||
text. Its only capabilities are `http.fetch@api.resend.com`, `http.fetch@api.postmarkapp.com` and `http.media`, because its
|
||||
`Img` component shows the image a template names.
|
||||
|
||||
```sh
|
||||
weft add weft/email
|
||||
```
|
||||
|
||||
```weft
|
||||
import { send } from "@weft/email"
|
||||
import { resend } from "@weft/email/resend"
|
||||
import { document } from "@weft/email/template"
|
||||
import { render } from "std/app"
|
||||
import { env } from "std/process"
|
||||
import Receipt from "./Receipt"
|
||||
|
||||
let mail = resend({ apiKey: env("RESEND_API_KEY")! })
|
||||
|
||||
let body = document(render(Receipt, { name: "Ana", total: "19,99 €" }), {
|
||||
title: "Your receipt",
|
||||
preheader: "Thanks for your order",
|
||||
footer: "Example d.o.o., Ljubljana",
|
||||
})
|
||||
let sent = try await send(mail, {
|
||||
from: { email: "info@example.com", name: "Example" },
|
||||
to: ["ana@example.com"],
|
||||
subject: "Your receipt",
|
||||
html: body.html,
|
||||
text: body.text,
|
||||
})
|
||||
```
|
||||
|
||||
```weft file=Receipt.weft
|
||||
import Button from "@weft/email/components/Button"
|
||||
import Facts from "@weft/email/components/Facts"
|
||||
import H1 from "@weft/email/components/H1"
|
||||
import P from "@weft/email/components/P"
|
||||
import Strong from "@weft/email/components/Strong"
|
||||
|
||||
prop name: string
|
||||
prop total: string
|
||||
---
|
||||
<H1>Thank you!</H1>
|
||||
<P>Hi <Strong>{name}</Strong>, your payment came through.</P>
|
||||
<Facts rows={[["Total", total]]} />
|
||||
<Button url="https://example.com/orders" label="Your orders" />
|
||||
```
|
||||
|
||||
## Modules
|
||||
|
||||
| module | what |
|
||||
|---|---|
|
||||
| `@weft/email` | `Message`, `send`, `validate`, `allowlist`, `memory` and `outbox` for tests |
|
||||
| `@weft/email/resend` | `resend({ apiKey })` |
|
||||
| `@weft/email/postmark` | `postmark({ serverToken, messageStream? })` |
|
||||
| `@weft/email/mime` | `toMime(message)`, the message as RFC 5322 text |
|
||||
| `@weft/email/template` | `document`, `isSafeUrl` |
|
||||
| `@weft/email/components/…` | `H1`, `H2`, `P`, `Strong`, `Em`, `A`, `Img`, `Ul`, `Ol`, `Facts`, `Button`, `Hr` |
|
||||
|
||||
## Messages
|
||||
|
||||
`send` validates a message before anything leaves. A line break in a subject, a display name or a header is refused, because it
|
||||
would let whoever typed that text add headers of their own, such as a `Bcc`.
|
||||
|
||||
```weft
|
||||
try await send(mail, {
|
||||
from: { email: "info@example.com", name: "Example" },
|
||||
to: ["ana@example.com"],
|
||||
replyTo: "owner@example.com",
|
||||
subject: "Your ticket",
|
||||
html: body.html,
|
||||
text: body.text,
|
||||
headers: [["List-Unsubscribe", "<https://example.com/unsubscribe?id=1>"]],
|
||||
attachments: [
|
||||
{ filename: "ticket.pdf", content: pdf, type: "application/pdf" },
|
||||
{ filename: "logo.png", content: logo, type: "image/png", contentId: "logo" }, // <img src="cid:logo">
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Errors are values
|
||||
|
||||
| `EmailError` | what to do |
|
||||
|---|---|
|
||||
| `InvalidMessage { field, message }` | fix the message: nothing was attempted |
|
||||
| `Rejected { status, code, message }` | a bad key, an unverified domain, a suppressed address: sending it again won't help |
|
||||
| `RateLimited { message, retryAfter }` | try again later |
|
||||
| `ProviderFailure { status, message }` | try again later |
|
||||
| `ConnectionFailed { message }` | the message **may** have been sent |
|
||||
| `BadResponse { message }` | the message may have been sent |
|
||||
|
||||
Nothing is retried for you, because sending an email twice is worse than a delay. With Resend, `idempotencyKey` makes a repeat
|
||||
safe:
|
||||
|
||||
```weft
|
||||
let mail = resend({ apiKey, idempotencyKey: m => `order-${orderId}` })
|
||||
```
|
||||
|
||||
## Staging
|
||||
|
||||
`allowlist` sends only to the addresses listed, and skips the rest without failing, so a staging site can't email real customers.
|
||||
`"*"` lifts the limit:
|
||||
|
||||
```weft
|
||||
let mail = allowlist(resend({ apiKey }), (env("EMAIL_ALLOWLIST") ?? "info@example.com").split(","))
|
||||
```
|
||||
|
||||
In tests, `memory()` keeps messages in `outbox()` instead of sending them.
|
||||
|
||||
## Templates
|
||||
|
||||
A template is a Weft component. `render` from `std/app` turns it into HTML with inline styles and a text version that reads as if a
|
||||
person wrote it. Everything a component shows is escaped, and a link that isn't `http`, `https`, `mailto`, `tel` or `cid` keeps
|
||||
only its text. Your own markup works too: classes become inline styles, and `hover:`, `dark:` and breakpoint classes are left out.
|
||||
|
||||
`document` wraps a rendered template in the whole email, a centred column that works in mail clients.
|
||||
|
||||
## What has and hasn't been tested
|
||||
|
||||
`node packages/email/scripts/integration.mjs` sends through both providers' APIs to a scripted server, and checks a full message
|
||||
with Python's `email` parser, an independent reader of the MIME. `weft test tests/email.test.weft` covers validation, encoding,
|
||||
payloads and templates. **No email has been sent through Resend or Postmark themselves**: the payloads follow their API references,
|
||||
so try a test key before relying on this.
|
||||
|
||||
## Limits
|
||||
|
||||
- **No SMTP.** `std` has no TCP or TLS sockets, so this package can't talk to a mail server. `toMime` already writes what SMTP's
|
||||
`DATA` needs, so only the socket is missing.
|
||||
- **It reaches only Resend's and Postmark's API hosts.** As a dependency, a `baseUrl` on any other host fails with a
|
||||
`CapabilityError`. To point it at a test server, the app lists that host in `allow` too, beside the two API hosts.
|
||||
8
email/components/A.weft
Normal file
8
email/components/A.weft
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/// A link. An address that isn't `http`, `https`, `mailto`, `tel` or `cid` renders as its text.
|
||||
import { isSafeUrl } from "../template"
|
||||
prop href: string
|
||||
prop children: Snippet
|
||||
---
|
||||
@if isSafeUrl(href) {<Link
|
||||
to={Route.url(href)}
|
||||
class="underline">@render children()</Link>} @else {@render children()}
|
||||
18
email/components/Button.weft
Normal file
18
email/components/Button.weft
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
/// A button. In the text version it is its label and its address.
|
||||
import type { Color } from "std/color"
|
||||
import { isSafeUrl } from "../template"
|
||||
prop url: string
|
||||
prop label: string
|
||||
prop color: Color = "#111111"
|
||||
prop textColor: Color = "#ffffff"
|
||||
---
|
||||
@if isSafeUrl(url) {
|
||||
<Box class="my-5">
|
||||
<Box class="inline-block rounded-md" style={{ background: color }}>
|
||||
<Link to={Route.url(url)} class="inline-block px-5 py-3 no-underline font-semibold"><Text
|
||||
style={{ color: textColor }}>{label}</Text></Link>
|
||||
</Box>
|
||||
</Box>
|
||||
} @else {
|
||||
<Box class="mb-4">{label}</Box>
|
||||
}
|
||||
4
email/components/Em.weft
Normal file
4
email/components/Em.weft
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/// Italic text.
|
||||
prop children: Snippet
|
||||
---
|
||||
<Box class="inline italic">@render children()</Box>
|
||||
9
email/components/Facts.weft
Normal file
9
email/components/Facts.weft
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/// Labels and values, as on a receipt.
|
||||
prop rows: [string, string][]
|
||||
---
|
||||
<Box role="list" class="mb-4">
|
||||
@for row of rows {
|
||||
<Box class="flex gap-3 py-1"><Text
|
||||
class="text-muted-foreground">{row[0]}:</Text> <Text>{row[1]}</Text></Box>
|
||||
}
|
||||
</Box>
|
||||
4
email/components/H1.weft
Normal file
4
email/components/H1.weft
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/// The largest heading.
|
||||
prop children: Snippet
|
||||
---
|
||||
<Box class="mb-4 text-2xl font-bold">@render children()</Box>
|
||||
4
email/components/H2.weft
Normal file
4
email/components/H2.weft
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/// A heading.
|
||||
prop children: Snippet
|
||||
---
|
||||
<Box class="mb-3 text-lg font-bold">@render children()</Box>
|
||||
3
email/components/Hr.weft
Normal file
3
email/components/Hr.weft
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
/// A horizontal rule.
|
||||
---
|
||||
<Box role="separator" class="my-5 border-t border-border" />
|
||||
13
email/components/Img.weft
Normal file
13
email/components/Img.weft
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
/// An image. Use an absolute URL, or `cid:<contentId>` for an attachment sent inline.
|
||||
import { isSafeUrl } from "../template"
|
||||
prop src: string
|
||||
prop alt: string
|
||||
prop width?: float
|
||||
---
|
||||
@if !isSafeUrl(src) {
|
||||
<Text>{alt}</Text>
|
||||
} @else if width != null {
|
||||
<Image src={src} label={alt} class="max-w-full h-auto" style={{ width }} />
|
||||
} @else {
|
||||
<Image src={src} label={alt} class="max-w-full h-auto" />
|
||||
}
|
||||
8
email/components/Ol.weft
Normal file
8
email/components/Ol.weft
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/// A numbered list, one line for each item.
|
||||
prop items: string[]
|
||||
---
|
||||
<Box role="list" class="mb-4">
|
||||
@for [i, item] of items.entries() {
|
||||
<Box class="mb-1">{i + 1}. {item}</Box>
|
||||
}
|
||||
</Box>
|
||||
4
email/components/P.weft
Normal file
4
email/components/P.weft
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/// A paragraph.
|
||||
prop children: Snippet
|
||||
---
|
||||
<Box class="mb-4">@render children()</Box>
|
||||
4
email/components/Strong.weft
Normal file
4
email/components/Strong.weft
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/// Bold text.
|
||||
prop children: Snippet
|
||||
---
|
||||
<Box class="inline font-bold">@render children()</Box>
|
||||
8
email/components/Ul.weft
Normal file
8
email/components/Ul.weft
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/// A list, one line for each item.
|
||||
prop items: string[]
|
||||
---
|
||||
<Box role="list" class="mb-4">
|
||||
@for item of items {
|
||||
<Box class="mb-1">- {item}</Box>
|
||||
}
|
||||
</Box>
|
||||
227
email/email.weft
Normal file
227
email/email.weft
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
// `@weft/email`: messages, their validation and sending them through a transport.
|
||||
/// An email address, with or without a display name: `"ana@example.com"` or `{ email: "ana@example.com", name: "Ana" }`.
|
||||
export type Address = string | { email: string, name?: string }
|
||||
|
||||
/// A file sent with a message. `type` is its media type (`application/octet-stream` unless given). `contentId` makes it an
|
||||
/// inline image, which the HTML shows with `<img src="cid:…">`.
|
||||
export type Attachment = { filename: string, content: Bytes, type?: string, contentId?: string }
|
||||
|
||||
/// A message. It needs a `from`, at least one recipient, a `subject` and an `html` or `text` body; send both when you can,
|
||||
/// since spam filters and some readers want the text. `headers` are extra headers, such as `List-Unsubscribe`.
|
||||
export type Message = {
|
||||
from: Address,
|
||||
to: Address[],
|
||||
cc?: Address[],
|
||||
bcc?: Address[],
|
||||
replyTo?: Address,
|
||||
subject: string,
|
||||
html?: string,
|
||||
text?: string,
|
||||
headers?: [string, string][],
|
||||
attachments?: Attachment[],
|
||||
}
|
||||
|
||||
/// What sending gave: the provider's id for the message. `skipped` is true when `allowlist` kept it from being sent.
|
||||
export type Sent = { id: string, provider: string, skipped: boolean }
|
||||
|
||||
/// Why a message wasn't sent.
|
||||
///
|
||||
/// - `InvalidMessage`: the message can't be sent as it is, and nothing was attempted. `field` says what is wrong.
|
||||
/// - `Rejected`: the provider refused it (a bad key, an unverified domain, a suppressed recipient). Sending it again won't help.
|
||||
/// - `RateLimited`: too many messages. Try again later.
|
||||
/// - `ProviderFailure`: the provider had a problem. Try again later.
|
||||
/// - `ConnectionFailed`: the provider wasn't reached, or its answer broke off, so the message **may** have been sent.
|
||||
/// - `BadResponse`: the provider's answer couldn't be read, so the message may have been sent.
|
||||
export type EmailError =
|
||||
| InvalidMessage { field: string, message: string }
|
||||
| Rejected { status: float, code: string?, message: string }
|
||||
| RateLimited { message: string, retryAfter: float? }
|
||||
| ProviderFailure { status: float, message: string }
|
||||
| ConnectionFailed { message: string }
|
||||
| BadResponse { message: string }
|
||||
|
||||
/// How messages leave: `resend(…)`, `postmark(…)`, `memory()`, or your own.
|
||||
export type Transport = { name: string, send: (message: Message) => Task<Sent ! EmailError> }
|
||||
|
||||
/// The plain address of an `Address`.
|
||||
export fn emailOf(address: Address): string {
|
||||
return address is string ? address : address.email
|
||||
}
|
||||
|
||||
/// The display name of an `Address`, if it has one.
|
||||
export fn nameOf(address: Address): string? {
|
||||
return address is string ? null : address.name
|
||||
}
|
||||
|
||||
fn hasLineBreak(s: string): boolean {
|
||||
return s.includes("\r") || s.includes("\n")
|
||||
}
|
||||
|
||||
fn isAddressChar(c: int): boolean {
|
||||
// Printable ASCII but what would end an address in a header, or anything from outside ASCII (internationalised mail).
|
||||
return c > 32 &&
|
||||
c != 127 &&
|
||||
c != 60 &&
|
||||
c != 62 &&
|
||||
c != 40 &&
|
||||
c != 41 &&
|
||||
c != 44 &&
|
||||
c != 59 &&
|
||||
c != 58 &&
|
||||
c != 34 &&
|
||||
c != 92 &&
|
||||
c != 91 &&
|
||||
c != 93
|
||||
}
|
||||
|
||||
/// Whether `email` has the shape of an address: one `@`, something on both sides, nothing that would end it in a header.
|
||||
export fn isValidEmail(email: string): boolean {
|
||||
let at = email.indexOf("@")
|
||||
if at <= 0 || at != email.lastIndexOf("@") || at == email.length - 1 || email.length > 254 {
|
||||
return false
|
||||
}
|
||||
for i of 0..email.length {
|
||||
let c = email.codeUnitAt(i) ?? 0
|
||||
if c != 64 && !isAddressChar(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
let domain = email.slice(at + 1)
|
||||
return !domain.startsWith(".") && !domain.endsWith(".") && !domain.includes("..")
|
||||
}
|
||||
|
||||
fn checkAddress(field: string, address: Address): void ! EmailError {
|
||||
let email = emailOf(address)
|
||||
if !isValidEmail(email) {
|
||||
fail InvalidMessage { field, message: `\`${email}\` isn't an email address` }
|
||||
}
|
||||
if hasLineBreak(nameOf(address) ?? "") {
|
||||
fail InvalidMessage { field, message: "a display name can't hold a line break" }
|
||||
}
|
||||
}
|
||||
|
||||
fn isHeaderName(name: string): boolean {
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
for i of 0..name.length {
|
||||
let c = name.codeUnitAt(i) ?? 0
|
||||
if c <= 32 || c >= 127 || c == 58 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Checks a message before it is sent. Line breaks in a subject, a name or a header are refused, because they would let
|
||||
/// whoever supplied that text add headers of their own.
|
||||
export fn validate(message: Message): void ! EmailError {
|
||||
try checkAddress("from", message.from)
|
||||
let to = message.to
|
||||
let cc = message.cc ?? []
|
||||
let bcc = message.bcc ?? []
|
||||
if to.length + cc.length + bcc.length == 0 {
|
||||
fail InvalidMessage { field: "to", message: "a message needs at least one recipient" }
|
||||
}
|
||||
for address of to {
|
||||
try checkAddress("to", address)
|
||||
}
|
||||
for address of cc {
|
||||
try checkAddress("cc", address)
|
||||
}
|
||||
for address of bcc {
|
||||
try checkAddress("bcc", address)
|
||||
}
|
||||
let replyTo = message.replyTo
|
||||
if replyTo != null {
|
||||
try checkAddress("replyTo", replyTo)
|
||||
}
|
||||
if message.subject.trim() == "" {
|
||||
fail InvalidMessage { field: "subject", message: "a message needs a subject" }
|
||||
}
|
||||
if hasLineBreak(message.subject) {
|
||||
fail InvalidMessage { field: "subject", message: "a subject can't hold a line break" }
|
||||
}
|
||||
if (message.html ?? "") == "" && (message.text ?? "") == "" {
|
||||
fail InvalidMessage { field: "html", message: "a message needs an html or a text body" }
|
||||
}
|
||||
for [name, value] of message.headers ?? [] {
|
||||
if !isHeaderName(name) {
|
||||
fail InvalidMessage { field: "headers", message: `\`${name}\` isn't a header name` }
|
||||
}
|
||||
if hasLineBreak(value) {
|
||||
fail InvalidMessage {
|
||||
field: "headers",
|
||||
message: `the header \`${name}\` can't hold a line break`,
|
||||
}
|
||||
}
|
||||
}
|
||||
for attachment of message.attachments ?? [] {
|
||||
if attachment.filename == "" || hasLineBreak(attachment.filename) {
|
||||
fail InvalidMessage {
|
||||
field: "attachments",
|
||||
message: "an attachment needs a file name on one line",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks a message and sends it.
|
||||
///
|
||||
/// ```weft
|
||||
/// import { send } from "@weft/email"
|
||||
/// import { resend } from "@weft/email/resend"
|
||||
///
|
||||
/// let mail = resend({ apiKey: env("RESEND_API_KEY")! })
|
||||
/// let sent = try await send(mail, {
|
||||
/// from: { email: "info@example.com", name: "Example" },
|
||||
/// to: ["ana@example.com"],
|
||||
/// subject: "Your ticket",
|
||||
/// html: "<p>See you there.</p>",
|
||||
/// text: "See you there.",
|
||||
/// })
|
||||
/// ```
|
||||
export async fn send(transport: Transport, message: Message): Sent ! EmailError {
|
||||
try validate(message)
|
||||
return try await transport.send(message)
|
||||
}
|
||||
|
||||
/// `inner`, sending only to the addresses listed (`"*"` lifts the limit). Other messages are skipped, not failed: staging
|
||||
/// sites use this so that real customers never get a test email.
|
||||
export fn allowlist(inner: Transport, allowed: string[]): Transport {
|
||||
let list = allowed.map(a => a.trim().toLowerCase())
|
||||
let open = list.includes("*")
|
||||
return {
|
||||
name: inner.name,
|
||||
send: async message => {
|
||||
let all = [...message.to, ...(message.cc ?? []), ...(message.bcc ?? [])]
|
||||
if !open && !all.every(a => list.includes(emailOf(a).trim().toLowerCase())) {
|
||||
return { id: "", provider: inner.name, skipped: true }
|
||||
}
|
||||
return try await inner.send(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let mut sentMessages: Message[] = []
|
||||
|
||||
/// A transport that keeps messages in this process instead of sending them, for tests. Read them with `outbox()`.
|
||||
export fn memory(): Transport {
|
||||
return {
|
||||
name: "memory",
|
||||
send: async message => {
|
||||
sentMessages.push(message)
|
||||
return { id: `memory-${sentMessages.length}`, provider: "memory", skipped: false }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// What `memory()` has been given, oldest first.
|
||||
export fn outbox(): Message[] {
|
||||
return sentMessages
|
||||
}
|
||||
|
||||
/// Empties `outbox()`.
|
||||
export fn clearOutbox() {
|
||||
sentMessages = []
|
||||
}
|
||||
208
email/mime.weft
Normal file
208
email/mime.weft
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// MIME: a message as the text mail servers exchange (RFC 5322, RFC 2045–2047, RFC 2231).
|
||||
import { uuid } from "std/random"
|
||||
import { emailOf, nameOf } from "./email"
|
||||
import type { Address, Attachment, Message } from "./email"
|
||||
|
||||
fn isAscii(s: string): boolean {
|
||||
for i of 0..s.length {
|
||||
let c = s.codeUnitAt(i) ?? 0
|
||||
if c >= 127 || c < 32 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// `text` for a header: as it is when it is plain ASCII, otherwise as RFC 2047 encoded words of at most 75 characters,
|
||||
/// never splitting a character.
|
||||
export fn encodeHeader(text: string): string {
|
||||
if isAscii(text) {
|
||||
return text
|
||||
}
|
||||
let mut words: string[] = []
|
||||
let mut chunk: int[] = []
|
||||
for ch of text {
|
||||
let bytes = Bytes.fromUtf8(ch).toList()
|
||||
// 45 bytes of base64 fill an encoded word's 60 characters.
|
||||
if chunk.length + bytes.length > 45 {
|
||||
words.push(`=?UTF-8?B?${Bytes.of(chunk).toBase64()}?=`)
|
||||
chunk = []
|
||||
}
|
||||
chunk.push(...bytes)
|
||||
}
|
||||
if chunk.length > 0 {
|
||||
words.push(`=?UTF-8?B?${Bytes.of(chunk).toBase64()}?=`)
|
||||
}
|
||||
return words.join("\r\n ")
|
||||
}
|
||||
|
||||
fn quoted(name: string): string {
|
||||
return `"${name.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`
|
||||
}
|
||||
|
||||
/// An address as a header writes it.
|
||||
export fn formatAddress(address: Address): string {
|
||||
let email = emailOf(address)
|
||||
let name = nameOf(address)
|
||||
if name == null || name == "" {
|
||||
return email
|
||||
}
|
||||
return isAscii(name) ? `${quoted(name)} <${email}>` : `${encodeHeader(name)} <${email}>`
|
||||
}
|
||||
|
||||
fn addressList(list: Address[]): string {
|
||||
return list.map(formatAddress).join(",\r\n ")
|
||||
}
|
||||
|
||||
/// One character of a line in quoted-printable. Spaces and tabs at the end of a line are encoded, as RFC 2045 requires.
|
||||
fn encodeChar(ch: string, last: boolean): string {
|
||||
let c = ch.codePointAt(0) ?? 0
|
||||
if (c >= 33 && c <= 126 && c != 61) || ((c == 32 || c == 9) && !last) {
|
||||
return ch
|
||||
}
|
||||
return Bytes.fromUtf8(ch)
|
||||
.toList()
|
||||
.map(b => "=" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0"))
|
||||
.join("")
|
||||
}
|
||||
|
||||
/// `text` in quoted-printable (RFC 2045): lines of at most 76 characters, with no character split across two of them.
|
||||
export fn quotedPrintable(text: string): string {
|
||||
let source = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n")
|
||||
let mut lines: string[] = []
|
||||
for line of source.split("\n") {
|
||||
let mut all: string[] = []
|
||||
for ch of line {
|
||||
all.push(ch)
|
||||
}
|
||||
let mut out: string[] = []
|
||||
let mut width = 0
|
||||
for [i, ch] of all.entries() {
|
||||
let piece = encodeChar(ch, i == all.length - 1)
|
||||
if width + piece.length > 75 {
|
||||
out.push("=\r\n")
|
||||
width = 0
|
||||
}
|
||||
out.push(piece)
|
||||
width += piece.length
|
||||
}
|
||||
lines.push(out.join(""))
|
||||
}
|
||||
return lines.join("\r\n")
|
||||
}
|
||||
|
||||
fn wrapBase64(bytes: Bytes): string {
|
||||
let text = bytes.toBase64()
|
||||
let mut lines: string[] = []
|
||||
let mut i = 0
|
||||
while i < text.length {
|
||||
lines.push(text.slice(i, i + 76))
|
||||
i += 76
|
||||
}
|
||||
return lines.join("\r\n")
|
||||
}
|
||||
|
||||
fn textPart(media: string, body: string): string {
|
||||
return `Content-Type: ${media}; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${quotedPrintable(body)}`
|
||||
}
|
||||
|
||||
fn quotedParam(value: string): string {
|
||||
return quoted(value)
|
||||
}
|
||||
|
||||
fn percentEncoded(text: string): string {
|
||||
let mut out: string[] = []
|
||||
for b of Bytes.fromUtf8(text).toList() {
|
||||
let plain = (b >= 48 && b <= 57) ||
|
||||
(b >= 65 && b <= 90) ||
|
||||
(b >= 97 && b <= 122) ||
|
||||
b == 45 ||
|
||||
b == 46 ||
|
||||
b == 95
|
||||
out.push(plain ? String.fromCharCode(b) : "%" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0"))
|
||||
}
|
||||
return out.join("")
|
||||
}
|
||||
|
||||
fn fileParam(name: string, filename: string): string {
|
||||
return isAscii(filename)
|
||||
? `${name}=${quotedParam(filename)}`
|
||||
: `${name}*=UTF-8''${percentEncoded(filename)}`
|
||||
}
|
||||
|
||||
fn attachmentPart(a: Attachment): string {
|
||||
let media = a.type ?? "application/octet-stream"
|
||||
let inline = a.contentId != null
|
||||
let head = [
|
||||
`Content-Type: ${media}; ${fileParam("name", a.filename)}`,
|
||||
"Content-Transfer-Encoding: base64",
|
||||
`Content-Disposition: ${inline ? "inline" : "attachment"}; ${fileParam("filename", a.filename)}`,
|
||||
]
|
||||
let cid = a.contentId
|
||||
let lines = cid != null ? [...head, `Content-ID: <${cid}>`] : head
|
||||
return `${lines.join("\r\n")}\r\n\r\n${wrapBase64(a.content)}`
|
||||
}
|
||||
|
||||
fn multipart(subtype: string, boundary: string, parts: string[]): string {
|
||||
let body = parts.map(p => `--${boundary}\r\n${p}\r\n`).join("")
|
||||
return `Content-Type: multipart/${subtype};\r\n boundary="${boundary}"\r\n\r\n${body}--${boundary}--`
|
||||
}
|
||||
|
||||
/// `id` makes the boundaries and the `Message-ID` repeatable, and `date` is the `Date` header (RFC 5322 form), for tests.
|
||||
export type MimeOptions = { id?: string, date?: string }
|
||||
|
||||
fn domainOf(address: Address): string {
|
||||
let email = emailOf(address)
|
||||
return email.slice(email.indexOf("@") + 1)
|
||||
}
|
||||
|
||||
/// The whole message as MIME text, with CRLF line endings and only ASCII in it: what an SMTP server is given after `DATA`.
|
||||
/// `bcc` isn't written, since every recipient would see it.
|
||||
///
|
||||
/// ```weft
|
||||
/// let source = toMime({ from: "a@example.com", to: ["b@example.com"], subject: "Hi", text: "Hello" })
|
||||
/// ```
|
||||
export fn toMime(message: Message, options: MimeOptions = {}): string {
|
||||
let id = options.id ?? uuid()
|
||||
let mut headers: string[] = [
|
||||
`From: ${formatAddress(message.from)}`,
|
||||
`To: ${addressList(message.to)}`,
|
||||
]
|
||||
let cc = message.cc ?? []
|
||||
if cc.length > 0 {
|
||||
headers.push(`Cc: ${addressList(cc)}`)
|
||||
}
|
||||
let replyTo = message.replyTo
|
||||
if replyTo != null {
|
||||
headers.push(`Reply-To: ${formatAddress(replyTo)}`)
|
||||
}
|
||||
headers.push(`Subject: ${encodeHeader(message.subject)}`)
|
||||
let date = options.date
|
||||
if date != null {
|
||||
headers.push(`Date: ${date}`)
|
||||
}
|
||||
headers.push(`Message-ID: <${id}@${domainOf(message.from)}>`)
|
||||
headers.push("MIME-Version: 1.0")
|
||||
for [name, value] of message.headers ?? [] {
|
||||
headers.push(`${name}: ${encodeHeader(value)}`)
|
||||
}
|
||||
let text = message.text ?? ""
|
||||
let html = message.html ?? ""
|
||||
let mut body = text != "" && html != ""
|
||||
? multipart(
|
||||
"alternative",
|
||||
`alt-${id}`,
|
||||
[textPart("text/plain", text), textPart("text/html", html)],
|
||||
)
|
||||
: html != "" ? textPart("text/html", html) : textPart("text/plain", text)
|
||||
let attachments = message.attachments ?? []
|
||||
let inline = attachments.filter(a => a.contentId != null)
|
||||
let files = attachments.filter(a => a.contentId == null)
|
||||
if inline.length > 0 {
|
||||
body = multipart("related", `rel-${id}`, [body, ...inline.map(attachmentPart)])
|
||||
}
|
||||
if files.length > 0 {
|
||||
body = multipart("mixed", `mix-${id}`, [body, ...files.map(attachmentPart)])
|
||||
}
|
||||
return `${headers.join("\r\n")}\r\n${body}\r\n`
|
||||
}
|
||||
131
email/postmark.weft
Normal file
131
email/postmark.weft
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
// Sending through Postmark (https://postmarkapp.com/developer/api/email-api).
|
||||
import { fetch } from "std/http"
|
||||
import type { Address, EmailError, Message, Transport } from "./email"
|
||||
import { formatAddress } from "./mime"
|
||||
|
||||
/// `messageStream` is Postmark's stream to send on (`outbound` unless given; broadcasts need `broadcast`). `baseUrl` is for tests.
|
||||
export type PostmarkOptions = {
|
||||
serverToken: string,
|
||||
messageStream?: string,
|
||||
baseUrl?: string,
|
||||
timeout?: float,
|
||||
}
|
||||
|
||||
fn text(value: json): string? {
|
||||
return value is string ? value : null
|
||||
}
|
||||
|
||||
fn list(addresses: Address[]): string {
|
||||
return addresses.map(formatAddress).join(", ")
|
||||
}
|
||||
|
||||
/// The JSON Postmark is sent for a message.
|
||||
export fn payload(message: Message, messageStream: string = "outbound"): json {
|
||||
let mut body: json = {
|
||||
From: formatAddress(message.from),
|
||||
To: list(message.to),
|
||||
Subject: message.subject,
|
||||
MessageStream: messageStream,
|
||||
}
|
||||
let cc = message.cc ?? []
|
||||
if cc.length > 0 {
|
||||
body["Cc"] = list(cc)
|
||||
}
|
||||
let bcc = message.bcc ?? []
|
||||
if bcc.length > 0 {
|
||||
body["Bcc"] = list(bcc)
|
||||
}
|
||||
let replyTo = message.replyTo
|
||||
if replyTo != null {
|
||||
body["ReplyTo"] = formatAddress(replyTo)
|
||||
}
|
||||
let html = message.html
|
||||
if html != null && html != "" {
|
||||
body["HtmlBody"] = html
|
||||
}
|
||||
let plainText = message.text
|
||||
if plainText != null && plainText != "" {
|
||||
body["TextBody"] = plainText
|
||||
}
|
||||
let headers = message.headers ?? []
|
||||
if headers.length > 0 {
|
||||
let fields: json[] = headers.map(h => {
|
||||
let field: json = { Name: h[0], Value: h[1] }
|
||||
return field
|
||||
})
|
||||
body["Headers"] = fields
|
||||
}
|
||||
let attachments = message.attachments ?? []
|
||||
if attachments.length > 0 {
|
||||
let files: json[] = attachments.map(a => {
|
||||
let mut file: json = {
|
||||
Name: a.filename,
|
||||
Content: a.content.toBase64(),
|
||||
ContentType: a.type ?? "application/octet-stream",
|
||||
}
|
||||
let cid = a.contentId
|
||||
if cid != null {
|
||||
file["ContentID"] = `cid:${cid}`
|
||||
}
|
||||
return file
|
||||
})
|
||||
body["Attachments"] = files
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
/// The error for an answer that isn't a success.
|
||||
export fn failureOf(status: float, body: json): EmailError {
|
||||
let message = text(body.Message) ?? `Postmark answered ${status}`
|
||||
let code = body.ErrorCode
|
||||
if status == 429 {
|
||||
return RateLimited { message, retryAfter: null }
|
||||
}
|
||||
if status >= 500 {
|
||||
return ProviderFailure { status, message }
|
||||
}
|
||||
return Rejected { status, code: code is float ? `${code}` : null, message }
|
||||
}
|
||||
|
||||
/// A transport that sends through Postmark. It needs `http.fetch`.
|
||||
///
|
||||
/// ```weft
|
||||
/// let mail = postmark({ serverToken: env("POSTMARK_TOKEN")! })
|
||||
/// ```
|
||||
export fn postmark(options: PostmarkOptions): Transport {
|
||||
let url = `${options.baseUrl ?? "https://api.postmarkapp.com"}/email`
|
||||
let timeout = options.timeout ?? 30000
|
||||
let token = options.serverToken
|
||||
let stream = options.messageStream ?? "outbound"
|
||||
return {
|
||||
name: "postmark",
|
||||
send: async message => {
|
||||
let headers: [string, string][] = [
|
||||
["x-postmark-server-token", token],
|
||||
["accept", "application/json"],
|
||||
["user-agent", "weft-email/0.1.0"],
|
||||
]
|
||||
let res, err = try await fetch(
|
||||
url,
|
||||
{ method: "POST", headers, json: payload(message, stream), timeout },
|
||||
)
|
||||
if err != null {
|
||||
fail ConnectionFailed { message: `could not reach Postmark: ${err.message}` }
|
||||
}
|
||||
let answer = try await res.json() else null
|
||||
if !res.ok {
|
||||
fail failureOf(res.status, answer)
|
||||
}
|
||||
// Postmark can answer 200 with an error code of its own.
|
||||
let code = answer.ErrorCode
|
||||
if code is float && code != 0 {
|
||||
fail failureOf(422, answer)
|
||||
}
|
||||
let id = text(answer.MessageID)
|
||||
if id == null {
|
||||
fail BadResponse { message: "Postmark's answer has no MessageID" }
|
||||
}
|
||||
return { id, provider: "postmark", skipped: false }
|
||||
},
|
||||
}
|
||||
}
|
||||
146
email/resend.weft
Normal file
146
email/resend.weft
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
// Sending through Resend (https://resend.com/docs/api-reference/emails/send-email).
|
||||
import { fetch } from "std/http"
|
||||
import { emailOf } from "./email"
|
||||
import type { Address, EmailError, Message, Transport } from "./email"
|
||||
|
||||
/// `baseUrl` is for tests. `idempotencyKey` is sent with every message when given as a function of the message, so that
|
||||
/// sending one again by accident does nothing.
|
||||
export type ResendOptions = {
|
||||
apiKey: string,
|
||||
baseUrl?: string,
|
||||
timeout?: float,
|
||||
idempotencyKey?: (message: Message) => string?,
|
||||
}
|
||||
|
||||
fn text(value: json): string? {
|
||||
return value is string ? value : null
|
||||
}
|
||||
|
||||
fn plain(address: Address): string {
|
||||
// Resend reads a UTF-8 display name directly, so it isn't encoded as a mail header would be.
|
||||
let email = emailOf(address)
|
||||
let name = address is string ? null : address.name
|
||||
if name == null || name == "" {
|
||||
return email
|
||||
}
|
||||
return `"${name.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}" <${email}>`
|
||||
}
|
||||
|
||||
/// The JSON Resend is sent for a message.
|
||||
export fn payload(message: Message): json {
|
||||
let mut body: json = {
|
||||
from: plain(message.from),
|
||||
to: message.to.map(plain),
|
||||
subject: message.subject,
|
||||
}
|
||||
let cc = message.cc ?? []
|
||||
if cc.length > 0 {
|
||||
body["cc"] = cc.map(plain)
|
||||
}
|
||||
let bcc = message.bcc ?? []
|
||||
if bcc.length > 0 {
|
||||
body["bcc"] = bcc.map(plain)
|
||||
}
|
||||
let replyTo = message.replyTo
|
||||
if replyTo != null {
|
||||
body["reply_to"] = plain(replyTo)
|
||||
}
|
||||
let html = message.html
|
||||
if html != null && html != "" {
|
||||
body["html"] = html
|
||||
}
|
||||
let plainText = message.text
|
||||
if plainText != null && plainText != "" {
|
||||
body["text"] = plainText
|
||||
}
|
||||
let headers = message.headers ?? []
|
||||
if headers.length > 0 {
|
||||
body["headers"] = Map<string, string>(headers)
|
||||
}
|
||||
let attachments = message.attachments ?? []
|
||||
if attachments.length > 0 {
|
||||
let files: json[] = attachments.map(a => {
|
||||
let mut file: json = { filename: a.filename, content: a.content.toBase64() }
|
||||
let media = a.type
|
||||
if media != null {
|
||||
file["content_type"] = media
|
||||
}
|
||||
let cid = a.contentId
|
||||
if cid != null {
|
||||
file["content_id"] = cid
|
||||
}
|
||||
return file
|
||||
})
|
||||
body["attachments"] = files
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
/// The error for an answer that isn't a success.
|
||||
export fn failureOf(status: float, body: json, retryAfter: string?): EmailError {
|
||||
let message = text(body.message) ?? `Resend answered ${status}`
|
||||
if status == 429 {
|
||||
return RateLimited { message, retryAfter: retryAfter != null ? secondsOf(retryAfter) : null }
|
||||
}
|
||||
if status >= 500 {
|
||||
return ProviderFailure { status, message }
|
||||
}
|
||||
return Rejected { status, code: text(body.name), message }
|
||||
}
|
||||
|
||||
fn secondsOf(value: string): float? {
|
||||
let n = value.trim()
|
||||
let mut total = 0
|
||||
if n == "" {
|
||||
return null
|
||||
}
|
||||
for ch of n {
|
||||
let c = ch.codeUnitAt(0) ?? 0
|
||||
if c < 48 || c > 57 {
|
||||
return null
|
||||
}
|
||||
total = total * 10 + (c - 48)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/// A transport that sends through Resend. It needs `http.fetch`.
|
||||
///
|
||||
/// ```weft
|
||||
/// let mail = resend({ apiKey: env("RESEND_API_KEY")! })
|
||||
/// ```
|
||||
export fn resend(options: ResendOptions): Transport {
|
||||
let url = `${options.baseUrl ?? "https://api.resend.com"}/emails`
|
||||
let timeout = options.timeout ?? 30000
|
||||
let keyOf = options.idempotencyKey
|
||||
let apiKey = options.apiKey
|
||||
return {
|
||||
name: "resend",
|
||||
send: async message => {
|
||||
let mut headers: [string, string][] = [
|
||||
["authorization", `Bearer ${apiKey}`],
|
||||
["user-agent", "weft-email/0.1.0"],
|
||||
]
|
||||
let key = keyOf != null ? keyOf(message) : null
|
||||
if key != null {
|
||||
headers.push(["idempotency-key", key])
|
||||
}
|
||||
let res, err = try await fetch(
|
||||
url,
|
||||
{ method: "POST", headers, json: payload(message), timeout },
|
||||
)
|
||||
if err != null {
|
||||
fail ConnectionFailed { message: `could not reach Resend: ${err.message}` }
|
||||
}
|
||||
let answer = try await res.json() else null
|
||||
if !res.ok {
|
||||
fail failureOf(res.status, answer, res.headers.get("retry-after"))
|
||||
}
|
||||
let id = text(answer.id)
|
||||
if id == null {
|
||||
fail BadResponse { message: "Resend's answer has no id" }
|
||||
}
|
||||
return { id, provider: "resend", skipped: false }
|
||||
},
|
||||
}
|
||||
}
|
||||
49
email/scripts/check_mime.py
Normal file
49
email/scripts/check_mime.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# Reads the message packages/integration/email prints and checks it with Python's own `email` parser: an independent reader
|
||||
# of what `toMime` writes. Usage: python3 check_mime.py <file with the message>
|
||||
import email
|
||||
import email.policy
|
||||
import sys
|
||||
|
||||
raw = open(sys.argv[1], "rb").read()
|
||||
assert b"\r\n" in raw and b"\n" not in raw.replace(b"\r\n", b""), "every line ends in CRLF"
|
||||
assert all(b < 128 for b in raw), "the message is ASCII"
|
||||
for line in raw.split(b"\r\n"):
|
||||
assert len(line) <= 998, "no line is over RFC 5322's limit"
|
||||
|
||||
msg = email.message_from_bytes(raw, policy=email.policy.default)
|
||||
defects = list(msg.defects) + [d for part in msg.walk() for d in part.defects]
|
||||
assert not defects, f"the parser found defects: {defects}"
|
||||
|
||||
assert msg["Subject"] == "Vaša vstopnica za dogodek: čudovit večer na gradu, ki se ga boste še dolgo spominjali", msg["Subject"]
|
||||
assert msg["From"].addresses[0].display_name == 'Žiga "Vidni" Novak', msg["From"]
|
||||
assert msg["From"].addresses[0].addr_spec == "info@example.com"
|
||||
to = msg["To"].addresses
|
||||
assert [a.addr_spec for a in to] == ["ana@example.com", "bor@example.com"], msg["To"]
|
||||
assert to[1].display_name == "Bor Šuštar", to[1].display_name
|
||||
assert msg["Cc"].addresses[0].addr_spec == "cene@example.com"
|
||||
assert msg["Bcc"] is None and b"skrito@example.com" not in raw, "bcc isn't written"
|
||||
assert msg["Reply-To"].addresses[0].addr_spec == "lastnik@example.com"
|
||||
assert msg["List-Unsubscribe"] == "<https://example.com/odjava?id=1>"
|
||||
assert msg["X-Oznaka"] == "račun", msg["X-Oznaka"]
|
||||
assert msg["MIME-Version"] == "1.0"
|
||||
assert msg["Message-ID"].endswith("@example.com>")
|
||||
|
||||
assert msg.get_content_type() == "multipart/mixed", msg.get_content_type()
|
||||
long = "Pozdravljeni, to je dolgo sporočilo s črkami č, š in ž, ki sega čez mejo šestinsedemdesetih znakov v vrstici. = in pika.\n.vrstica s piko\nKonec "
|
||||
plain = msg.get_body(preferencelist=("plain",)).get_content()
|
||||
assert plain.replace("\r\n", "\n").rstrip("\n") == long, repr(plain)
|
||||
html = msg.get_body(preferencelist=("html",)).get_content()
|
||||
assert html.replace("\r\n", "\n").rstrip("\n") == f'<p>{long}</p><img src="cid:logo">', repr(html)
|
||||
|
||||
files = {part.get_filename(): part for part in msg.iter_attachments()}
|
||||
assert set(files) == {"račun št. 5.pdf", "dogodek.ics"}, set(files)
|
||||
assert files["račun št. 5.pdf"].get_content() == bytes(range(256))
|
||||
assert files["račun št. 5.pdf"].get_content_type() == "application/pdf"
|
||||
assert files["dogodek.ics"].get_content_type() == "text/calendar"
|
||||
|
||||
inline = [p for p in msg.walk() if p.get("Content-ID")]
|
||||
assert len(inline) == 1 and inline[0]["Content-ID"] == "<logo>" and inline[0].get_content_disposition() == "inline"
|
||||
assert inline[0].get_payload(decode=True) == bytes([137, 80, 78, 71])
|
||||
kinds = [p.get_content_type() for p in msg.walk()]
|
||||
assert kinds[:4] == ["multipart/mixed", "multipart/related", "multipart/alternative", "text/plain"], kinds
|
||||
print("Python's email parser reads the message back exactly")
|
||||
28
email/scripts/integration.mjs
Normal file
28
email/scripts/integration.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// Runs packages/integration/email, then checks the MIME it prints with Python's `email` parser.
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdirSync, writeFileSync } from "node:fs"
|
||||
import { dirname, join } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..")
|
||||
const weft = process.env.WEFT_BIN ?? join(root, "../../core/target/release/weft")
|
||||
const app = join(root, "../integration/email")
|
||||
spawnSync(weft, ["install"], { cwd: app, stdio: "inherit" })
|
||||
const r = spawnSync(weft, ["run", "."], { cwd: app, encoding: "utf8", env: { ...process.env, WEFT_DEADLINE_MS: "0" } })
|
||||
const out = r.stdout
|
||||
const [before, rest] = out.split("=====MIME=====\n")
|
||||
if (!rest) {
|
||||
console.log(out, r.stderr)
|
||||
process.exit(1)
|
||||
}
|
||||
const [mime, after] = rest.split("=====END=====\n")
|
||||
process.stdout.write(before + after)
|
||||
if (r.stderr) process.stderr.write(r.stderr)
|
||||
const dir = join(root, "../../core/target/tools")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const file = join(dir, "email-sample.eml")
|
||||
writeFileSync(file, mime, "latin1")
|
||||
const py = spawnSync("python3", ["-I", join(root, "scripts/check_mime.py"), file], { encoding: "utf8" })
|
||||
process.stdout.write(py.stdout)
|
||||
process.stderr.write(py.stderr)
|
||||
process.exit(r.status === 0 && py.status === 0 ? 0 : 1)
|
||||
45
email/template.weft
Normal file
45
email/template.weft
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// Email templates are Weft components: write one with the components in `components/`, render it with `render` from `std/app`,
|
||||
// and give the result to `document`. Everything shown in a component is escaped, so values from users are safe in it.
|
||||
/// An email rendered both ways: what `render` from `std/app` gives.
|
||||
export type Rendered = { html: string, text: string }
|
||||
|
||||
fn escape(s: string): string {
|
||||
return s.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll("\"", """)
|
||||
}
|
||||
|
||||
/// Whether an address may go in a link or an image: `http`, `https`, `mailto`, `tel` or `cid`.
|
||||
export fn isSafeUrl(url: string): boolean {
|
||||
let lower = url.trim().toLowerCase()
|
||||
return lower.startsWith("http://") ||
|
||||
lower.startsWith("https://") ||
|
||||
lower.startsWith("mailto:") ||
|
||||
lower.startsWith("tel:") ||
|
||||
lower.startsWith("cid:")
|
||||
}
|
||||
|
||||
/// What surrounds an email's content. `preheader` is the line inboxes show beside the subject; `footer` is the small print;
|
||||
/// `lang` is the language of the text (`en`).
|
||||
export type DocumentOptions = { title?: string, preheader?: string, footer?: string, lang?: string }
|
||||
|
||||
/// A rendered template as a whole email: its content in a centred column, with the preheader and footer.
|
||||
///
|
||||
/// ```weft
|
||||
/// let mail = document(render(Receipt, { name: "Ana", total: "19,99 €" }), { title: "Your receipt", footer: "Example d.o.o." })
|
||||
/// ```
|
||||
export fn document(content: Rendered, options: DocumentOptions = {}): Rendered {
|
||||
let body = content.html
|
||||
let preheader = options.preheader ?? ""
|
||||
let hidden = preheader != ""
|
||||
? `<div style="display:none;max-height:0;overflow:hidden;opacity:0">${escape(preheader)}</div>`
|
||||
: ""
|
||||
let footer = options.footer ?? ""
|
||||
let small = footer != ""
|
||||
? `<p style="margin:24px 0 0;font-size:12px;line-height:1.5;color:#8a8a84">${escape(footer)}</p>`
|
||||
: ""
|
||||
let html = `<!doctype html><html lang="${escape(options.lang ?? "en")}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(options.title ?? "")}</title></head><body style="margin:0;padding:0;background:#f6f6f3">${hidden}<table role="presentation" width="100%" style="border-collapse:collapse"><tr><td align="center" style="padding:24px 12px"><table role="presentation" width="100%" style="max-width:560px;border-collapse:collapse;background:#ffffff;border-radius:8px"><tr><td style="padding:28px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:15px;line-height:1.55;color:#1c1c1a">${body}${small}</td></tr></table></td></tr></table></body></html>`
|
||||
let plain = content.text
|
||||
return { html, text: footer != "" ? `${plain}\n\n--\n${footer}\n` : `${plain}\n` }
|
||||
}
|
||||
3
email/tests/Broken.weft
Normal file
3
email/tests/Broken.weft
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
let missing: string? = null
|
||||
---
|
||||
<Text>{missing!}</Text>
|
||||
7
email/tests/Escapes.weft
Normal file
7
email/tests/Escapes.weft
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import A from "../components/A"
|
||||
import P from "../components/P"
|
||||
prop text: string
|
||||
prop url: string
|
||||
---
|
||||
<P>{text}</P>
|
||||
<P><A href={url}>go</A></P>
|
||||
21
email/tests/Everything.weft
Normal file
21
email/tests/Everything.weft
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import A from "../components/A"
|
||||
import Button from "../components/Button"
|
||||
import Em from "../components/Em"
|
||||
import Facts from "../components/Facts"
|
||||
import H1 from "../components/H1"
|
||||
import Hr from "../components/Hr"
|
||||
import Img from "../components/Img"
|
||||
import Ol from "../components/Ol"
|
||||
import P from "../components/P"
|
||||
import Strong from "../components/Strong"
|
||||
import Ul from "../components/Ul"
|
||||
---
|
||||
<H1>Thank you</H1>
|
||||
<P>Hi <Strong>Ana</Strong>, see <A href="https://x.dev/t">your ticket</A>.</P>
|
||||
<Ul items={["One", "Two"]} />
|
||||
<Ol items={["First", "Second"]} />
|
||||
<Hr />
|
||||
<Facts rows={[["Total", "19,99 €"], ["Date", "1. 12."]]} />
|
||||
<Button url="https://x.dev/pay" label="Pay" />
|
||||
<Img src="https://x.dev/a.png" alt="Logo" />
|
||||
<P><Em>small</Em></P>
|
||||
5
email/tests/Mailto.weft
Normal file
5
email/tests/Mailto.weft
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import A from "../components/A"
|
||||
import P from "../components/P"
|
||||
---
|
||||
<P><A href="mailto:a@b.co">write to us</A></P>
|
||||
<P><A href="https://x.dev">https://x.dev</A></P>
|
||||
8
email/tests/Unsafe.weft
Normal file
8
email/tests/Unsafe.weft
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import A from "../components/A"
|
||||
import Button from "../components/Button"
|
||||
import Img from "../components/Img"
|
||||
import P from "../components/P"
|
||||
---
|
||||
<P><A href="javascript:alert(1)">click</A></P>
|
||||
<Button url="javascript:alert(1)" label="press" />
|
||||
<Img src="javascript:x" alt="a cat" />
|
||||
451
email/tests/email.test.weft
Normal file
451
email/tests/email.test.weft
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
// `weft test tests/email.test.weft`: messages, MIME, the providers' payloads and templates. packages/integration/email sends
|
||||
// through both providers' APIs against a scripted server, and checks the MIME with Python's parser.
|
||||
import { assert, assertEq, assertPanics, mount } from "std/testing"
|
||||
import { stringify } from "std/json"
|
||||
import { allowlist, clearOutbox, isValidEmail, memory, outbox, send, validate } from "../email"
|
||||
import type { EmailError, Message } from "../email"
|
||||
import { encodeHeader, formatAddress, quotedPrintable, toMime } from "../mime"
|
||||
import * as postmark from "../postmark"
|
||||
import * as resend from "../resend"
|
||||
import { render } from "std/app"
|
||||
import { document } from "../template"
|
||||
import Broken from "./Broken"
|
||||
import Escapes from "./Escapes"
|
||||
import Everything from "./Everything"
|
||||
import Mailto from "./Mailto"
|
||||
import Unsafe from "./Unsafe"
|
||||
|
||||
fn message(): Message {
|
||||
return { from: "info@example.com", to: ["ana@example.com"], subject: "Hello", text: "Hi" }
|
||||
}
|
||||
|
||||
fn edit(change: (mut m: Message) => void): Message {
|
||||
let mut m = message()
|
||||
change(&m)
|
||||
return m
|
||||
}
|
||||
|
||||
fn problem(m: Message): string {
|
||||
let _, err = try validate(m)
|
||||
return match err {
|
||||
InvalidMessage { field } => field,
|
||||
null => "valid",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
// ---- validation ----
|
||||
test "a good message is valid" {
|
||||
assertEq(problem(message()), "valid")
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.to = [{ email: "ana@example.com", name: "Ana Novak" }]
|
||||
m.html = "<p>Hi</p>"
|
||||
}),
|
||||
),
|
||||
"valid",
|
||||
)
|
||||
}
|
||||
|
||||
test "addresses" {
|
||||
for good of ["a@b.co", "first.last+tag@sub.example.com", "čebela@example.si"] {
|
||||
assert(isValidEmail(good), good)
|
||||
}
|
||||
for bad of [
|
||||
"",
|
||||
"a",
|
||||
"a@",
|
||||
"@b.co",
|
||||
"a@@b.co",
|
||||
"a b@c.co",
|
||||
"a@b..co",
|
||||
"a@.b.co",
|
||||
"a@b.co.",
|
||||
"a<b@c.co",
|
||||
"a,b@c.co",
|
||||
"a@b.co\r\nBcc: x@y.z",
|
||||
] {
|
||||
assert(!isValidEmail(bad), bad)
|
||||
}
|
||||
}
|
||||
|
||||
test "what a message can't be sent without" {
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.to = []
|
||||
}),
|
||||
),
|
||||
"to",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.subject = " "
|
||||
}),
|
||||
),
|
||||
"subject",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.text = ""
|
||||
}),
|
||||
),
|
||||
"html",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.from = "nobody"
|
||||
}),
|
||||
),
|
||||
"from",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.to = ["nobody"]
|
||||
}),
|
||||
),
|
||||
"to",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.cc = ["nobody"]
|
||||
}),
|
||||
),
|
||||
"cc",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.bcc = ["nobody"]
|
||||
}),
|
||||
),
|
||||
"bcc",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.replyTo = "nobody"
|
||||
}),
|
||||
),
|
||||
"replyTo",
|
||||
)
|
||||
}
|
||||
|
||||
test "header injection is refused" {
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.subject = "Hi\r\nBcc: victim@example.com"
|
||||
}),
|
||||
),
|
||||
"subject",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.subject = "Hi\nBcc: victim@example.com"
|
||||
}),
|
||||
),
|
||||
"subject",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.from = { email: "a@b.co", name: "A\r\nBcc: v@x.y" }
|
||||
}),
|
||||
),
|
||||
"from",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.to = [{ email: "a@b.co", name: "A\nX: y" }]
|
||||
}),
|
||||
),
|
||||
"to",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.headers = [["X-Tag", "a\r\nBcc: v@x.y"]]
|
||||
}),
|
||||
),
|
||||
"headers",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.headers = [["Bad Name", "a"]]
|
||||
}),
|
||||
),
|
||||
"headers",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.headers = [["X:Y", "a"]]
|
||||
}),
|
||||
),
|
||||
"headers",
|
||||
)
|
||||
assertEq(
|
||||
problem(
|
||||
edit((mut m) => {
|
||||
m.attachments = [{ filename: "a\r\nb.txt", content: Bytes.of([1]) }]
|
||||
}),
|
||||
),
|
||||
"attachments",
|
||||
)
|
||||
}
|
||||
|
||||
// ---- sending ----
|
||||
test "send validates, then hands the message to the transport" {
|
||||
clearOutbox()
|
||||
let sent = try await send(memory(), message())
|
||||
assertEq(sent.provider, "memory")
|
||||
assertEq(outbox().length, 1)
|
||||
let _, err = try await send(
|
||||
memory(),
|
||||
edit((mut m) => {
|
||||
m.to = []
|
||||
}),
|
||||
)
|
||||
assert(err != null)
|
||||
assertEq(outbox().length, 1)
|
||||
}
|
||||
|
||||
test "an allowlist keeps other recipients from being sent to" {
|
||||
clearOutbox()
|
||||
let staging = allowlist(memory(), ["info@vidni.si"])
|
||||
let skipped = try await send(staging, message())
|
||||
assert(skipped.skipped)
|
||||
assertEq(outbox().length, 0)
|
||||
let sent = try await send(
|
||||
staging,
|
||||
edit((mut m) => {
|
||||
m.to = ["INFO@vidni.si "]
|
||||
}),
|
||||
) else null
|
||||
assert(sent == null, "an address with a space is invalid")
|
||||
let allowed = try await send(
|
||||
staging,
|
||||
edit((mut m) => {
|
||||
m.to = ["INFO@vidni.si"]
|
||||
}),
|
||||
)
|
||||
assert(!allowed.skipped)
|
||||
assertEq(outbox().length, 1)
|
||||
// One recipient outside the list keeps the whole message back.
|
||||
let mixed = try await send(
|
||||
staging,
|
||||
edit((mut m) => {
|
||||
m.to = ["info@vidni.si"]
|
||||
m.cc = ["ana@example.com"]
|
||||
}),
|
||||
)
|
||||
assert(mixed.skipped)
|
||||
let open = try await send(allowlist(memory(), ["*"]), message())
|
||||
assert(!open.skipped)
|
||||
}
|
||||
|
||||
// ---- MIME ----
|
||||
test "headers stay ASCII" {
|
||||
assertEq(encodeHeader("Hello"), "Hello")
|
||||
assertEq(encodeHeader("Račun št. 5"), "=?UTF-8?B?UmHEjXVuIMWhdC4gNQ==?=")
|
||||
// A long subject is split between characters, each encoded word at most 75 characters long.
|
||||
for word of encodeHeader("č".repeat(100)).split("\r\n ") {
|
||||
assert(word.length <= 75, word)
|
||||
}
|
||||
assertEq(formatAddress("a@b.co"), "a@b.co")
|
||||
assertEq(
|
||||
formatAddress({ email: "a@b.co", name: "Ana \"N\" Novak" }),
|
||||
"\"Ana \\\"N\\\" Novak\" <a@b.co>",
|
||||
)
|
||||
assertEq(formatAddress({ email: "a@b.co", name: "Žiga" }), "=?UTF-8?B?xb1pZ2E=?= <a@b.co>")
|
||||
}
|
||||
|
||||
test "quoted-printable" {
|
||||
assertEq(quotedPrintable("a=b"), "a=3Db")
|
||||
assertEq(quotedPrintable("č"), "=C4=8D")
|
||||
assertEq(quotedPrintable("line one\nline two"), "line one\r\nline two")
|
||||
assertEq(quotedPrintable("trailing space "), "trailing space=20")
|
||||
for line of quotedPrintable("x".repeat(500)).split("\r\n") {
|
||||
assert(line.length <= 76, line)
|
||||
}
|
||||
// A multi-byte character isn't split across a soft line break.
|
||||
for line of quotedPrintable("č".repeat(100)).split("\r\n") {
|
||||
assert(line.length <= 76 && !line.replace("=", "").endsWith("C4="), line)
|
||||
}
|
||||
}
|
||||
|
||||
test "a text message" {
|
||||
let mime = toMime(message(), { id: "fixed", date: "Tue, 17 Nov 2026 10:00:00 +0000" })
|
||||
assertEq(
|
||||
mime,
|
||||
"From: info@example.com\r\nTo: ana@example.com\r\nSubject: Hello\r\nDate: Tue, 17 Nov 2026 10:00:00 +0000\r\nMessage-ID: <fixed@example.com>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nHi\r\n",
|
||||
)
|
||||
}
|
||||
|
||||
test "html and text, attachments and inline images nest in the right order" {
|
||||
let mime = toMime(
|
||||
edit((mut m) => {
|
||||
m.html = "<p>Hi</p><img src=\"cid:logo\">"
|
||||
m.attachments = [
|
||||
{ filename: "racun.pdf", content: Bytes.of([1, 2, 3]), type: "application/pdf" },
|
||||
{ filename: "logo.png", content: Bytes.of([4]), type: "image/png", contentId: "logo" },
|
||||
]
|
||||
}),
|
||||
{ id: "x" },
|
||||
)
|
||||
assert(mime.includes("multipart/mixed"))
|
||||
assert(mime.indexOf("multipart/mixed") < mime.indexOf("multipart/related"))
|
||||
assert(mime.indexOf("multipart/related") < mime.indexOf("multipart/alternative"))
|
||||
assert(mime.includes("Content-Disposition: attachment; filename=\"racun.pdf\""))
|
||||
assert(mime.includes("Content-Disposition: inline; filename=\"logo.png\"\r\nContent-ID: <logo>"))
|
||||
assert(mime.includes("\r\n\r\nAQID\r\n"))
|
||||
}
|
||||
|
||||
test "bcc is never written, and every line ends in CRLF" {
|
||||
let mime = toMime(
|
||||
edit((mut m) => {
|
||||
m.bcc = ["secret@example.com"]
|
||||
m.html = "<p>a\nb</p>"
|
||||
}),
|
||||
{ id: "x" },
|
||||
)
|
||||
assert(!mime.includes("secret@example.com"))
|
||||
assert(!mime.replaceAll("\r\n", "").includes("\n"))
|
||||
}
|
||||
|
||||
test "a file name outside ASCII" {
|
||||
let mime = toMime(
|
||||
edit((mut m) => {
|
||||
m.attachments = [{ filename: "račun.pdf", content: Bytes.of([1]) }]
|
||||
}),
|
||||
{ id: "x" },
|
||||
)
|
||||
assert(mime.includes("filename*=UTF-8''ra%C4%8Dun.pdf"))
|
||||
}
|
||||
|
||||
// ---- the providers ----
|
||||
fn full(): Message {
|
||||
return {
|
||||
from: { email: "info@example.com", name: "Vidni" },
|
||||
to: ["ana@example.com", { email: "bor@example.com", name: "Bor" }],
|
||||
cc: ["c@example.com"],
|
||||
bcc: ["d@example.com"],
|
||||
replyTo: "owner@example.com",
|
||||
subject: "Račun",
|
||||
html: "<p>Hi</p>",
|
||||
text: "Hi",
|
||||
headers: [["List-Unsubscribe", "<https://example.com/u>"]],
|
||||
attachments: [
|
||||
{
|
||||
filename: "a.ics",
|
||||
content: Bytes.fromUtf8("BEGIN"),
|
||||
type: "text/calendar",
|
||||
contentId: "cal",
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
test "Resend's payload" {
|
||||
assertEq(
|
||||
stringify(resend.payload(full())),
|
||||
"{\"from\":\"\\\"Vidni\\\" <info@example.com>\",\"to\":[\"ana@example.com\",\"\\\"Bor\\\" <bor@example.com>\"],\"subject\":\"Račun\",\"cc\":[\"c@example.com\"],\"bcc\":[\"d@example.com\"],\"reply_to\":\"owner@example.com\",\"html\":\"<p>Hi</p>\",\"text\":\"Hi\",\"headers\":{\"List-Unsubscribe\":\"<https://example.com/u>\"},\"attachments\":[{\"filename\":\"a.ics\",\"content\":\"QkVHSU4=\",\"content_type\":\"text/calendar\",\"content_id\":\"cal\"}]}",
|
||||
)
|
||||
assertEq(
|
||||
stringify(resend.payload(message())),
|
||||
"{\"from\":\"info@example.com\",\"to\":[\"ana@example.com\"],\"subject\":\"Hello\",\"text\":\"Hi\"}",
|
||||
)
|
||||
}
|
||||
|
||||
test "Postmark's payload" {
|
||||
assertEq(
|
||||
stringify(postmark.payload(full(), "broadcast")),
|
||||
"{\"From\":\"\\\"Vidni\\\" <info@example.com>\",\"To\":\"ana@example.com, \\\"Bor\\\" <bor@example.com>\",\"Subject\":\"Račun\",\"MessageStream\":\"broadcast\",\"Cc\":\"c@example.com\",\"Bcc\":\"d@example.com\",\"ReplyTo\":\"owner@example.com\",\"HtmlBody\":\"<p>Hi</p>\",\"TextBody\":\"Hi\",\"Headers\":[{\"Name\":\"List-Unsubscribe\",\"Value\":\"<https://example.com/u>\"}],\"Attachments\":[{\"Name\":\"a.ics\",\"Content\":\"QkVHSU4=\",\"ContentType\":\"text/calendar\",\"ContentID\":\"cid:cal\"}]}",
|
||||
)
|
||||
}
|
||||
|
||||
fn kind(e: EmailError): string {
|
||||
return e.kind
|
||||
}
|
||||
|
||||
test "providers' errors" {
|
||||
assertEq(kind(resend.failureOf(422, null, null)), "Rejected")
|
||||
assertEq(kind(resend.failureOf(401, null, null)), "Rejected")
|
||||
assertEq(kind(resend.failureOf(500, null, null)), "ProviderFailure")
|
||||
assertEq(
|
||||
resend.failureOf(429, null, "30"),
|
||||
RateLimited { message: "Resend answered 429", retryAfter: 30 },
|
||||
)
|
||||
assertEq(kind(postmark.failureOf(422, null)), "Rejected")
|
||||
assertEq(kind(postmark.failureOf(429, null)), "RateLimited")
|
||||
assertEq(kind(postmark.failureOf(503, null)), "ProviderFailure")
|
||||
}
|
||||
|
||||
// ---- templates ----
|
||||
test "everything shown in a template is escaped" {
|
||||
let r = render(Escapes, { text: "<script>alert(1)</script> & co", url: "https://x.dev/?a=1&b=2" })
|
||||
assert(!r.html.includes("<script>"))
|
||||
assert(r.html.includes("<script>alert(1)</script> & co"))
|
||||
assert(r.html.includes("href=\"https://x.dev/?a=1&b=2\""))
|
||||
}
|
||||
|
||||
test "unsafe links and images lose their address" {
|
||||
let r = render(Unsafe)
|
||||
assert(!r.html.includes("javascript:"))
|
||||
assert(r.html.includes("click") && r.html.includes("press") && r.html.includes("a cat"))
|
||||
assert(!r.text.includes("javascript:"))
|
||||
}
|
||||
|
||||
test "the text version reads like a person wrote it" {
|
||||
assertEq(
|
||||
render(Everything).text,
|
||||
"Thank you\n\nHi Ana, see your ticket (https://x.dev/t).\n\n- One\n- Two\n\n1. First\n2. Second\n\n---\n\nTotal: 19,99 €\nDate: 1. 12.\n\nPay (https://x.dev/pay)\n\nLogo\n\nsmall",
|
||||
)
|
||||
}
|
||||
|
||||
test "a mailto link's text doesn't repeat the address" {
|
||||
assertEq(render(Mailto).text, "write to us (a@b.co)\n\nhttps://x.dev")
|
||||
}
|
||||
|
||||
test "styles are inline, in forms mail clients read" {
|
||||
let html = render(Everything).html
|
||||
assert(html.includes("font-weight:700"))
|
||||
assert(html.includes("margin-bottom:16px"))
|
||||
assert(html.includes("#111111"))
|
||||
assert(html.includes("alt=\"Logo\""))
|
||||
for missing of ["class=", "var(", "oklch(", "rem", "<!--"] {
|
||||
assert(!html.includes(missing), missing)
|
||||
}
|
||||
}
|
||||
|
||||
test "rendering leaves what is mounted alone" {
|
||||
let view = mount(Mailto)
|
||||
let before = view.text()
|
||||
render(Everything)
|
||||
assertEq(view.text(), before)
|
||||
}
|
||||
|
||||
test "a panic while rendering is the caller's" {
|
||||
assertPanics(() => render(Broken), "TypeError")
|
||||
}
|
||||
|
||||
test "a whole document" {
|
||||
let r = document(
|
||||
render(Mailto),
|
||||
{ title: "Receipt <1>", preheader: "Thanks", footer: "Vidni d.o.o.", lang: "sl" },
|
||||
)
|
||||
assert(r.html.startsWith("<!doctype html><html lang=\"sl\">"))
|
||||
assert(r.html.includes("<title>Receipt <1></title>"))
|
||||
assert(r.html.includes("Thanks") && r.html.includes("Vidni d.o.o."))
|
||||
assertEq(r.text, "write to us (a@b.co)\n\nhttps://x.dev\n\n--\nVidni d.o.o.\n")
|
||||
}
|
||||
11
email/weft.toml
Normal file
11
email/weft.toml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
[package]
|
||||
name = "weft/email"
|
||||
version = "0.1.0"
|
||||
description = "Email for Weft: Resend and Postmark, MIME messages with attachments, and templates rendered to HTML and text"
|
||||
license = "MIT OR Apache-2.0"
|
||||
# A placeholder until the public repository exists (packages/README.md, Publishing for real).
|
||||
repository = "https://git.weft-lang.dev/weft/packages"
|
||||
hosts = ["api.resend.com", "api.postmarkapp.com"]
|
||||
exports = ["email", "mime", "resend", "postmark", "template", "components"]
|
||||
main = "email"
|
||||
include = ["*.weft", "components", "README.md"]
|
||||
Loading…
Reference in a new issue