Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Email SMTP OAuth2 support (#1296)

Martin Peetersda157933e920
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
index fa492ee45..6e76b088a 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
@@ -42,6 +42,7 @@ public abstract class AbstractMailAgent<T extends AbstractMailAgent<T, U, V>, U
public static final AttributeDescriptor<Boolean> DELETE_PROCESSED_MAIL = new AttributeDescriptor<>("deleteProcessedMail", ValueType.BOOLEAN).withOptional(true);
public static final AttributeDescriptor<Boolean> PREFER_HTML = new AttributeDescriptor<>("preferHTML", ValueType.BOOLEAN).withOptional(true);
public static final AttributeDescriptor<String> MAIL_FOLDER_NAME = new AttributeDescriptor<>("mailFolderName", ValueType.TEXT).withOptional(true);
+ public static final AttributeDescriptor<Boolean> START_TLS = new AttributeDescriptor<>("startTLS", ValueType.BOOLEAN).withOptional(true);
protected AbstractMailAgent() {
}
@@ -90,6 +91,14 @@ public abstract class AbstractMailAgent<T extends AbstractMailAgent<T, U, V>, U
return (T) this;
}
+ public Optional<Boolean> getStartTLS() { return getAttributes().getValue(START_TLS); }
+
+ @SuppressWarnings("unchecked")
+ public T setStartTLS(Boolean value) {
+ getAttributes().getOrCreate(START_TLS).setValue(value);
+ return (T) this;
+ }
+
public Optional<String> getMailFolderName() {
return getAttributes().getValue(MAIL_FOLDER_NAME);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailProtocol.java
index c964f28df..bccf2f3f8 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailProtocol.java
@@ -61,6 +61,7 @@ public abstract class AbstractMailProtocol<T extends AbstractMailAgent<T, U, V>,
Path persistenceDir = storageDir.resolve("protocol").resolve("mail");
Optional<OAuthGrant> oAuthGrant = getAgent().getOAuthGrant();
UsernamePassword userPassword = getAgent().getUsernamePassword().orElseThrow();
+ Optional<Boolean> startTLS = getAgent().getStartTLS();
MailClientBuilder clientBuilder = new MailClientBuilder(
container.getExecutorService(),
@@ -84,6 +85,8 @@ public abstract class AbstractMailProtocol<T extends AbstractMailAgent<T, U, V>,
oAuthGrant.map(oAuth -> clientBuilder.setOAuth(userPassword.getUsername(), oAuth)).orElseGet(() ->
clientBuilder.setBasicAuth(userPassword.getUsername(), userPassword.getPassword()));
+ startTLS.map(clientBuilder::setStartTls);
+
mailClient = clientBuilder.build();
mailClient.addConnectionListener(this::onConnectionEvent);
mailClient.addMessageListener(this::onMailMessage);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java b/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
index c37536a47..df8bb7db4 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
@@ -53,6 +53,7 @@ public class MailClientBuilder {
protected String user;
protected String password;
protected boolean deleteMessageOnceProcessed;
+ protected boolean startTls;
protected Properties properties = new Properties();
public MailClientBuilder(ScheduledExecutorService scheduledExecutorService, String protocol, String host, int port) {
@@ -82,6 +83,12 @@ public class MailClientBuilder {
return this;
}
+ public MailClientBuilder setStartTls(boolean startTls) {
+ this.startTls = startTls;
+ setProperty("mail." + protocol + ".starttls.enable", startTls);
+ return this;
+ }
+
public MailClientBuilder setCheckIntervalSeconds(int checkIntervalSeconds) {
this.checkIntervalSeconds = Math.max(checkIntervalSeconds, MIN_CHECK_INTERVAL_SECONDS);
return this;
@@ -184,6 +191,10 @@ public class MailClientBuilder {
return preferHTML;
}
+ public boolean isStartTls() {
+ return startTls;
+ }
+
public Properties getProperties() {
return properties;
}
@@ -192,7 +203,7 @@ public class MailClientBuilder {
return new MailClient(this);
}
- UsernamePassword getAuth() throws SocketException, NullPointerException {
+ public UsernamePassword getAuth() throws SocketException, NullPointerException {
Objects.requireNonNull(user, "User must be supplied");
if (oAuthGrant != null) {
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index d5e7f4126..9eb2e9556 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -22,11 +22,14 @@ package org.openremote.manager.notification;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
+import org.openremote.agent.protocol.mail.MailClientBuilder;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.asset.Asset;
+import org.openremote.model.auth.OAuthClientCredentialsGrant;
+import org.openremote.model.auth.UsernamePassword;
import org.openremote.model.notification.AbstractNotificationMessage;
import org.openremote.model.notification.EmailNotificationMessage;
import org.openremote.model.notification.Notification;
@@ -72,7 +75,11 @@ public class EmailNotificationHandler implements NotificationHandler {
int port = getInteger(container.getConfig(), OR_EMAIL_PORT, OR_EMAIL_PORT_DEFAULT);
String user = container.getConfig().getOrDefault(OR_EMAIL_USER, null);
String password = container.getConfig().getOrDefault(OR_EMAIL_PASSWORD, null);
+ String clientId = container.getConfig().getOrDefault(OR_EMAIL_OAUTH2_CLIENT_ID, null);
+ String clientSecret = container.getConfig().getOrDefault(OR_EMAIL_OAUTH2_CLIENT_SECRET, null);
+ boolean useOAuth = !TextUtil.isNullOrEmpty(clientId) && !TextUtil.isNullOrEmpty(clientSecret);
+ // Parse map of headers
String headersStr = container.getConfig().getOrDefault(OR_EMAIL_X_HEADERS, null);
if (!TextUtil.isNullOrEmpty(headersStr)) {
headers = Arrays.stream(headersStr.split("\\R"))
@@ -85,32 +92,59 @@ public class EmailNotificationHandler implements NotificationHandler {
defaultFrom = container.getConfig().getOrDefault(OR_EMAIL_FROM, OR_EMAIL_FROM_DEFAULT);
- if (!TextUtil.isNullOrEmpty(host) && !TextUtil.isNullOrEmpty(user) && !TextUtil.isNullOrEmpty(password)) {
+ if (!TextUtil.isNullOrEmpty(host) && (useOAuth || (!TextUtil.isNullOrEmpty(user) && !TextUtil.isNullOrEmpty(password)))) {
+
+ // Init client builder
boolean startTls = getBoolean(container.getConfig(), OR_EMAIL_TLS, OR_EMAIL_TLS_DEFAULT);
String protocol = startTls ? "smtp" : getString(container.getConfig(), OR_EMAIL_PROTOCOL, OR_EMAIL_PROTOCOL_DEFAULT);
- Properties props = new Properties();
- props.put("mail." + protocol + ".auth", true);
- props.put("mail." + protocol + ".starttls.enable", startTls);
- props.put("mail." + protocol + ".host", host);
- props.put("mail." + protocol + ".port", port);
-
- mailSession = Session.getInstance(props, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, password);
+ MailClientBuilder mailClientBuilder = new MailClientBuilder(
+ container.getExecutorService(), protocol, host, port
+ );
+
+ // Add authentication
+ if (useOAuth) {
+ String oAuthUrl = container.getConfig().getOrDefault(OR_EMAIL_OAUTH2_URL, null);
+ String oAuthScopes = container.getConfig().getOrDefault(OR_EMAIL_OAUTH2_SCOPES, "");
+
+ if(TextUtil.isNullOrEmpty(clientId) || TextUtil.isNullOrEmpty(clientSecret)) {
+ LOG.info("Tried to configure oAuth2, but no client id and/or client secret is present. Falling back to basic auth.");
+ mailClientBuilder.setBasicAuth(user, password);
+
+ } else if (TextUtil.isNullOrEmpty(oAuthUrl)) {
+ LOG.info("oAuth2 is enabled, but no oAuth2 token URL is configured. Falling back to basic auth.");
+ mailClientBuilder.setBasicAuth(user, password);
+
+ } else {
+ mailClientBuilder.setOAuth(user, new OAuthClientCredentialsGrant(oAuthUrl, clientId, clientSecret, oAuthScopes));
}
- });
- boolean valid;
+ } else {
+ mailClientBuilder.setBasicAuth(user, password);
+ }
+
+ if (startTls) {
+ mailClientBuilder.setStartTls(true);
+ }
+ // Create session
+ mailSession = Session.getInstance(mailClientBuilder.getProperties());
+ if (container.isDevMode()) {
+ mailSession.setDebug(true);
+ }
+
+ // Initiate transport to test and validate connection
+ boolean valid;
try {
mailTransport = mailSession.getTransport(protocol);
- mailTransport.connect();
+ UsernamePassword usernamePassword = mailClientBuilder.getAuth();
+ mailTransport.connect(usernamePassword.getUsername(), usernamePassword.getPassword());
valid = mailTransport.isConnected();
try {
mailTransport.close();
} catch (Exception ignored) {
+ // ignored
}
+
} catch (Exception e) {
valid = false;
LOG.log(Level.SEVERE, "Failed to connect to SMTP server so disabling email notifications", e);
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index 54e674c46..72b1ad3af 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -59,6 +59,10 @@ public interface Constants {
String OR_SSL_PORT = "OR_SSL_PORT";
String OR_EMAIL_USER = "OR_EMAIL_USER";
String OR_EMAIL_HOST = "OR_EMAIL_HOST";
+ String OR_EMAIL_OAUTH2_URL = "OR_EMAIL_OAUTH2_URL";
+ String OR_EMAIL_OAUTH2_CLIENT_ID = "OR_EMAIL_OAUTH2_CLIENT_ID";
+ String OR_EMAIL_OAUTH2_CLIENT_SECRET = "OR_EMAIL_OAUTH2_CLIENT_SECRET";
+ String OR_EMAIL_OAUTH2_SCOPES = "OR_EMAIL_OAUTH2_SCOPES";
String OR_EMAIL_PASSWORD = "OR_EMAIL_PASSWORD";
String OR_EMAIL_PORT = "OR_EMAIL_PORT";
int OR_EMAIL_PORT_DEFAULT = 587;
diff --git a/profile/deploy.yml b/profile/deploy.yml
index 48f8673ea..b3493f5c8 100644
--- a/profile/deploy.yml
+++ b/profile/deploy.yml
@@ -176,6 +176,11 @@ services:
OR_EMAIL_X_HEADERS: # Headers to set on all outbound emails
OR_EMAIL_PROTOCOL: # smtp or smtps for SSL (if TLS not set or is true then smtp is assumed)
+ # Optional oAuth2 configuration to use instead of username/password
+ OR_EMAIL_OAUTH2_URL: # url to request an access token
+ OR_EMAIL_OAUTH2_CLIENT_ID:
+ OR_EMAIL_OAUTH2_CLIENT_SECRET:
+
# Where to send admin emails to
OR_EMAIL_ADMIN: