# Send your own MIME

The sending commands take a whole email that you built: `data` in `messages.submit` and `messages.submitMany`, `raw` in `campaigns.submit`. The SDK builds it for you from `from`, `to`, `subject`, `text` and `html`, so with an SDK you can skip this page. A client without one builds the message itself.

## What a whole message is

Header lines, an empty line, then the body, with every line ending in CRLF. That is RFC 5322, and your language's mail library writes it. A message with a text and an HTML version, or with files, is a MIME message, which the same library writes too.

```text
From: Acme <hello@example.com>
To: ana@example.org
Subject: Your Acme code
Message-ID: <3f9a1c0e7b2d4a58@example.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8

Your code is 123456.
```

## Encode it

Write the message's bytes as standard base64 on one line: `+` and `/`, with padding, and no line breaks. Base64url is refused.

A message can be 20 MB before base64. `messages.submitMany` takes up to 100 messages and 48 MB in one request: see [Send many messages at once](https://mailset.app/docs/recipes/batches).

## Headers Mailset reads

- `From` names one address: the mailbox your key sends as or one of its aliases, or for a domain key one of the addresses it names. A `Sender` header has to match it.
- `To`, `Cc` and `Bcc` say who gets it. There has to be at least one address among them, and at most 100 in each. Mailset takes `Bcc` out before the message leaves.
- `Message-ID` is kept when you set one, and Mailset adds one when you don't. Sending the same one again from the same mailbox (or a domain key's domain) answers the first receipt and sends nothing twice: see [Retry without sending twice](https://mailset.app/docs/recipes/retries).
- `Date` is added when you leave it out.
- The unsubscribe headers are yours to set on promotional email, or Mailset's to add: see [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes).

## Headers Mailset refuses

- Two of `From`, `Sender`, `To`, `Cc`, `Bcc`, `Subject`, `Date`, `Message-ID`, `In-Reply-To` or `References`. A message has one of each.
- A `From` with no address, or with more than one.
- An unsubscribe header or `Precedence: bulk` on a message sent with `mode` set to `transactional`.

`Return-Path` and any `Resent-` header are removed, since Mailset sets where bounces go.

A refused message answers `invalid_input` with a sentence saying which header is wrong.

## Build one with the SDK

The SDK can hand you the message its own send would make, without sending it. Use it for a queue of your own, or to submit from another service.

```typescript
import { messageOf } from 'mailset';

const { raw, messageId } = messageOf({
	from: 'Acme <hello@example.com>',
	to: 'ana@example.org',
	subject: 'Your Acme code',
	text: 'Your code is 123456.',
});

// The `data` that messages.submit takes.
const data = Buffer.from(raw).toString('base64');

console.log(messageId, data.length);
```

```python
import base64

from mailset import build_message

built = build_message(
    {
        "from": "Acme <hello@example.com>",
        "to": "ana@example.org",
        "subject": "Your Acme code",
        "text": "Your code is 123456.",
    }
)

# The `data` that messages.submit takes.
data = base64.b64encode(built["raw"]).decode()

print(built["message_id"], len(data))
```

```go
import (
	"encoding/base64"
	"fmt"
	"log"

	mailset "mailset.app/go"
)

message := mailset.Message{
	From:    "Acme <hello@example.com>",
	To:      []string{"ana@example.org"},
	Subject: "Your Acme code",
	Text:    "Your code is 123456.",
}
raw, messageID, err := mailset.BuildMessage(message)
if err != nil {
	log.Fatal(err)
}

// The data that messages.submit takes.
data := base64.StdEncoding.EncodeToString(raw)

fmt.Println(messageID, len(data))
```

```ruby
require 'mailset'

message = Mailset.build_message(
  from: 'Acme <hello@example.com>',
  to: 'ana@example.org',
  subject: 'Your Acme code',
  text: 'Your code is 123456.'
)

# The `data` that messages.submit takes.
data = message.base64

puts message.message_id, data.length
```

```php
<?php

require 'vendor/autoload.php';

$message = Mailset\Message::build([
    'from' => 'Acme <hello@example.com>',
    'to' => 'ana@example.org',
    'subject' => 'Your Acme code',
    'text' => 'Your code is 123456.',
]);

// The `data` that messages.submit takes.
$data = base64_encode($message->raw);

echo $message->messageId, ' ', strlen($data), PHP_EOL;
```

```java
import app.mailset.Message;
import app.mailset.RawMessage;

RawMessage raw = Message.builder()
        .from("Acme <hello@example.com>")
        .to("ana@example.org")
        .subject("Your Acme code")
        .text("Your code is 123456.")
        .build()
        .toRaw();

// The data that messages.submit takes.
String data = raw.base64();

System.out.println(raw.messageId());
System.out.println(data.length());
```

```rust
use base64::engine::general_purpose::STANDARD;
use base64::Engine;

let message = mailset::Message::builder()
    .from("Acme <hello@example.com>")
    .to("ana@example.org")
    .subject("Your Acme code")
    .text("Your code is 123456.")
    .build();
let mime = message.to_mime()?;

// The `data` that messages.submit takes.
let data = STANDARD.encode(&mime.raw);

println!("{} {}", mime.message_id, data.len());
```

## Build one without an SDK

Each of these builds a message with a text and an HTML part and sends it with `messages.submitMany`. They lean on `run`, the signed call from [Calling the API without an SDK](https://mailset.app/docs/authentication/http#a-client-in-your-language), and are files Mailset's own tests run.

```python
def build_message(sender: str, recipient: str, subject: str) -> bytes:
    """A whole RFC 5322 message, text and HTML, as bytes with CRLF line ends."""
    message = EmailMessage(policy=SMTP)
    message["From"] = sender
    message["To"] = recipient
    message["Subject"] = subject
    message["Date"] = formatdate()
    # Keep the Message-ID. Sending the same one again answers the first
    # receipt and sends nothing twice, so a retry is safe.
    message["Message-ID"] = make_msgid(domain=parseaddr(sender)[1].split("@")[1])
    message.set_content("Your code is 123456.\n")
    message.add_alternative("<p>Your code is <b>123456</b>.</p>\n", subtype="html")
    return message.as_bytes()


def send(raw: bytes, key: dict) -> list:
    """Submits whole messages, up to 100 a call. One result per message, in order."""
    answer = run(
        "messages.submitMany",
        {
            "messages": [
                # Standard base64, on one line. transactional: a product's own
                # mail, such as a sign-in code or a receipt. No copy in Sent.
                {"data": base64.b64encode(raw).decode(), "transactional": True}
            ]
        },
        key,
    )
    if not answer.get("ok"):
        # The whole call was refused: the key, the signature or the input.
        raise RuntimeError(json.dumps(answer["error"]))
    return answer["data"]["results"]
```

```go
// buildMessage writes a whole RFC 5322 message, text and HTML, with CRLF
// line ends.
func buildMessage(from, to, subject string) ([]byte, error) {
	sender, err := mail.ParseAddress(from)
	if err != nil {
		return nil, err
	}
	_, domain, _ := strings.Cut(sender.Address, "@")
	id := make([]byte, 16)
	rand.Read(id)

	var body bytes.Buffer
	parts := multipart.NewWriter(&body)
	for _, part := range [][2]string{
		{"text/plain", "Your code is 123456.\n"},
		{"text/html", "<p>Your code is <b>123456</b>.</p>\n"},
	} {
		header := textproto.MIMEHeader{}
		header.Set("Content-Type", part[0]+"; charset=utf-8")
		header.Set("Content-Transfer-Encoding", "quoted-printable")
		writer, err := parts.CreatePart(header)
		if err != nil {
			return nil, err
		}
		encoded := quotedprintable.NewWriter(writer)
		encoded.Write([]byte(part[1]))
		encoded.Close()
	}
	parts.Close()

	var message bytes.Buffer
	for _, line := range []string{
		"From: " + from,
		"To: " + to,
		// QEncoding leaves plain ASCII alone and encodes the rest (RFC 2047).
		"Subject: " + mime.QEncoding.Encode("utf-8", subject),
		"Date: " + time.Now().Format(time.RFC1123Z),
		// Keep the Message-ID. Sending the same one again answers the first
		// receipt and sends nothing twice, so a retry is safe.
		"Message-ID: <" + hex.EncodeToString(id) + "@" + domain + ">",
		"MIME-Version: 1.0",
		"Content-Type: multipart/alternative; boundary=" + parts.Boundary(),
		"",
	} {
		message.WriteString(line + "\r\n")
	}
	message.Write(body.Bytes())
	return message.Bytes(), nil
}

// send submits whole messages, up to 100 a call, and returns one result per
// message, in order.
func send(raw []byte, key Key) ([]any, error) {
	answer, err := run("messages.submitMany", map[string]any{
		"messages": []map[string]any{{
			// Standard base64, on one line. transactional: a product's own
			// mail, such as a sign-in code or a receipt. No copy in Sent.
			"data":          base64.StdEncoding.EncodeToString(raw),
			"transactional": true,
		}},
	}, key)
	if err != nil {
		return nil, err
	}
	if answer["ok"] != true {
		// The whole call was refused: the key, the signature or the input.
		refusal, _ := json.Marshal(answer["error"])
		return nil, errors.New(string(refusal))
	}
	results, _ := answer["data"].(map[string]any)["results"].([]any)
	return results, nil
}
```

```ruby
# A header value in ASCII: other text becomes an RFC 2047 encoded word.
def header_text(text)
  text.ascii_only? ? text : "=?UTF-8?B?#{Base64.strict_encode64(text)}?="
end

# One body part, base64 in CRLF lines, so any text survives any mail server.
def body_part(type, text)
  [
    "Content-Type: #{type}; charset=utf-8",
    'Content-Transfer-Encoding: base64',
    '',
    Base64.encode64(text).split("\n")
  ]
end

# A whole RFC 5322 message, text and HTML, with CRLF line ends. Ruby's
# standard library has no builder for one, so this writes it out.
def build_message(from, to, subject)
  boundary = "part-#{SecureRandom.hex(12)}"
  [
    "From: #{from}",
    "To: #{to}",
    "Subject: #{header_text(subject)}",
    "Date: #{Time.now.rfc2822}",
    # Keep the Message-ID. Sending the same one again answers the first
    # receipt and sends nothing twice, so a retry is safe.
    "Message-ID: <#{SecureRandom.hex(16)}@#{from[/@([\w.-]+)/, 1]}>",
    'MIME-Version: 1.0',
    "Content-Type: multipart/alternative; boundary=\"#{boundary}\"",
    '',
    "--#{boundary}",
    body_part('text/plain', "Your code is 123456.\n"),
    "--#{boundary}",
    body_part('text/html', "<p>Your code is <b>123456</b>.</p>\n"),
    "--#{boundary}--",
    ''
  ].flatten.join("\r\n")
end

# Submits whole messages, up to 100 a call. One result per message, in order.
def send_message(raw, key)
  answer = run('messages.submitMany', {
    messages: [
      # Standard base64 on one line: strict_encode64, since encode64 adds
      # line breaks. transactional: a product's own mail, such as a sign-in
      # code or a receipt. No copy in Sent.
      { data: Base64.strict_encode64(raw), transactional: true }
    ]
  }, key)
  # Not ok: the whole call was refused. The key, the signature or the input.
  raise JSON.generate(answer['error']) unless answer['ok']

  answer['data']['results']
end
```

```php
// A whole RFC 5322 message, text and HTML, with CRLF line ends. PHP's mail()
// sends a message itself and hands none back, so this writes it out.
function buildMessage(string $from, string $to, string $subject): string
{
    // A header is ASCII: other text becomes an RFC 2047 encoded word.
    if (preg_match('/[^\x20-\x7e]/', $subject)) {
        $subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
    }
    // One body part, base64 in CRLF lines, so any text survives any mail server.
    $part = fn (string $type, string $text) => "Content-Type: $type; charset=utf-8\r\n"
        . "Content-Transfer-Encoding: base64\r\n\r\n"
        . rtrim(chunk_split(base64_encode($text)));
    $boundary = 'part-' . bin2hex(random_bytes(12));
    preg_match('/@([\w.-]+)/', $from, $domain);

    return implode("\r\n", [
        "From: $from",
        "To: $to",
        "Subject: $subject",
        'Date: ' . date(DATE_RFC2822),
        // Keep the Message-ID. Sending the same one again answers the first
        // receipt and sends nothing twice, so a retry is safe.
        'Message-ID: <' . bin2hex(random_bytes(16)) . "@$domain[1]>",
        'MIME-Version: 1.0',
        "Content-Type: multipart/alternative; boundary=\"$boundary\"",
        '',
        "--$boundary",
        $part('text/plain', "Your code is 123456.\n"),
        "--$boundary",
        $part('text/html', "<p>Your code is <b>123456</b>.</p>\n"),
        "--$boundary--",
        '',
    ]);
}

// Submits whole messages, up to 100 a call. One result per message, in order.
function send(string $raw, array $key): array
{
    $answer = run('messages.submitMany', [
        'messages' => [
            // Standard base64, on one line. transactional: a product's own
            // mail, such as a sign-in code or a receipt. No copy in Sent.
            ['data' => base64_encode($raw), 'transactional' => true],
        ],
    ], $key);
    if (!$answer['ok']) {
        // The whole call was refused: the key, the signature or the input.
        throw new RuntimeException(json_encode($answer['error']));
    }
    return $answer['data']['results'];
}
```

```java
/** A header value in ASCII: other text becomes an RFC 2047 encoded word. */
static String headerText(String text) {
    if (StandardCharsets.US_ASCII.newEncoder().canEncode(text)) return text;
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    return "=?UTF-8?B?" + Base64.getEncoder().encodeToString(bytes) + "?=";
}

/** One body part, base64 in CRLF lines, so any text survives any mail server. */
static String bodyPart(String type, String text) {
    return "Content-Type: " + type + "; charset=utf-8\r\n"
            + "Content-Transfer-Encoding: base64\r\n\r\n"
            + Base64.getMimeEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
}

/**
 * A whole RFC 5322 message, text and HTML, with CRLF line ends. The JDK
 * has no builder for one (Jakarta Mail is a separate library), so this
 * writes it out.
 */
static byte[] buildMessage(String from, String to, String subject) {
    String boundary = "part-" + UUID.randomUUID();
    String domain = from.replaceAll("^.*@([\\w.-]+).*$", "$1");
    return String.join("\r\n",
            "From: " + from,
            "To: " + to,
            "Subject: " + headerText(subject),
            "Date: " + DateTimeFormatter.RFC_1123_DATE_TIME.format(OffsetDateTime.now()),
            // Keep the Message-ID. Sending the same one again answers the
            // first receipt and sends nothing twice, so a retry is safe.
            "Message-ID: <" + UUID.randomUUID() + "@" + domain + ">",
            "MIME-Version: 1.0",
            "Content-Type: multipart/alternative; boundary=\"" + boundary + "\"",
            "",
            "--" + boundary,
            bodyPart("text/plain", "Your code is 123456.\n"),
            "--" + boundary,
            bodyPart("text/html", "<p>Your code is <b>123456</b>.</p>\n"),
            "--" + boundary + "--",
            "").getBytes(StandardCharsets.UTF_8);
}

/**
 * Submits whole messages, up to 100 a call. The answer's data.results
 * holds one result per message, in order: {"ok":true,"id",...} or
 * {"ok":false,"error":{"code","message"}}.
 */
static String send(byte[] raw, Key key) throws Exception {
    // Standard base64, on one line: getEncoder, since getMimeEncoder adds
    // line breaks. transactional: a product's own mail, such as a sign-in
    // code or a receipt. No copy in Sent.
    String data = Base64.getEncoder().encodeToString(raw);
    return run("messages.submitMany",
            "{\"messages\":[{\"data\":\"" + data + "\",\"transactional\":true}]}", key);
}
```

```rust
/// A header value in ASCII: other text becomes an RFC 2047 encoded word.
fn header_text(text: &str) -> String {
    if text.is_ascii() {
        return text.to_string();
    }
    format!("=?UTF-8?B?{}?=", STANDARD.encode(text))
}

/// One body part, base64 in CRLF lines, so any text survives any mail server.
fn body_part(kind: &str, text: &str) -> String {
    let encoded = STANDARD.encode(text);
    let lines: Vec<&str> = (0..encoded.len())
        .step_by(76)
        .map(|at| &encoded[at..encoded.len().min(at + 76)])
        .collect();
    format!(
        "Content-Type: {kind}; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n{}",
        lines.join("\r\n")
    )
}

/// A whole RFC 5322 message, text and HTML, with CRLF line ends. Rust's
/// standard library has no builder for one, so this writes it out.
fn build_message(from: &str, to: &str, subject: &str) -> Result<Vec<u8>, Box<dyn Error>> {
    // std has no random numbers either, so the Message-ID and the boundary
    // are a hash of the message and the clock, which no two sends share.
    let nanos = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
    let unique: String = Sha256::digest(format!("{from}\n{to}\n{subject}\n{nanos}"))
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let (id, boundary) = (&unique[..32], format!("part-{}", &unique[32..56]));
    let domain = from
        .rsplit('@')
        .next()
        .unwrap_or_default()
        .trim_end_matches('>');

    Ok([
        format!("From: {from}"),
        format!("To: {to}"),
        format!("Subject: {}", header_text(subject)),
        // Keep the Message-ID. Sending the same one again answers the first
        // receipt and sends nothing twice, so a retry is safe.
        format!("Message-ID: <{id}@{domain}>"),
        // No Date: std has no calendar, and Mailset dates a message that
        // comes without one.
        "MIME-Version: 1.0".to_string(),
        format!("Content-Type: multipart/alternative; boundary=\"{boundary}\""),
        String::new(),
        format!("--{boundary}"),
        body_part("text/plain", "Your code is 123456.\n"),
        format!("--{boundary}"),
        body_part("text/html", "<p>Your code is <b>123456</b>.</p>\n"),
        format!("--{boundary}--"),
        String::new(),
    ]
    .join("\r\n")
    .into_bytes())
}

/// Submits whole messages, up to 100 a call. One result per message, in order.
fn send(raw: &[u8], key: &Value) -> Result<Vec<Value>, Box<dyn Error>> {
    let answer = run(
        "messages.submitMany",
        json!({
            "messages": [
                // Standard base64, on one line. transactional: a product's own
                // mail, such as a sign-in code or a receipt. No copy in Sent.
                { "data": STANDARD.encode(raw), "transactional": true }
            ]
        }),
        key,
    )?;
    if answer["ok"] != true {
        // The whole call was refused: the key, the signature or the input.
        return Err(answer["error"].to_string().into());
    }
    Ok(answer["data"]["results"]
        .as_array()
        .cloned()
        .unwrap_or_default())
}
```

---

© 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