• Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 4 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ballerina module to send and receive emails

Ballerina Email Library

Build codecov Trivy GraalVM Check GitHub Last Commit Github issues

This library provides APIs to perform email operations such as sending and reading emails using the SMTP, POP3, and IMAP4 protocols.

Client

This library supports the following three client types.

email:SmtpClient: The client, which supports sending an email using the SMTP protocol.

email:PopClient: The client, which supports receiving an email using the POP3 protocol.

email:ImapClient: The client, which supports receiving an email using the IMAP4 protocol.

SMTP client

To send an email using the SMTP protocol, you must first create an email:SmtpClient object. The code for creating an email:SmtpClient can be found below.

Create a client

The following code creates an SMTP client, which connects to the default port (i.e. 465) and enables SSL.

email:SmtpClient smtpClient = check new ("smtp.email.com", "[email protected]", "pass123");

The port number of the server can be configured by passing the following configurations.

email:SmtpConfiguration smtpConfig = {
    port: 465
};

email:SmtpClient smtpClient = check new ("smtp.email.com", "[email protected]", "pass123", smtpConfig);
Send an email

Once the email:SmtpClient is created, an email can be sent using the SMTP protocol through that client. Samples for this operation can be found below.

email:Message email = {
    to: ["[email protected]", "[email protected]"],
    cc: ["[email protected]", "[email protected]"],
    bcc: ["[email protected]"],
    subject: "Sample Email",
    body: "This is a sample email.",
    'from: "[email protected]",
    sender: "[email protected]",
    replyTo: ["[email protected]", "[email protected]"]
};

check smtpClient->sendMessage(email);

An email can be sent directly by calling the client specifying optional parameters as named parameters as well. Samples for this operation can be found below.

email:Error? response = smtpClient->send(
    ["[email protected]", "[email protected]"],
    "Sample Email",
    "[email protected]",
    body="This is a sample email.",
    cc=["[email protected]", "[email protected]"],
    bcc=["[email protected]"],
    sender="[email protected]",
    replyTo=["[email protected]", "[email protected]"]
);

POP3 client

To receive an email using the POP3 protocol, you must first create an email:PopClient object. The code for creating an email:PopClient can be found below.

Create a client

The following code creates a POP3 client, which connects to the default port (i.e. 995) and enables SSL.

email:PopClient popClient = check new ("pop.email.com", "[email protected]", "pass456");

The port number of the server can be configured by passing the following configurations.

email:PopConfiguration popConfig = {
    port: 995
};

email:PopClient popClient = check new ("pop.email.com", "[email protected]", "pass456", popConfig);
Receive an email

Once the email:PopClient is created, emails can be received using the POP3 protocol through that client. Samples for this operation can be found below.

email:Message? emailResponse = check popClient->receiveMessage();

IMAP4 client

To receive an email using the IMAP4 protocol, you must first create an email:ImapClient object. The code for creating an email:ImapClient can be found below.

Create a client

The following code creates an IMAP4 client, which connects to the default port (i.e. 993) and enables SSL.

email:ImapClient imapClient = check new ("imap.email.com", "[email protected]", "pass456");

The port number of the server can be configured by passing the following configuration.

email:ImapConfiguration imapConfig = {
    port: 993
};

email:ImapClient imapClient = check new ("imap.email.com", "[email protected]", "pass456", imapConfig);
Receive an email

Once the email:ImapClient is created, emails can be received using the IMAP4 protocol through that client. Samples for this operation can be found below.

email:Message? emailResponse = check imapClient->receiveMessage();

POP3 and IMAP listeners

As POP3 and IMAP4 protocols are similar in the listener use cases, POP3 is considered in the examples below. In order to receive emails one-by-one from a POP3 server, you must first create an email:PopListener object. The code for creating an email:PopListener can be found below.

listener email:PopListener emailListener = check new ({
    host: "pop.email.com",
    username: "[email protected]",
    password: "pass456",
    pollingInterval: 2,
    port: 995
});

Once initialized, a service can listen to the new emails as follows. New emails get received at the onMessage method and when errors happen, the onError method gets called.

