Docs
Handle bounces
Tell a dead address from a full inbox, and keep your list clean.
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 (
moc.laimg@ana) is refused when you send, before it can bounce:invalid_inputwithrefusal: "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, 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 |
// 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 });
}
# 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
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,
}
# 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
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);
// 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;
}
// 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;
};
Catch the refusal when you send
An address you already know is bad is refused at once, with no event to wait for.
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);
}
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)
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)
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
$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);
}
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);
}
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 bouncedfinds them, and the SDK'sdelivery.search()runs the same search for a key's own mailbox, or for the addresses a domain key sends as.