Send your own MIME
Build the whole message yourself and hand it over as base64.
On this page
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.
From: Acme <moc.elpmaxe@olleh>
To: gro.elpmaxe@ana
Subject: Your Acme code
Message-ID: <moc.elpmaxe@85a4d2b7e0c1a9f3>
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.
Headers Mailset reads
Fromnames one address: the mailbox your key sends as or one of its aliases, or for a domain key one of the addresses it names. ASenderheader has to match it.To,CcandBccsay who gets it. There has to be at least one address among them, and at most 100 in each. Mailset takesBccout before the message leaves.Message-IDis 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.Dateis 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.
Headers Mailset refuses
- Two of
From,Sender,To,Cc,Bcc,Subject,Date,Message-ID,In-Reply-ToorReferences. A message has one of each. - A
Fromwith no address, or with more than one. - An unsubscribe header or
Precedence: bulkon a message sent withmodeset totransactional.
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.
import { messageOf } from 'mailset';
const { raw, messageId } = messageOf({
from: 'Acme <moc.elpmaxe@olleh>',
to: 'gro.elpmaxe@ana',
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);
import base64
from mailset import build_message
built = build_message(
{
"from": "Acme <moc.elpmaxe@olleh>",
"to": "gro.elpmaxe@ana",
"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))
import (
"encoding/base64"
"fmt"
"log"
mailset "mailset.app/go"
)
message := mailset.Message{
From: "Acme <moc.elpmaxe@olleh>",
To: []string{"gro.elpmaxe@ana"},
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))
require 'mailset'
message = Mailset.build_message(
from: 'Acme <moc.elpmaxe@olleh>',
to: 'gro.elpmaxe@ana',
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
require 'vendor/autoload.php';
$message = Mailset\Message::build([
'from' => 'Acme <moc.elpmaxe@olleh>',
'to' => 'gro.elpmaxe@ana',
'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;
import app.mailset.Message;
import app.mailset.RawMessage;
RawMessage raw = Message.builder()
.from("Acme <moc.elpmaxe@olleh>")
.to("gro.elpmaxe@ana")
.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());
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
let message = mailset::Message::builder()
.from("Acme <moc.elpmaxe@olleh>")
.to("gro.elpmaxe@ana")
.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, and are files Mailset's own tests run.
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(
// 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{}
# 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)
// 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",
/** 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.
/// 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")
)
}