service "emailObserver" on emailListener {

    remote function onMessage(email:Message emailMessage) {
        io:println("Email Subject: ", emailMessage.subject);
        io:println("Email Body: ", emailMessage.body);
    }

    remote function onError(email:Error emailError) {
        io:println("Error while polling for the emails: " + emailError.message());
    }

}

Security and authentication

The email library supports both the TLS/SSL and STARTTLS as transport-level security protocols.

Transport-level security for all SMTP, POP3, and IMAP clients/listeners can be configured with the secureSocket field.

secureSocket: {
    cert: "path/to/certfile.crt",
    protocol: {
        name: TLS,
        versions: ["TLSv1.2", "TLSv1.1"]
    },
    ciphers: ["TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"],
    verifyHostName: true
}

Transport-level security for the SMTP client configuration can be defined as follows.

email:SmtpConfiguration smtpConfig = {
    port: 465,
    secureSocket: {
        // Transport level configuration
    }
};

Transport-level security for the POP3 client configuration can be defined as follows.

email:PopConfiguration popConfig = {
     port: 995,
     secureSocket: {
         // Transport level configuration
     }
};

Transport-level security for the IMAP client configuration can be defined as follows.

email:ImapConfiguration imapConfig = {
     port: 993,
     secureSocket: {
         // Transport level configuration
     }
};

Transport-level security for the POP3 listener configuration can be defined as follows.

email:PopListenerConfiguration popListenerConfig = {
    host: "127.0.0.1",
    username: "hascode",
    password: "abcdef123",
    pollingInterval: 2,
    port: 995,
    secureSocket: {
        // Transport level configuration
    }
};

Transport-level security for the IMAP listener configuration can be defined as follows.

email:ImapListenerConfiguration imapListenerConfig = {
    host: "127.0.0.1",
    username: "hascode",
    password: "abcdef123",
    pollingInterval: 2,
    port: 993,
    secureSocket: {
        // Transport level configuration
    }
};

By default, TLS/SSL is enabled as the default transport-level security protocol, and the certificate verification is set as required. This optional protocol definition can be configured with the security enum field in each of the configuration types described above.

The options available with the security field are as follows.

SSL: As same as the default TLS/SSL protocol

START_TLS_NEVER: Disables both TLS/SSL and STARTTLS protocols and allows only the unencrypted transport-level communication

START_TLS_ALWAYS: Makes it mandatory to use the secure STARTTLS protocol

START_TLS_AUTO: Enables the STARTTLS protocol, which would switch to the unsecured communication mode if the secure STARTTLS mode is not available in the server

The following is an example of using the security field in the SMTP client with the START_TLS_AUTO mode.

email:SmtpConfiguration smtpConfig = {
    port: 587,
    secureSocket: {
        // Transport level configuration
    },
    security: START_TLS_AUTO
};

Similarly, other client/listener configuration types can also be defined with the security field.

Note: Make sure the port number is changed accordingly depending on the protocol used.

Standard port numbers used for each of the protocol for each type of transport security are as given below.

Protocol/Security SSL STARTTLS Unsecure
SMTP 465 587 25, 587
POP3 995 995 110
IMAP4 993 143, 993 143

All the authentications are based on the username/password credentials.

Note: When the 'from field is not provided in an email:Message, the username field of the initialization argument of the email:SmtpClient is set as the from address of an email to be sent with SMTP.

Message content and attachments

An email:Message prepared to be sent can have the text body content, body, and/or HTML body content (htmlBody). When emails are received with POP3 or IMAP, the text email bodies and HTML bodies of the email are captured by the body and htmlBody fields of the email:Message respectively.

When sending emails with SMTP, there are four options to specify the email attachments in the email:Message.

  1. With the email:Attachment type, which points to an attachment file along with its content-type
  2. With an array of the email:Attachment type
  3. With the mime:Entity type
  4. With an array of the mime:Entity type

Option 1 and 2 are designed for ordinary users to attach files from the local machine along with its content-type. Option 3 and 4 are designed for advanced users who have programming knowledge to define complex MIME typed data attachments.

The following is an example of attaching a PDF file to an email with option 1.

email:Attachment pdfAttachment = {filePath: "path/to/application.pdf", contentType: "application/pdf"};

email:Message email = {
    // Other fields
    attachments: pdfAttachment
};

The following is an example of attaching a JPG file to an email with option 3.

mime:Entity imageAttachment = new;
mime:ContentDisposition disposition = new;
disposition.fileName = "profilePic.jpg";
disposition.disposition = "attachment";
disposition.name = "profilePic";
imageAttachment.setContentDisposition(disposition);
imageAttachment.setContentId("ImageAttachment");
imageAttachment.setFileAsEntityBody("path/to/profilePic.jpg", mime:IMAGE_JPEG);

email:Message email = {
    // Other fields
    attachments: imageAttachment
};

Issues and projects

Issues and Projects tabs are disabled for this repository as this is part of the Ballerina Library. To report bugs, request new features, start new discussions, view project boards, etc. please visit the Ballerina library parent repository.

This repository only contains the source code for the package.

Build from the source

Set up the prerequisites

  1. Download and install Java SE Development Kit (JDK) version 17 (from one of the following locations).

    • Oracle

    • OpenJDK

      Note: Set the JAVA_HOME environment variable to the path name of the directory into which you installed JDK.

Build the source

Execute the commands below to build from source.

  1. To build the package:

        ./gradlew clean build
  2. To run the tests:

        ./gradlew clean test
  3. To run a group of tests

    ./gradlew clean test -Pgroups=<test_group_names>
    
  4. To build the without the tests:

    ./gradlew clean build -x test
    
  5. To debug package implementation:

    ./gradlew clean build -Pdebug=<port>
    
  6. To debug with Ballerina language:

    ./gradlew clean build -PbalJavaDebug=<port>
    
  7. Publish the generated artifacts to the local Ballerina central repository:

    ./gradlew clean build -PpublishToLocalCentral=true
    
  8. Publish the generated artifacts to the Ballerina central repository:

    ./gradlew clean build -PpublishToCentral=true
    

Contribute to Ballerina

As an open source project, Ballerina welcomes contributions from the community.

For more information, go to the contribution guidelines.

Code of conduct

All contributors are encouraged to read the Ballerina Code of Conduct.

Useful links

More Repositories

1

ballerina-lang

The Ballerina Programming Language
Ballerina
3,286
star
2

lsp4intellij

This language client library provides language server protocol support for IntelliJ IDEA and other Jetbrains IDEs.
Java
413
star
3

ballerina-spec

Ballerina Language and Platform Specifications
HTML
171
star
4

ballerina-dev-website

Dev version of the ballerina.io website
HTML
163
star
5

module-ballerina-graphql

The Ballerina GraphQL module is part of the Ballerina Standard Library. It is a spec-compliant, production-ready GraphQL implementation for writing GraphQL APIs in Ballerina.
Ballerina
144
star
6

nballerina

Ballerina compiler that generates native executables.
Ballerina
142
star
7

ballerina-library

The Ballerina Library
Ballerina
137
star
8

module-ballerina-jwt

Ballerina JWT module.
Ballerina
130
star
9

openapi-tools

Ballerina OpenApi-Tool
Java
129
star
10

module-ballerina-grpc

Ballerina gRPC Module
Ballerina
128
star
11

ballerina-release

Ballerina release scripts
Python
126
star
12

openapi-connectors

Generate Ballerina connector with OpenAPI definition
Ballerina
126
star
13

module-ballerina-http

Ballerina HTTP Module
Java
124
star
14

module-ballerinax-nats

Ballerina NATS Module.
Ballerina
124
star
15

ballerina-platform.github.io

ballerina-platform.github.io - Github pages based ballerina.io website
HTML
124
star
16

ballerina-action

Dockerfile
124
star
17

module-ballerina-io

Ballerina io Module
Ballerina
123
star
18

module-ballerina-tcp

Ballerina socket module
Java
122
star
19

module-ballerina-oauth2

