Unverified Commit 7dbd4cfe authored by Zzm0809's avatar Zzm0809 Committed by GitHub

fix email alert error (#2598)

* Fixed issues with flickering and repeated rendering when editor size changes * Spotless Apply * fix email alert error * fix * Update EmailSender.java --------- Co-authored-by: 's avatarZzm0809 <Zzm0809@users.noreply.github.com>
parent a41aac28
...@@ -35,7 +35,15 @@ ...@@ -35,7 +35,15 @@
<groupId>org.dinky</groupId> <groupId>org.dinky</groupId>
<artifactId>dinky-alert-base</artifactId> <artifactId>dinky-alert-base</artifactId>
</dependency> </dependency>
<!--
this dependency to fix <javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)>
because TLS1.3 does not have ECDHE-ECDSA-AES256-GCM-SHA384 and ECDHE-RSA-AES256-GCM-SHA384 that meet RFC8461, so it is deprecated
-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.69</version>
</dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId> <artifactId>javax.mail</artifactId>
......
...@@ -27,23 +27,18 @@ import org.dinky.alert.email.params.EmailParams; ...@@ -27,23 +27,18 @@ import org.dinky.alert.email.params.EmailParams;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.HtmlEmail;
import java.security.GeneralSecurityException;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.sun.mail.smtp.SMTPSSLProvider; import com.sun.mail.util.MailSSLSocketFactory;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
/** /**
...@@ -69,112 +64,71 @@ public final class EmailSender { ...@@ -69,112 +64,71 @@ public final class EmailSender {
} }
/** /**
* send mail * Sends an email with the given title and content.
* *
* @param title title * @param title the title of the email
* @param content content * @param content the content of the email
* @return an AlertResult object representing the result of the email sending
*/ */
public AlertResult send(String title, String content) { public AlertResult send(String title, String content) {
AlertResult alertResult = new AlertResult(); AlertResult alertResult = new AlertResult();
alertResult.setSuccess(false);
// if there is no receivers && no receiversCc, no need to process // if there is no receivers && no receiversCc, no need to process
if (CollectionUtils.isEmpty(emailParams.getReceivers()) if (CollectionUtils.isEmpty(emailParams.getReceivers())) {
&& CollectionUtils.isEmpty(emailParams.getReceiverCcs())) { logger.error("no receivers , you must set receivers");
logger.error("no receivers && no receiversCc");
return alertResult; return alertResult;
} }
Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
HtmlEmail email = new HtmlEmail();
try { try {
Session session = getSession(); String sendResult = MailUtil.send(
email.setHostName(emailParams.getServerHost()); getMailAccount(),
email.setSmtpPort(emailParams.getServerPort()); emailParams.getReceivers(),
email.setSSLOnConnect(emailParams.isSslEnable()); emailParams.getReceiverCcs(),
email.setSslSmtpPort(String.valueOf(emailParams.getServerPort())); null,
email.setStartTLSEnabled(emailParams.isStarttlsEnable()); title,
email.setSSLCheckServerIdentity(emailParams.isSslEnable()); content,
if (emailParams.isEnableSmtpAuth()) { true);
email.setAuthentication(emailParams.getUser(), emailParams.getPassword()); if (StringUtils.isNotBlank(sendResult)) {
}
email.setMailSession(session);
email.setFrom(emailParams.getUser(), emailParams.getSender());
email.setCharset(EmailConstants.CHARSET);
email.setSubject(title);
email.setMsg(content);
email.setDebug(true);
if (CollectionUtils.isNotEmpty(emailParams.getReceivers())) {
// receivers mail
for (String receiver : emailParams.getReceivers()) {
email.addTo(receiver);
}
}
if (CollectionUtils.isNotEmpty(emailParams.getReceiverCcs())) {
// cc
for (String receiverCc : emailParams.getReceiverCcs()) {
email.addCc(receiverCc);
}
}
// sender mail
String sendResult = email.send();
logger.info("Send email info: {}", sendResult); logger.info("Send email info: {}", sendResult);
alertResult.setSuccess(true); alertResult.setSuccess(true);
alertResult.setMessage(sendResult);
return alertResult; return alertResult;
} catch (Exception e) { }
} catch (GeneralSecurityException e) {
handleException(alertResult, e); handleException(alertResult, e);
} }
return alertResult; return alertResult;
} }
/** /**
* get session * Retrieves the MailAccount object for sending emails.
* *
* @return the new Session * @return the MailAccount object containing the email server configuration
* @throws GeneralSecurityException if there is a security exception during the process
*/ */
private Session getSession() { private MailAccount getMailAccount() throws GeneralSecurityException {
// support multilple email format MailAccount mailAccount = new MailAccount();
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailAccount.setHost(emailParams.getServerHost());
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mailAccount.setPort(emailParams.getServerPort());
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); String userNameFrom = emailParams.getUser();
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); if (emailParams.getUser() != null && emailParams.getSender() != null) {
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); userNameFrom = emailParams.getSender() + "<" + emailParams.getUser() + ">";
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
Properties props = new Properties();
props.put(EmailConstants.NAME_MAIL_PROTOCOL, "smtp");
props.setProperty(EmailConstants.MAIL_SMTP_HOST, emailParams.getServerHost());
props.setProperty(EmailConstants.MAIL_SMTP_PORT, String.valueOf(emailParams.getServerPort()));
props.setProperty(EmailConstants.MAIL_SMTP_AUTH, String.valueOf(emailParams.isEnableSmtpAuth()));
if (StringUtils.isNotEmpty(emailParams.getMailProtocol())) {
props.setProperty(EmailConstants.MAIL_TRANSPORT_PROTOCOL, emailParams.getMailProtocol());
} }
props.setProperty(EmailConstants.MAIL_SMTP_SSL_ENABLE, String.valueOf(emailParams.isSslEnable())); mailAccount.setFrom(userNameFrom);
props.setProperty(EmailConstants.MAIL_SMTP_STARTTLS_ENABLE, String.valueOf(emailParams.isStarttlsEnable())); if (emailParams.isEnableSmtpAuth()) {
props.setProperty(EmailConstants.MAIL_SENDER, emailParams.getSender()); mailAccount.setAuth(emailParams.isEnableSmtpAuth());
props.setProperty(EmailConstants.MAIL_USER, emailParams.getUser()); mailAccount.setUser(emailParams.getUser());
props.setProperty(EmailConstants.MAIL_PASSWD, emailParams.getPassword()); mailAccount.setPass(emailParams.getPassword());
if (StringUtils.isNotEmpty(emailParams.getSmtpSslTrust())) {
props.setProperty(EmailConstants.MAIL_SMTP_SSL_TRUST, emailParams.getSmtpSslTrust());
}
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// mail username and password
return new PasswordAuthentication(emailParams.getUser(), emailParams.getPassword());
} }
}; mailAccount.setStarttlsEnable(emailParams.isStarttlsEnable());
mailAccount.setSslEnable(emailParams.isSslEnable());
Session session = Session.getInstance(props, auth); mailAccount.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
session.addProvider(new SMTPSSLProvider()); MailSSLSocketFactory sf = new MailSSLSocketFactory();
return session; sf.setTrustedHosts(emailParams.getSmtpSslTrust().split(","));
mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
return mailAccount;
} }
/** /**
...@@ -182,6 +136,7 @@ public final class EmailSender { ...@@ -182,6 +136,7 @@ public final class EmailSender {
*/ */
private void handleException(AlertResult alertResult, Exception e) { private void handleException(AlertResult alertResult, Exception e) {
logger.error("Send email to {} failed", emailParams.getReceivers(), e); logger.error("Send email to {} failed", emailParams.getReceivers(), e);
alertResult.setSuccess(false);
alertResult.setMessage( alertResult.setMessage(
"Send email to {" + String.join(",", emailParams.getReceivers()) + "} failed," + e.toString()); "Send email to {" + String.join(",", emailParams.getReceivers()) + "} failed," + e.toString());
} }
......
...@@ -22,6 +22,7 @@ package org.dinky.alert.email; ...@@ -22,6 +22,7 @@ package org.dinky.alert.email;
import org.dinky.alert.AlertBaseConstant; import org.dinky.alert.AlertBaseConstant;
import org.dinky.alert.AlertResult; import org.dinky.alert.AlertResult;
import java.security.GeneralSecurityException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -58,9 +59,9 @@ public class EmailSenderTest { ...@@ -58,9 +59,9 @@ public class EmailSenderTest {
@Ignore @Ignore
@Test @Test
public void testTextSendMails() { public void testTextSendMails() throws GeneralSecurityException {
AlertResult alertResult = AlertResult alertResult =
emailSender.send(AlertBaseConstant.ALERT_TEMPLATE_TITLE, AlertBaseConstant.ALERT_TEMPLATE_MSG); emailSender.send(AlertBaseConstant.ALERT_TEMPLATE_TITLE, AlertBaseConstant.ALERT_TEMPLATE_MSG);
Assert.assertEquals(true, alertResult.getSuccess()); // 格式需要调整 Assert.assertEquals(true, alertResult.getSuccess());
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment