# Handle bounces

A bounce is a recipient's server sending your message back. Some mean the address is dead, and writing to it again hurts your sender's standing. Others clear up alone.

## What Mailset already does

- An address at a domain that takes no email (`ana@gmial.com`) is refused when you send, before it can bounce: `invalid_input` with `refusal: "recipient"`.
- After a hard bounce that says the mailbox or the domain doesn't exist, Mailset stops sending your product's email to that address, with the same refusal.
- A bounce or a skip never needs a retry from you.

So your job is small: tell the person, and stop asking for that address.

## Read the event

Each bounce arrives as a `bounced` event on your [webhook](https://mailset.app/docs/webhooks), with `bounce.kind` and `bounce.class`.

| `kind` | `class`             | What it means                     | What to do                      |
| ------ | ------------------- | --------------------------------- | ------------------------------- |
| `hard` | `mailbox`, `domain` | The address can't get email       | Mark it bad and ask for another |
| `hard` | `suppressed`        | It bounced or complained before   | The same                        |
| `hard` | `policy`            | The receiver refused this message | Keep the address, read `reason` |
| `soft` | `full`              | The inbox is full                 | Nothing: it may clear           |
| `soft` | `too_large`         | The message is too big for them   | Send a smaller one              |
| any    | `other`             | Anything else                     | Log `reason`                    |

```typescript
// What a bounce says when the address can't get mail.
const dead = ['mailbox', 'domain', 'suppressed'];

export async function POST(request: Request) {
	const events = await webhooks.verify({
		body: await request.text(),
		headers: request.headers,
		secret: process.env.MAILSET_HOOK_SECRET ?? '',
	});
	for (const event of events) {
		if (event.type !== 'bounced') continue;
		if (event.bounce.kind !== 'hard') continue;
		if (dead.includes(event.bounce.class))
			await markAddressBad(event.recipient);
	}
	return new Response(null, { status: 204 });
}
```

```python
# What a bounce says when the address can't get mail.
DEAD = {"mailbox", "domain", "suppressed"}


def handle(
    body: bytes, headers: Mapping[str, str]
) -> int:
    events = webhooks.verify(body, headers, SECRET)
    for event in events:
        if event["type"] != "bounced":
            continue
        bounce = event["bounce"]
        if bounce["kind"] != "hard":
            continue
        if bounce["class"] in DEAD:
            mark_address_bad(event["recipient"])
    return 204
```

```go
import (
	"io"
	"log"
	"net/http"
	"os"

	mailset "mailset.app/go"
)

// What a bounce says when the address can't get mail.
var dead = map[mailset.BounceClass]bool{
	mailset.BounceMailbox:    true,
	mailset.BounceDomain:     true,
	mailset.BounceSuppressed: true,
}

func hook(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "unreadable", http.StatusBadRequest)
		return
	}
	secret := os.Getenv("MAILSET_HOOK_SECRET")
	events, err := mailset.VerifyWebhookHeader(
		body, r.Header, secret,
	)
	if err != nil {
		http.Error(w, "unsigned", http.StatusUnauthorized)
		return
	}
	for _, event := range events {
		if event.Type != mailset.EventBounced {
			continue
		}
		if event.Bounce.Kind != mailset.BounceHard {
			continue
		}
		if dead[event.Bounce.Class] {
			markAddressBad(event.Recipient)
		}
	}
	w.WriteHeader(http.StatusNoContent)
}
```

```ruby
# What a bounce says when the address can't get mail.
DEAD = %w[mailbox domain suppressed].freeze

class MailsetEventsController < ApplicationController
  skip_forgery_protection

  def create
    events = Mailset::Webhooks.verify(
      body: request.raw_post,
      headers: request.headers,
      secret: ENV.fetch('MAILSET_HOOK_SECRET')
    )
    events.each do |event|
      next unless event.type == 'bounced'
      next unless event.bounce.kind == 'hard'
      next unless DEAD.include?(event.bounce.class)

      Addresses.mark_bad(event.recipient)
    end
    head :no_content
  end
end
```

```php
use Mailset\Events\BouncedEvent;
use Mailset\Webhooks;

// What a bounce says when the address can't get mail.
$dead = ['mailbox', 'domain', 'suppressed'];

$events = Webhooks::verify(
    (string) file_get_contents('php://input'),
    getallheaders(),
    (string) getenv('MAILSET_HOOK_SECRET'),
);
foreach ($events as $event) {
    if (!$event instanceof BouncedEvent) {
        continue;
    }
    if ($event->bounce->kind !== 'hard') {
        continue;
    }
    if (in_array($event->bounce->class, $dead, true)) {
        markAddressBad($event->recipient);
    }
}
http_response_code(204);
```

```java
// What a bounce says when the address can't get mail.
static final Set<String> DEAD =
        Set.of("mailbox", "domain", "suppressed");

// Your hook's endpoint calls it with the raw body.
public static int events(byte[] body, String signature) {
    List<MailEvent> events =
            Webhooks.verify(body, signature, secret);
    for (MailEvent event : events) {
        if (!(event instanceof MailEvent.Bounced b))
            continue;
        if (!b.bounce().kind().equals("hard")) continue;
        if (DEAD.contains(b.bounce().bounceClass()))
            markAddressBad(b.recipient());
    }
    return 204;
}
```

```rust
// What a bounce says when the address can't get mail.
const DEAD: [BounceClass; 3] = [
    BounceClass::Mailbox,
    BounceClass::Domain,
    BounceClass::Suppressed,
];

pub async fn mailset_hook(
    headers: HeaderMap,
    body: Bytes,
) -> StatusCode {
    let secret = std::env::var("MAILSET_HOOK_SECRET");
    let secret = secret.unwrap_or_default();
    let verified =
        webhooks::verify(&body, &headers, &secret);
    let Ok(events) = verified else {
        return StatusCode::UNAUTHORIZED;
    };
    for event in events {
        let Event::Bounced(bounced) = event else {
            continue;
        };
        let bounce = &bounced.bounce;
        if bounce.kind != BounceKind::Hard {
            continue;
        }
        if DEAD.contains(&bounce.class) {
            mark_address_bad(&bounced.recipient).await;
        }
    }
    StatusCode::NO_CONTENT
}
```

## Catch the refusal when you send

An address you already know is bad is refused at once, with no event to wait for.

```typescript
const message = { from, to: user.email, subject, text };
try {
	await mailset.send(message);
} catch (error) {
	if (!(error instanceof MailsetError)) throw error;
	if (error.refusal !== 'recipient') throw error;
	await askForAnotherAddress(user);
}
```

```python
message: SendInput = {
    "from": sender,
    "to": user["email"],
    "subject": subject,
    "text": text,
}
try:
    mailset.send(message)
except MailsetError as error:
    if error.refusal != "recipient":
        raise
    ask_for_another_address(user)
```

```go
import (
	"context"
	"errors"
	"log"

	mailset "mailset.app/go"
)

message := mailset.Message{
	From:    from,
	To:      []string{user.Email},
	Subject: subject,
	Text:    text,
}
_, err := client.Send(ctx, message)
var refused *mailset.Error
if !errors.As(err, &refused) {
	return err // sent, or Mailset out of reach
}
if refused.Refusal != "recipient" {
	return err
}
return askForAnotherAddress(user)
```

```ruby
begin
  mailset.send_email(
    from: from, to: user[:email],
    subject: subject, text: text
  )
rescue Mailset::Error => e
  raise unless e.refusal == 'recipient'

  ask_for_another_address(user)
end
```

```php
$message = [
    'from' => $from,
    'to' => $user['email'],
    'subject' => $subject,
    'text' => $text,
];
try {
    $mailset->send($message);
} catch (MailsetException $error) {
    if ($error->refusal !== 'recipient') {
        throw $error;
    }
    askForAnotherAddress($user);
}
```

```java
Message message = Message.builder()
        .from(from)
        .to(user.email())
        .subject(subject)
        .text(text)
        .build();
try {
    mailset.send(message);
} catch (MailsetException error) {
    if (!"recipient".equals(error.getRefusal()))
        throw error;
    askForAnotherAddress(user);
}
```

```rust
let message = Message::builder()
    .from(FROM)
    .to(user.email)
    .subject(SUBJECT)
    .text(TEXT);
if let Err(error) = mailset.send(message).await {
    if error.refusal() != Some("recipient") {
        return Err(error);
    }
    ask_for_another_address(&user).await;
}
```

## Watch out

- A typo at sign-up is the usual cause. Confirm a new address before you send it anything else.
- Never retry a hard bounce. When bounces run high, Mailset pauses the key that sent them: `mailset guide brakes`.
- No webhook? `mailset delivery search --status bounced` finds them, and the SDK's `delivery.search()` runs the same search for a key's own mailbox, or for the addresses a domain key sends as.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content