Ballerina OAuth2 Module
Ballerina
122
star
20

module-ballerina-websocket

Ballerina WebSocket Module
Java
121
star
21

module-ballerina-websub

Ballerina Websub module.
Ballerina
120
star
22

module-ballerina-mime

Ballerina MIME Module
Java
119
star
23

plugin-intellij

Ballerina extension for IntelliJ IDEA.
Java
119
star
24

module-ballerinax-mysql

Ballerina mysql Module
Ballerina
119
star
25

module-ballerina-auth

Ballerina Auth Module
Java
119
star
26

module-ballerina-sql

Ballerina SQL Module
Java
119
star
27

module-ballerinax-kafka

Ballerina Kafka Module.
Ballerina
119
star
28

module-ballerina-udp

Ballerina UDP module enables transport layer communication over UDP protocol.
Java
118
star
29

module-ballerinax-java.jdbc

Ballerina JDBC Module
Ballerina
118
star
30

module-ballerina-cache

Ballerina cache Module
Ballerina
118
star
31

module-ballerina-log

Ballerina log Module
Ballerina
118
star
32

module-ballerina-c2c

Ballerina Code2Cloud implementation
Java
118
star
33

module-ballerinax-slack

Ballerina slack module
Ballerina
118
star
34

module-ballerinax-azure-cosmosdb

Ballerina
118
star
35

plugin-vscode-compiler-toolkit

Compiler tools for Ballerina developers
TypeScript
118
star
36

ballerina-dev-tools

Ballerina Developer Tooling
Java
118
star
37

module-ballerinax-stan

Ballerina NATS Streaming Module.
Java
117
star
38

module-ballerina-crypto

Ballerina crypto Module
Ballerina
117
star
39

module-ballerina-websubhub

This modules includes a bunch of APIs to facilitate writing different WebSub Hub implementations
Ballerina
116
star
40

module-ballerinax-googleapis.calendar

Connector repository for Google Calendar API.
Ballerina
116
star
41

module-ballerina-xmldata

Ballerina xml utils Module
Ballerina
116
star
42

module-ballerinax-postgresql

Ballerina PostgreSQL DB module
Ballerina
116
star
43

module-ballerinax-java.jms

Ballerina
116
star
44

module-ballerina-file

Ballerina File Module
Ballerina
116
star
45

module-ballerinax-azure-service-bus

Ballerina
116
star
46

module-ballerinax-aws.dynamodb

This is to keep the Amazon DynamoDB connector for Ballerina.
Ballerina
116
star
47

module-ballerinax-aws.s3

Ballerina
116
star
48

module-ballerina-task

Ballerina task Module
Java
116
star
49

module-ballerina-time

Ballerina time Module
Ballerina
116
star
50

module-ballerinax-azure.functions

The implementation of Azure Functions compiler extension for Ballerina.
Java
116
star
51

module-ballerinax-datamapper

A compiler extension to extract abstract representation of Ballerina connector actions and their associated types
Java
116
star
52

module-ballerina-uuid

Ballerina UUID Module
Ballerina
116
star
53

module-ballerinax-netsuite

The Ballerina connector to perform operations on Netsuite integrate cloud system.
Ballerina
116
star
54

module-ballerinax-twitter

This repo is to keep Ballerina Twitter connector implementation for Ballerina
Ballerina
116
star
55

ballerina-update-tool

Ballerina Update Tool implementation to manage Ballerina versions
Java
116
star
56

module-ballerinax-ai.agent

Ballerina ReAct type Agent module using Large language models (LLMs)
Ballerina
115
star
57

module-ballerina-os

Ballerina system Module
Java
115
star
58

module-ballerinax-jaeger

Ballerina Jaeger Observability Extension Module
Java
115
star
59

module-ballerinax-aws.sqs

Ballerina
115
star
60

module-ballerinax-mssql

Ballerina MSSQL DB module
Ballerina
115
star
61

module-ballerinax-aws.lambda

Java
115
star
62

module-ballerina-serdes

This is the Ballerina SerDes package, which is a part of the Ballerina Language Standard Library
Java
115
star
63

module-ballerinax-oracledb

Oracle Database Connector for Ballerina
Ballerina
115
star
64

module-ballerina-xslt

Ballerina xslt module
Java
115
star
65

module-ballerina-url

Ballerina encoding module.
Ballerina
115
star
66

module-ballerinax-rabbitmq

Ballerina RabbitMQ Module.
Ballerina
115
star
67

module-ballerinax-prometheus

Ballerina Prometheus Observability Extension Module
Java
115
star
68

module-ballerinai-transaction

Ballerina internal module of transaction implementation
Ballerina
115
star
69

module-ballerinax-mysql.driver

Ballerina Azure MySQL Module
Ballerina
115
star
70

module-ballerinax-azure-storage-service

Ballerina
115
star
71

graphql-tools

Maintain the source code for GraphQL related tools.
Java
115
star
72

module-ballerina-jballerina.java.arrays

Ballerina Java Array Module
Ballerina
114
star
73

module-ballerina-constraint

Ballerina Constraint Module
Ballerina
114
star
74

module-ballerinax-choreo

Ballerina Choreo Observability Extension Module
Java
114
star
75

ballerina-performance-cloud

Ballerina Performance Tests in Cloud
Shell
114
star
76

module-ballerinax-azure.eventhub

Azure Eventhub connector
Ballerina
114
star
77

module-ballerina-regex

Ballerina Regex Module
Ballerina
114
star
78

plugin-gradle

Ballerina Gradle plugin
Groovy
114
star
79

module-ballerinax-mssql.driver

Ballerina MSSQL DB Driver
Ballerina
114
star
80

module-ballerina-random

Ballerina Random Library
Ballerina
114
star
81

module-ballerinax-health.fhir.templates

FHIR Ballerina templates
Ballerina
114
star
82

module-ballerinax-persist.sql

SQL database support of Ballerina Persist
Ballerina
114
star
83

module-ballerinax-microsoft.onedrive

The Ballerina connector to perform operations on the files, which is stored on OneDrive
Ballerina
114
star
84

ballerina-custom-jre

Generates platform-specific custom Java runtime images to be bundled with Ballerina platform distributions, which contains only the required modules for Ballerina runtime.
114
star
85

asyncapi-tools

This repository is the code base for the ballerina async-api tool
Java
114
star
86

persist-tools

Ballerina persist tools
Ballerina
113
star
87

module-ballerinax-cdata.connect

Manage Ballerina CData connector modules centrally.
Java
113
star
88

module-ballerina-persist

Ballerina Persist module
Java
113
star
89

module-ballerinax-peoplehr

Ballerina connector for People HR
Ballerina
113
star
90

module-ballerinax-aws.ses

The Ballerina connector to perform operations on Amazon Simple Email Service(Amazon SES).
Ballerina
113
star
91

module-ballerinax-googleapis.people

Repository for Google People API Connector
Ballerina
113
star
92

module-ballerinax-microsoft.teams

The Ballerina Microsoft Teams Connector for teamwork and intelligent communications.
Ballerina
113
star
93

module-ballerinax-googleapis.drive

Repository for Google Drive module.
Ballerina
113
star
94

module-ballerinax-microsoft.excel

The Ballerina connector to perform operations on Excel workbooks stored in Microsoft OneDrive.
Ballerina
113
star
95

asyncapi-triggers

This repo will contain the trigger source code generated through ballerina async api tool
Ballerina
113
star
96

module-ballerinax-aws.simpledb

This is to keep the Amazon SimpleDB connector for Ballerina.
Ballerina
112
star
97

module-ballerinax-aws.sns

This repo is to keep the newly written Amazon SNS connector for Ballerina.
Ballerina
112
star
98

module-ballerina-toml

Ballerina TOML Parser
Ballerina
112
star
99

edi-tools

This library provides the functionality required to process EDI files and implement EDI integrations.
Ballerina
112
star
100

module-ballerinax-health.fhir.r4

FHIR R4 Ballerina modules
Ballerina
112
star