Search in sources :

Example 1 with Configurable

use of alfio.model.Configurable in project alf.io by alfio-event.

the class SmtpMailer method send.

@Override
public void send(Configurable configurable, String fromName, String to, List<String> cc, String subject, String text, Optional<String> html, Attachment... attachments) {
    var conf = configurationManager.getFor(Set.of(SMTP_FROM_EMAIL, MAIL_REPLY_TO, SMTP_HOST, SMTP_PORT, SMTP_PROTOCOL, SMTP_USERNAME, SMTP_PASSWORD, SMTP_PROPERTIES), configurable.getConfigurationLevel());
    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments) ? new MimeMessageHelper(mimeMessage, true, "UTF-8") : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(conf.get(SMTP_FROM_EMAIL).getRequiredValue(), fromName);
        String replyTo = conf.get(MAIL_REPLY_TO).getValueOrDefault("");
        if (StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if (cc != null && !cc.isEmpty()) {
            message.setCc(cc.toArray(new String[0]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }
        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()), a.getContentType());
            }
        }
        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(conf).send(preparator);
}
Also used : MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) java.util(java.util) MailParseException(org.springframework.mail.MailParseException) MessagingException(javax.mail.MessagingException) ArrayUtils(org.apache.commons.lang3.ArrayUtils) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) StringUtils(org.apache.commons.lang3.StringUtils) ByteArrayResource(org.springframework.core.io.ByteArrayResource) StandardCharsets(java.nio.charset.StandardCharsets) PropertiesLoaderUtils(org.springframework.core.io.support.PropertiesLoaderUtils) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) EncodedResource(org.springframework.core.io.support.EncodedResource) JavaMailSenderImpl(org.springframework.mail.javamail.JavaMailSenderImpl) Log4j2(lombok.extern.log4j.Log4j2) FileTypeMap(javax.activation.FileTypeMap) Session(javax.mail.Session) Configurable(alfio.model.Configurable) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) InputStream(java.io.InputStream) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) ByteArrayResource(org.springframework.core.io.ByteArrayResource) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper)

Example 2 with Configurable

use of alfio.model.Configurable in project alf.io by alfio-event.

the class MailjetMailerTest method send.

@Test
void send() throws Exception {
    var attachment = new Mailer.Attachment("filename", "test".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of("model", "model"), Mailer.AttachmentIdentifier.CALENDAR_ICS);
    @SuppressWarnings("unchecked") var response = (HttpResponse<Object>) mock(HttpResponse.class);
    when(response.statusCode()).thenReturn(200);
    when(httpClient.send(any(), any())).thenReturn(response);
    mailjetMailer.send(configurable, "from_name", "to", List.of("cc"), "subject", "text", Optional.of("html"), attachment);
    verify(httpClient).send(requestCaptor.capture(), eq(HttpResponse.BodyHandlers.discarding()));
    // verify request
    var request = requestCaptor.getValue();
    assertNotNull(request);
    var body = request.bodyPublisher().orElseThrow();
    var semaphore = new Semaphore(1);
    // acquire lock so that the async processing can complete before exiting the test
    assertTrue(semaphore.tryAcquire());
    body.subscribe(new Flow.Subscriber<>() {

        private final StringBuffer buffer = new StringBuffer();

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            subscription.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(ByteBuffer item) {
            buffer.append(new String(item.array(), StandardCharsets.UTF_8));
        }

        @Override
        public void onError(Throwable throwable) {
            fail(throwable);
        }

        @Override
        public void onComplete() {
            assertTrue(buffer.length() > 0);
            var payload = Json.fromJson(buffer.toString(), new TypeReference<Map<String, JsonNode>>() {
            });
            assertNotNull(payload);
            assertFalse(payload.isEmpty());
            assertEquals("mail_from", getValue(payload.get("FromEmail")));
            assertEquals("from_name", getValue(payload.get("FromName")));
            assertEquals("subject", getValue(payload.get("Subject")));
            assertEquals("text", getValue(payload.get("Text-part")));
            assertEquals("html", getValue(payload.get("Html-part")));
            var recipients = payload.get("Recipients");
            var counter = new AtomicInteger(0);
            var emails = List.of("to", "cc");
            recipients.forEach(node -> {
                if (emails.contains(node.get("Email").asText())) {
                    counter.incrementAndGet();
                }
            });
            // we expect to find both addresses
            assertEquals(2, counter.get());
            assertEquals("mail_to", payload.get("Headers").get("Reply-To").asText());
            assertEquals(1, payload.get("Attachments").size());
            var attachment = payload.get("Attachments").get(0);
            assertEquals("filename", attachment.get("Filename").asText());
            assertEquals("text/plain", attachment.get("Content-type").asText());
            assertEquals(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)), attachment.get("content").asText());
            var headers = request.headers();
            assertEquals(HttpUtils.APPLICATION_JSON, headers.firstValue(HttpUtils.CONTENT_TYPE).orElseThrow());
            assertEquals(HttpUtils.basicAuth("public", "private"), headers.firstValue(HttpUtils.AUTHORIZATION).orElseThrow());
            semaphore.release();
        }
    });
    assertTrue(semaphore.tryAcquire(1, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) MAIL_REPLY_TO(alfio.model.system.ConfigurationKeys.MAIL_REPLY_TO) java.util(java.util) HttpUtils(alfio.util.HttpUtils) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) CompletableFuture(java.util.concurrent.CompletableFuture) ByteBuffer(java.nio.ByteBuffer) HttpRequest(java.net.http.HttpRequest) Json(alfio.util.Json) ArgumentCaptor(org.mockito.ArgumentCaptor) SSLSession(javax.net.ssl.SSLSession) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Flow(java.util.concurrent.Flow) Configurable(alfio.model.Configurable) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpClient(java.net.http.HttpClient) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpResponse(java.net.http.HttpResponse) Semaphore(java.util.concurrent.Semaphore) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) MaybeConfigurationBuilder.existing(alfio.manager.testSupport.MaybeConfigurationBuilder.existing) Assertions(org.junit.jupiter.api.Assertions) ConfigurationKeys(alfio.model.system.ConfigurationKeys) MaybeConfigurationBuilder(alfio.manager.testSupport.MaybeConfigurationBuilder) HttpHeaders(java.net.http.HttpHeaders) HttpResponse(java.net.http.HttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode) Semaphore(java.util.concurrent.Semaphore) ByteBuffer(java.nio.ByteBuffer) Flow(java.util.concurrent.Flow) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.jupiter.api.Test)

Aggregations

Configurable (alfio.model.Configurable)2 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 StandardCharsets (java.nio.charset.StandardCharsets)2 java.util (java.util)2 MaybeConfigurationBuilder (alfio.manager.testSupport.MaybeConfigurationBuilder)1 MaybeConfigurationBuilder.existing (alfio.manager.testSupport.MaybeConfigurationBuilder.existing)1 MAIL_REPLY_TO (alfio.model.system.ConfigurationKeys.MAIL_REPLY_TO)1 HttpUtils (alfio.util.HttpUtils)1 Json (alfio.util.Json)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 URI (java.net.URI)1 HttpClient (java.net.http.HttpClient)1 HttpHeaders (java.net.http.HttpHeaders)1 HttpRequest (java.net.http.HttpRequest)1 HttpResponse (java.net.http.HttpResponse)1 ByteBuffer (java.nio.ByteBuffer)1