Search in sources :

Example 51 with SimpleMailMessage

use of org.springframework.mail.SimpleMailMessage in project goci by EBISPOT.

the class GOCIMailService method sendEmail.

public void sendEmail(GenericEmail email) {
    // Format mail message
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setTo(email.getTo());
    mailMessage.setFrom(email.getFrom());
    mailMessage.setSubject(email.getSubject());
    mailMessage.setText(email.getBody());
    javaMailSender.send(mailMessage);
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage)

Example 52 with SimpleMailMessage

use of org.springframework.mail.SimpleMailMessage in project perun by CESNET.

the class RTMessagesManagerBlImpl method sendMessageToRT.

@Override
public RTMessage sendMessageToRT(PerunSession sess, int voId, String queue, String subject, String text) {
    log.debug("Parameters of rtMessage are queue='" + queue + "', subject='{}' and text='{}'", subject, text);
    // Get Email from User who get from session
    String email;
    User user = sess.getPerunPrincipal().getUser();
    // try to get user/member email from user in session
    if (user != null)
        email = findUserPreferredEmail(sess, user);
    else {
        email = null;
        log.info("Can't get user from session.");
    }
    // try to get email from additionalInformations in session (attribute mail)
    if (email == null) {
        Matcher emailMatcher;
        Map<String, String> additionalInfo = sess.getPerunPrincipal().getAdditionalInformations();
        // If there are some data in additionalInfo
        if (additionalInfo != null) {
            String mailInfo = additionalInfo.get("mail");
            // If there is notnull attribute "mail" in map
            if (mailInfo != null) {
                // If attribute mail has separator ',' or ';'
                if (mailInfo.contains(";")) {
                    String[] mailsFromInfo = mailInfo.split(";");
                    for (String mail : mailsFromInfo) {
                        emailMatcher = Utils.emailPattern.matcher(mail);
                        if (emailMatcher.matches()) {
                            email = mail;
                            break;
                        }
                    }
                } else if (mailInfo.contains(",")) {
                    String[] mailsFromInfo = mailInfo.split(",");
                    for (String mail : mailsFromInfo) {
                        emailMatcher = Utils.emailPattern.matcher(mail);
                        if (emailMatcher.matches()) {
                            email = mail;
                            break;
                        }
                    }
                } else {
                    // If there is no separator, test if this has format of email, if yes, save it to email
                    emailMatcher = Utils.emailPattern.matcher(mailInfo);
                    if (emailMatcher.matches()) {
                        email = mailInfo;
                    }
                }
            }
        }
    }
    if (StringUtils.isNotBlank(BeansUtils.getCoreConfig().getRtSendToMail())) {
        // redirect all RT messages to mail address
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("[" + queue + "] " + subject);
        if (email != null) {
            simpleMailMessage.setText("Requestor: " + email + "\n\n" + text);
            simpleMailMessage.setReplyTo(email);
        } else {
            simpleMailMessage.setText("Requestor: UNKNOWN\n\n" + text);
        }
        simpleMailMessage.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
        simpleMailMessage.setTo(BeansUtils.getCoreConfig().getRtSendToMail());
        try {
            log.trace("Message to be sent: {}", simpleMailMessage);
            mailSender.send(simpleMailMessage);
        } catch (MailException ex) {
            log.error("RT message was not send to email address, due to an error.", ex);
            throw new InternalErrorException("RT message was not send to email address, due to an error: " + ex.getMessage());
        }
        return new RTMessage(email, 0);
    } else {
        // Prepare sending message
        HttpResponse response;
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // just like cookie-policy: ignore cookies
        httpClientBuilder.disableCookieManagement();
        HttpClient httpClient = httpClientBuilder.build();
        StringBuilder responseMessage = new StringBuilder();
        String ticketNumber = "0";
        try {
            response = httpClient.execute(this.prepareDataAndGetHttpRequest(sess, voId, queue, email, subject, text));
            BufferedReader bw = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            // Reading response from RT
            String line;
            while ((line = bw.readLine()) != null) {
                responseMessage.append(line);
                responseMessage.append('\n');
                // Matcher for ticketNumber
                Matcher ticketNumberMatcher = this.ticketNumberPattern.matcher(line);
                if (ticketNumberMatcher.find()) {
                    ticketNumber = ticketNumberMatcher.group(1);
                }
            }
        } catch (IOException ex) {
            throw new InternalErrorException("IOException has been throw while executing http request.", ex);
        }
        // Return message if response is ok, or throw exception with bad response
        int ticketNum = Integer.parseInt(ticketNumber);
        if (ticketNum != 0) {
            RTMessage rtmessage = new RTMessage(email, ticketNum);
            log.debug("RT message was send successfully and the ticket has number: " + ticketNum);
            return rtmessage;
        } else {
            throw new InternalErrorException("RT message was not send due to error with RT returned this message: " + responseMessage.toString());
        }
    }
}
Also used : User(cz.metacentrum.perun.core.api.User) InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) HttpResponse(org.apache.http.HttpResponse) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) RTMessage(cz.metacentrum.perun.core.api.RTMessage) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) MailException(org.springframework.mail.MailException)

Example 53 with SimpleMailMessage

use of org.springframework.mail.SimpleMailMessage in project springside4 by springside.

the class MailService method sendMail.

public void sendMail(String to, String from, String subject, String content) {
    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setFrom(from);
    mail.setTo(to);
    mail.setSubject(subject);
    mail.setText(content);
    mailSender.send(mail);
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage)

Example 54 with SimpleMailMessage

use of org.springframework.mail.SimpleMailMessage in project spring-framework by spring-projects.

the class JavaMailSenderTests method failedMailServerConnect.

@Test
public void failedMailServerConnect() {
    MockJavaMailSender sender = new MockJavaMailSender();
    sender.setHost(null);
    sender.setUsername("username");
    sender.setPassword("password");
    SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
    assertThatExceptionOfType(MailSendException.class).isThrownBy(() -> sender.send(simpleMessage1)).satisfies(ex -> assertThat(ex.getFailedMessages()).containsExactly(entry(simpleMessage1, (Exception) ex.getCause())));
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage) Test(org.junit.jupiter.api.Test)

Example 55 with SimpleMailMessage

use of org.springframework.mail.SimpleMailMessage in project spring-framework by spring-projects.

the class JavaMailSenderTests method javaMailSenderWithSimpleMessages.

@Test
public void javaMailSenderWithSimpleMessages() throws MessagingException {
    MockJavaMailSender sender = new MockJavaMailSender();
    sender.setHost("host");
    sender.setUsername("username");
    sender.setPassword("password");
    SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
    simpleMessage1.setTo("he@mail.org");
    SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
    simpleMessage2.setTo("she@mail.org");
    sender.send(simpleMessage1, simpleMessage2);
    assertThat(sender.transport.getConnectedHost()).isEqualTo("host");
    assertThat(sender.transport.getConnectedUsername()).isEqualTo("username");
    assertThat(sender.transport.getConnectedPassword()).isEqualTo("password");
    assertThat(sender.transport.isCloseCalled()).isTrue();
    assertThat(sender.transport.getSentMessages().size()).isEqualTo(2);
    MimeMessage sentMessage1 = sender.transport.getSentMessage(0);
    List<Address> tos1 = Arrays.asList(sentMessage1.getRecipients(Message.RecipientType.TO));
    assertThat(tos1.size()).isEqualTo(1);
    assertThat(((InternetAddress) tos1.get(0)).getAddress()).isEqualTo("he@mail.org");
    MimeMessage sentMessage2 = sender.transport.getSentMessage(1);
    List<Address> tos2 = Arrays.asList(sentMessage2.getRecipients(Message.RecipientType.TO));
    assertThat(tos2.size()).isEqualTo(1);
    assertThat(((InternetAddress) tos2.get(0)).getAddress()).isEqualTo("she@mail.org");
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) InternetAddress(jakarta.mail.internet.InternetAddress) Address(jakarta.mail.Address) MimeMessage(jakarta.mail.internet.MimeMessage) Test(org.junit.jupiter.api.Test)

Aggregations

SimpleMailMessage (org.springframework.mail.SimpleMailMessage)106 MailException (org.springframework.mail.MailException)17 Test (org.junit.Test)13 Test (org.testng.annotations.Test)7 Test (org.junit.jupiter.api.Test)6 User (org.molgenis.data.security.auth.User)5 JavaMailSender (org.springframework.mail.javamail.JavaMailSender)5 IOException (java.io.IOException)4 MessagingException (javax.mail.MessagingException)4 AbstractMolgenisSpringTest (org.molgenis.data.AbstractMolgenisSpringTest)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 MailSendException (org.springframework.mail.MailSendException)4 InternetAddress (jakarta.mail.internet.InternetAddress)3 MimeMessage (jakarta.mail.internet.MimeMessage)3 Date (java.util.Date)3 RunAsSystem (org.molgenis.security.core.runas.RunAsSystem)3 MolgenisUserException (org.molgenis.security.user.MolgenisUserException)3 JavaMailSenderImpl (org.springframework.mail.javamail.JavaMailSenderImpl)3 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 User (fr.codechill.spring.model.User)2