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:
Service | Description | Key Methods |
---|---|---|
AccountService | Email account management | GetAccount , CreateAccount , UpdateAccount , ListAccounts , GetAccountState |
MessageService | Email message operations | ListMessages , MoveMessages , DeleteMessages , FetchMessageContent , MessageSearch |
MailboxService | Mailbox management | ListMailboxes , CreateMailbox , SubscribeMailbox , RenameMailbox |
SendMailService | Email sending operations | SendNewMail , ReplyMail , ForwardMail , ListEmailTasks |
AutoConfigService | Email server auto-configuration | GetAutoconfig |
OAuth2Service | OAuth2 configuration management | CreateOAuth2Config , GetOAuth2Config , CreateAuthorizeUrl , GetOAuth2Tokens |
MtaService | Mail Transfer Agent management | CreateMta , ListMta , SendTestEmail , UpdateMta |
TemplatesService | Email template management | CreateTemplate , ListTemplates , SendTestEmail , ListAccountTemplates |
StatusService | System status and monitoring | GetStatus , GetNotifications |
EventHooksService | Webhook and event management | CreateEventHook , 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
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 Range | gRPC Status | Description |
---|---|---|
10000-10999 | INVALID_ARGUMENT | Client errors |
20000-20999 | PERMISSION_DENIED | Authentication errors |
30000-30999 | NOT_FOUND, ALREADY_EXISTS | Resource errors |
40000+ | INTERNAL | Server 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
Issue | Solution |
---|---|
Connection refused | Check if gRPC server is enabled and running on correct port |
Authentication failed | Verify access token is valid and properly formatted |
SSL/TLS errors | Ensure HTTPS settings match between client and server |
Compression errors | Verify 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
- Connection Pooling: Reuse gRPC connections when possible
- Compression: Enable compression for better performance
- Error Handling: Always check both gRPC status and RustMailer error codes
- Authentication: Store access tokens securely
- Timeouts: Set appropriate request timeouts for your use case
- Retry Logic: Implement exponential backoff for transient errors