Email

Email Server

docker-compose.yml

version: "3"
services:
  email:
    image: greenmail/standalone:1.5.11
    container_name: email-server
    environment:
      - GREENMAIL_OPTS=-Dgreenmail.verbose -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.setup.test.smtps -Dgreenmail.setup.test.imaps -Dgreenmail.users=alice:alice123,bob:bob123,eve:eve123
    ports:
      - "3465:3465" # SMTPs
      - "3993:3993" # IMAPs
$ docker-compose -f docker-compose.yml up

IMAP Listener

imap_email_listener_tls.bal

import ballerina/email;
import ballerina/io;

listener email:ImapListener securedEP = check new ({
    host: "127.0.0.1",
    port: 3993,
    username: "bob",
    password: "bob123",
    pollingInterval: 15,
    secureSocket: {
        cert: "./resources/cert/server.crt",
        protocol: {
            name: email:TLS,
            versions: ["TLSv1.2", "TLSv1.1"]
        },
        verifyHostName: false
    }
});

isolated service on securedEP {
    isolated remote function onMessage(email:Message email) {
        io:println("Received email: ", email.subject);
    }
}
$ bal run imap_email_listener_tls.bal

IMAP Client

smtp_email_client_tls.bal

import ballerina/email;
import ballerina/io;

final email:SmtpClient securedEP = check new ("127.0.0.1", "alice", "alice123", {
    port: 3465,
    secureSocket: {
        cert: "./resources/cert/server.crt",
        protocol: {
            name: email:TLS,
            versions: ["TLSv1.2", "TLSv1.1"]
        },
        verifyHostName: false
    }
});

public function main() returns error? {
    email:Message email = {
        to: "bob",
        subject: "Hello, World!",
        body: "This is a sample email.",
        'from: "author@email.com"
    };
    check securedEP->sendMessage(email);
    io:println("Email sent successfully.");
}
$ bal run smtp_email_client_tls.bal

Resources

server.crt

-----BEGIN CERTIFICATE-----
MIIDgTCCAmmgAwIBAgIEB9RhrzANBgkqhkiG9w0BAQsFADBxMQswCQYDVQQGEwJV
UzEeMBwGA1UEChMVSWNlZ3JlZW4gVGVjaG5vbG9naWVzMRIwEAYDVQQLEwlHcmVl
bk1haWwxLjAsBgNVBAMTJUdyZWVuTWFpbCBzZWxmc2lnbmVkIFRlc3QgQ2VydGlm
aWNhdGUwHhcNMTkx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