You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EmailNotificationChannel.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.notification.email;
  21. import java.net.MalformedURLException;
  22. import java.net.URL;
  23. import java.util.Objects;
  24. import java.util.Set;
  25. import javax.annotation.CheckForNull;
  26. import javax.annotation.concurrent.Immutable;
  27. import org.apache.commons.lang.StringUtils;
  28. import org.apache.commons.mail.Email;
  29. import org.apache.commons.mail.EmailException;
  30. import org.apache.commons.mail.HtmlEmail;
  31. import org.apache.commons.mail.SimpleEmail;
  32. import org.sonar.api.config.EmailSettings;
  33. import org.sonar.api.notifications.Notification;
  34. import org.sonar.api.notifications.NotificationChannel;
  35. import org.sonar.api.user.User;
  36. import org.sonar.api.utils.SonarException;
  37. import org.sonar.api.utils.log.Logger;
  38. import org.sonar.api.utils.log.Loggers;
  39. import org.sonar.db.DbClient;
  40. import org.sonar.db.DbSession;
  41. import org.sonar.db.user.UserDto;
  42. import org.sonar.server.issue.notification.EmailMessage;
  43. import org.sonar.server.issue.notification.EmailTemplate;
  44. import static java.util.Objects.requireNonNull;
  45. /**
  46. * References:
  47. * <ul>
  48. * <li><a href="http://tools.ietf.org/html/rfc4021">Registration of Mail and MIME Header Fields</a></li>
  49. * <li><a href="http://tools.ietf.org/html/rfc2919">List-Id: A Structured Field and Namespace for the Identification of Mailing Lists</a></li>
  50. * <li><a href="https://github.com/blog/798-threaded-email-notifications">GitHub: Threaded Email Notifications</a></li>
  51. * </ul>
  52. *
  53. * @since 2.10
  54. */
  55. public class EmailNotificationChannel extends NotificationChannel {
  56. private static final Logger LOG = Loggers.get(EmailNotificationChannel.class);
  57. /**
  58. * @see org.apache.commons.mail.Email#setSocketConnectionTimeout(int)
  59. * @see org.apache.commons.mail.Email#setSocketTimeout(int)
  60. */
  61. private static final int SOCKET_TIMEOUT = 30_000;
  62. /**
  63. * Email Header Field: "List-ID".
  64. * Value of this field should contain mailing list identifier as specified in <a href="http://tools.ietf.org/html/rfc2919">RFC 2919</a>.
  65. */
  66. private static final String LIST_ID_HEADER = "List-ID";
  67. /**
  68. * Email Header Field: "List-Archive".
  69. * Value of this field should contain URL of mailing list archive as specified in <a href="http://tools.ietf.org/html/rfc2369">RFC 2369</a>.
  70. */
  71. private static final String LIST_ARCHIVE_HEADER = "List-Archive";
  72. /**
  73. * Email Header Field: "In-Reply-To".
  74. * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a>.
  75. */
  76. private static final String IN_REPLY_TO_HEADER = "In-Reply-To";
  77. /**
  78. * Email Header Field: "References".
  79. * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a>
  80. */
  81. private static final String REFERENCES_HEADER = "References";
  82. private static final String SUBJECT_DEFAULT = "Notification";
  83. private static final String SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG = "SMTP host was not configured - email will not be sent";
  84. private final EmailSettings configuration;
  85. private final EmailTemplate[] templates;
  86. private final DbClient dbClient;
  87. public EmailNotificationChannel(EmailSettings configuration, EmailTemplate[] templates, DbClient dbClient) {
  88. this.configuration = configuration;
  89. this.templates = templates;
  90. this.dbClient = dbClient;
  91. }
  92. public boolean isActivated() {
  93. return !StringUtils.isBlank(configuration.getSmtpHost());
  94. }
  95. @Override
  96. public boolean deliver(Notification notification, String username) {
  97. if (!isActivated()) {
  98. LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG);
  99. return false;
  100. }
  101. User user = findByLogin(username);
  102. if (user == null || StringUtils.isBlank(user.email())) {
  103. LOG.debug("User does not exist or has no email: {}", username);
  104. return false;
  105. }
  106. EmailMessage emailMessage = format(notification);
  107. if (emailMessage != null) {
  108. emailMessage.setTo(user.email());
  109. return deliver(emailMessage);
  110. }
  111. return false;
  112. }
  113. @Immutable
  114. public static final class EmailDeliveryRequest {
  115. private final String recipientEmail;
  116. private final Notification notification;
  117. public EmailDeliveryRequest(String recipientEmail, Notification notification) {
  118. this.recipientEmail = requireNonNull(recipientEmail, "recipientEmail can't be null");
  119. this.notification = requireNonNull(notification, "notification can't be null");
  120. }
  121. public String getRecipientEmail() {
  122. return recipientEmail;
  123. }
  124. public Notification getNotification() {
  125. return notification;
  126. }
  127. @Override
  128. public boolean equals(Object o) {
  129. if (this == o) {
  130. return true;
  131. }
  132. if (o == null || getClass() != o.getClass()) {
  133. return false;
  134. }
  135. EmailDeliveryRequest that = (EmailDeliveryRequest) o;
  136. return Objects.equals(recipientEmail, that.recipientEmail) &&
  137. Objects.equals(notification, that.notification);
  138. }
  139. @Override
  140. public int hashCode() {
  141. return Objects.hash(recipientEmail, notification);
  142. }
  143. @Override
  144. public String toString() {
  145. return "EmailDeliveryRequest{" + "'" + recipientEmail + '\'' + " : " + notification + '}';
  146. }
  147. }
  148. public int deliverAll(Set<EmailDeliveryRequest> deliveries) {
  149. if (deliveries.isEmpty() || !isActivated()) {
  150. LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG);
  151. return 0;
  152. }
  153. return (int) deliveries.stream()
  154. .filter(t -> !t.getRecipientEmail().isBlank())
  155. .map(t -> {
  156. EmailMessage emailMessage = format(t.getNotification());
  157. if (emailMessage != null) {
  158. emailMessage.setTo(t.getRecipientEmail());
  159. return deliver(emailMessage);
  160. }
  161. return false;
  162. })
  163. .filter(Boolean::booleanValue)
  164. .count();
  165. }
  166. @CheckForNull
  167. private User findByLogin(String login) {
  168. try (DbSession dbSession = dbClient.openSession(false)) {
  169. UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login);
  170. return dto != null ? dto.toUser() : null;
  171. }
  172. }
  173. private EmailMessage format(Notification notification) {
  174. for (EmailTemplate template : templates) {
  175. EmailMessage email = template.format(notification);
  176. if (email != null) {
  177. return email;
  178. }
  179. }
  180. LOG.warn("Email template not found for notification: {}", notification);
  181. return null;
  182. }
  183. boolean deliver(EmailMessage emailMessage) {
  184. if (!isActivated()) {
  185. LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG);
  186. return false;
  187. }
  188. try {
  189. send(emailMessage);
  190. return true;
  191. } catch (EmailException e) {
  192. LOG.error("Unable to send email", e);
  193. return false;
  194. }
  195. }
  196. private void send(EmailMessage emailMessage) throws EmailException {
  197. // Trick to correctly initialize javax.mail library
  198. ClassLoader classloader = Thread.currentThread().getContextClassLoader();
  199. Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
  200. try {
  201. LOG.trace("Sending email: {}", emailMessage);
  202. String host = resolveHost();
  203. Email email = createEmailWithMessage(emailMessage);
  204. setHeaders(email, emailMessage, host);
  205. setConnectionDetails(email);
  206. setToAndFrom(email, emailMessage);
  207. setSubject(email, emailMessage);
  208. email.send();
  209. } finally {
  210. Thread.currentThread().setContextClassLoader(classloader);
  211. }
  212. }
  213. private static Email createEmailWithMessage(EmailMessage emailMessage) throws EmailException {
  214. if (emailMessage.isHtml()) {
  215. return new HtmlEmail().setHtmlMsg(emailMessage.getMessage());
  216. }
  217. return new SimpleEmail().setMsg(emailMessage.getMessage());
  218. }
  219. private void setSubject(Email email, EmailMessage emailMessage) {
  220. String subject = StringUtils.defaultIfBlank(StringUtils.trimToEmpty(configuration.getPrefix()) + " ", "")
  221. + StringUtils.defaultString(emailMessage.getSubject(), SUBJECT_DEFAULT);
  222. email.setSubject(subject);
  223. }
  224. private void setToAndFrom(Email email, EmailMessage emailMessage) throws EmailException {
  225. String fromName = configuration.getFromName();
  226. String from = StringUtils.isBlank(emailMessage.getFrom()) ? fromName : (emailMessage.getFrom() + " (" + fromName + ")");
  227. email.setFrom(configuration.getFrom(), from);
  228. email.addTo(emailMessage.getTo(), " ");
  229. }
  230. @CheckForNull
  231. private String resolveHost() {
  232. try {
  233. return new URL(configuration.getServerBaseURL()).getHost();
  234. } catch (MalformedURLException e) {
  235. // ignore
  236. return null;
  237. }
  238. }
  239. private void setHeaders(Email email, EmailMessage emailMessage, @CheckForNull String host) {
  240. // Set general information
  241. email.setCharset("UTF-8");
  242. if (StringUtils.isNotBlank(host)) {
  243. /*
  244. * Set headers for proper threading: GMail will not group messages, even if they have same subject, but don't have "In-Reply-To" and
  245. * "References" headers. TODO investigate threading in other clients like KMail, Thunderbird, Outlook
  246. */
  247. if (StringUtils.isNotEmpty(emailMessage.getMessageId())) {
  248. String messageId = "<" + emailMessage.getMessageId() + "@" + host + ">";
  249. email.addHeader(IN_REPLY_TO_HEADER, messageId);
  250. email.addHeader(REFERENCES_HEADER, messageId);
  251. }
  252. // Set headers for proper filtering
  253. email.addHeader(LIST_ID_HEADER, "SonarQube <sonar." + host + ">");
  254. email.addHeader(LIST_ARCHIVE_HEADER, configuration.getServerBaseURL());
  255. }
  256. }
  257. private void setConnectionDetails(Email email) {
  258. email.setHostName(configuration.getSmtpHost());
  259. configureSecureConnection(email);
  260. if (StringUtils.isNotBlank(configuration.getSmtpUsername()) || StringUtils.isNotBlank(configuration.getSmtpPassword())) {
  261. email.setAuthentication(configuration.getSmtpUsername(), configuration.getSmtpPassword());
  262. }
  263. email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
  264. email.setSocketTimeout(SOCKET_TIMEOUT);
  265. }
  266. private void configureSecureConnection(Email email) {
  267. if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "ssl")) {
  268. email.setSSLOnConnect(true);
  269. email.setSSLCheckServerIdentity(true);
  270. email.setSslSmtpPort(String.valueOf(configuration.getSmtpPort()));
  271. // this port is not used except in EmailException message, that's why it's set with the same value than SSL port.
  272. // It prevents from getting bad message.
  273. email.setSmtpPort(configuration.getSmtpPort());
  274. } else if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "starttls")) {
  275. email.setStartTLSEnabled(true);
  276. email.setStartTLSRequired(true);
  277. email.setSSLCheckServerIdentity(true);
  278. email.setSmtpPort(configuration.getSmtpPort());
  279. } else if (StringUtils.isBlank(configuration.getSecureConnection())) {
  280. email.setSmtpPort(configuration.getSmtpPort());
  281. } else {
  282. throw new SonarException("Unknown type of SMTP secure connection: " + configuration.getSecureConnection());
  283. }
  284. }
  285. /**
  286. * Send test email.
  287. *
  288. * @throws EmailException when unable to send
  289. */
  290. public void sendTestEmail(String toAddress, String subject, String message) throws EmailException {
  291. try {
  292. EmailMessage emailMessage = new EmailMessage();
  293. emailMessage.setTo(toAddress);
  294. emailMessage.setSubject(subject);
  295. emailMessage.setPlainTextMessage(message);
  296. send(emailMessage);
  297. } catch (EmailException e) {
  298. LOG.debug("Fail to send test email to {}: {}", toAddress, e);
  299. throw e;
  300. }
  301. }
  302. }