Skip to main content

gRPC Client Connection Guide

RustMailer provides a comprehensive gRPC API for programmatic access to all email management features. This guide shows you how to connect and interact with RustMailer using gRPC clients.

You can find the complete Protocol Buffer definitions in the protos/ directory. This includes the core file rustmailer.proto, which defines all gRPC services, message types, service interfaces, and method signatures. These definitions serve as the foundation for generating client code in various programming languages.

Use this file to generate gRPC client stubs in Rust, Go, TypeScript, or any other supported language.

Server Configuration

Default Settings

RustMailer's gRPC server runs with the following default configuration:

  • Port: 16630
  • Protocol: HTTP/2 (with optional HTTPS/TLS)
  • Compression: Configurable (none, gzip, brotli, zstd, deflate)
  • Authentication: Optional access token validation

Environment Variables

Configure the gRPC server using these environment variables:

# Enable/disable gRPC server
RUSTMAILER_GRPC_ENABLED=true

# gRPC server port
RUSTMAILER_GRPC_PORT=16630

# Enable HTTPS for gRPC
RUSTMAILER_ENABLE_GRPC_HTTPS=false

# Compression algorithm
RUSTMAILER_GRPC_COMPRESSION=gzip

# Server bind address
RUSTMAILER_BIND_IP=0.0.0.0

Available Services

RustMailer exposes the following gRPC services:

ServiceDescriptionKey Methods
AccountServiceEmail account managementGetAccount, CreateAccount, UpdateAccount, ListAccounts, GetAccountState
MessageServiceEmail message operationsListMessages, MoveMessages, DeleteMessages, FetchMessageContent, MessageSearch
MailboxServiceMailbox managementListMailboxes, CreateMailbox, SubscribeMailbox, RenameMailbox
SendMailServiceEmail sending operationsSendNewMail, ReplyMail, ForwardMail, ListEmailTasks
AutoConfigServiceEmail server auto-configurationGetAutoconfig
OAuth2ServiceOAuth2 configuration managementCreateOAuth2Config, GetOAuth2Config, CreateAuthorizeUrl, GetOAuth2Tokens
MtaServiceMail Transfer Agent managementCreateMta, ListMta, SendTestEmail, UpdateMta
TemplatesServiceEmail template managementCreateTemplate, ListTemplates, SendTestEmail, ListAccountTemplates
StatusServiceSystem status and monitoringGetStatus, GetNotifications
EventHooksServiceWebhook and event managementCreateEventHook, ListEventHook, VrlScriptResolve, EventExamples

Client Connection Examples

Node.js/JavaScript Client

import { ClientConfig, MessageServiceClient } from '@grpc/grpc-js';

// Create client configuration
const client = new MessageServiceClient(
'localhost:16630',
grpc.credentials.createInsecure()
);

// Enable compression
client.setOptions({
'grpc.default_compression_algorithm': 'gzip',
'grpc.default_compression_level': 'high'
});

// Make authenticated request
const metadata = new grpc.Metadata();
metadata.add('authorization', 'Bearer your-access-token');

const request = {
account_id: 123456789,
mailbox_name: 'INBOX',
page: 1,
page_size: 10,
remote: false,
desc: true
};

client.listMessages(request, metadata, (error, response) => {
if (error) {
console.error('gRPC Error:', error);
return;
}
console.log('Messages:', response.items);
});

Python Client

import grpc
from rustmailer_pb2_grpc import MessageServiceStub
from rustmailer_pb2 import ListMessagesRequest

# Create channel with compression
channel = grpc.insecure_channel(
'localhost:16630',
options=[
('grpc.default_compression_algorithm', grpc.Compression.Gzip),
('grpc.default_compression_level', grpc.Compression.High),
]
)

# Create client stub
client = MessageServiceStub(channel)

# Prepare request with authentication
metadata = [('authorization', 'Bearer your-access-token')]

request = ListMessagesRequest(
account_id=123456789,
mailbox_name='INBOX',
page=1,
page_size=10,
remote=False,
desc=True
)

try:
response = client.ListMessages(request, metadata=metadata)
print(f"Found {len(response.items)} messages")
except grpc.RpcError as e:
print(f"gRPC Error: {e.code()} - {e.details()}")
# Check for RustMailer error code in metadata
rustmailer_code = dict(e.trailing_metadata()).get('rustmailer-error-code')
if rustmailer_code:
print(f"RustMailer Error Code: {rustmailer_code}")

Go Client

package main

import (
"context"
"crypto/tls"
"log"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"

pb "your-project/rustmailer"
)

func main() {
// Create connection with compression
conn, err := grpc.Dial("localhost:16630",
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})),
grpc.WithDefaultCallOptions(grpc.UseCompressor("gzip")),
)
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()

// Create client
client := pb.NewMessageServiceClient(conn)

// Add authentication metadata
ctx := metadata.AppendToOutgoingContext(context.Background(),
"authorization", "Bearer your-access-token")

// Make request
request := &pb.ListMessagesRequest{
AccountId: 123456789,
MailboxName: "INBOX",
Page: 1,
PageSize: 10,
Remote: false,
Desc: true,
}

response, err := client.ListMessages(ctx, request)
if err != nil {
log.Printf("gRPC Error: %v", err)
return
}

log.Printf("Found %d messages", len(response.Items))
}

Authentication

See access_token

Access Token Authentication

If RUSTMAILER_ENABLE_ACCESS_TOKEN=true, all gRPC requests must include a valid access token:

// Add to request metadata
const metadata = new grpc.Metadata();
metadata.add('authorization', 'Bearer your-access-token');

Root Token Access

For administrative operations, use the root token found in {RUSTMAILER_ROOT_DIR}/root:

# Read root token
ROOT_TOKEN=$(cat /data/rustmailer/root)

# Use in gRPC metadata
metadata.add('authorization', `Bearer ${ROOT_TOKEN}`);

Error Handling

gRPC Status Codes

RustMailer maps internal error codes to standard gRPC status codes:

RustMailer Error RangegRPC StatusDescription
10000-10999INVALID_ARGUMENTClient errors
20000-20999PERMISSION_DENIEDAuthentication errors
30000-30999NOT_FOUND, ALREADY_EXISTSResource errors
40000+INTERNALServer errors

Error Metadata

The original RustMailer error code is included in gRPC metadata:

// Extract RustMailer error code
const rustmailerCode = error.metadata.get('rustmailer-error-code')[0];
console.log(`RustMailer Error Code: ${rustmailerCode}`);

Connection Troubleshooting

Common Issues

IssueSolution
Connection refusedCheck if gRPC server is enabled and running on correct port
Authentication failedVerify access token is valid and properly formatted
SSL/TLS errorsEnsure HTTPS settings match between client and server
Compression errorsVerify both client and server support the same compression algorithm

Health Check

Test connectivity using the StatusService:

const statusClient = new StatusServiceClient('localhost:16630');
statusClient.getStatus({}, (error, response) => {
if (error) {
console.error('Health check failed:', error);
} else {
console.log('Server status:', response.status);
}
});

Protocol Buffer Definitions

The complete protocol buffer definitions are available in the protos/rustmailer.proto file. Generate client stubs for your language using the protoc compiler:

# Generate JavaScript client
protoc --js_out=import_style=commonjs,binary:. \
--grpc-web_out=import_style=commonjs,mode=grpcwebtext:. \
rustmailer.proto

# Generate Python client
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. rustmailer.proto

# Generate Go client
protoc --go_out=. --go-grpc_out=. rustmailer.proto

Best Practices

  1. Connection Pooling: Reuse gRPC connections when possible
  2. Compression: Enable compression for better performance
  3. Error Handling: Always check both gRPC status and RustMailer error codes
  4. Authentication: Store access tokens securely
  5. Timeouts: Set appropriate request timeouts for your use case
  6. Retry Logic: Implement exponential backoff for transient errors