Search in sources :

Example 1 with SimpleEmail

use of org.apache.commons.mail.SimpleEmail in project sonarqube by SonarSource.

the class EmailNotificationChannel method send.

private void send(EmailMessage emailMessage) throws EmailException {
    // Trick to correctly initialize javax.mail library
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {
        LOG.debug("Sending email: {}", emailMessage);
        String host = null;
        try {
            host = new URL(configuration.getServerBaseURL()).getHost();
        } catch (MalformedURLException e) {
        // ignore
        }
        SimpleEmail email = new SimpleEmail();
        if (StringUtils.isNotBlank(host)) {
            /*
         * Set headers for proper threading: GMail will not group messages, even if they have same subject, but don't have "In-Reply-To" and
         * "References" headers. TODO investigate threading in other clients like KMail, Thunderbird, Outlook
         */
            if (StringUtils.isNotEmpty(emailMessage.getMessageId())) {
                String messageId = "<" + emailMessage.getMessageId() + "@" + host + ">";
                email.addHeader(IN_REPLY_TO_HEADER, messageId);
                email.addHeader(REFERENCES_HEADER, messageId);
            }
            // Set headers for proper filtering
            email.addHeader(LIST_ID_HEADER, "SonarQube <sonar." + host + ">");
            email.addHeader(LIST_ARCHIVE_HEADER, configuration.getServerBaseURL());
        }
        // Set general information
        email.setCharset("UTF-8");
        String from = StringUtils.isBlank(emailMessage.getFrom()) ? FROM_NAME_DEFAULT : (emailMessage.getFrom() + " (SonarQube)");
        email.setFrom(configuration.getFrom(), from);
        email.addTo(emailMessage.getTo(), " ");
        String subject = StringUtils.defaultIfBlank(StringUtils.trimToEmpty(configuration.getPrefix()) + " ", "") + StringUtils.defaultString(emailMessage.getSubject(), SUBJECT_DEFAULT);
        email.setSubject(subject);
        email.setMsg(emailMessage.getMessage());
        // Send
        email.setHostName(configuration.getSmtpHost());
        configureSecureConnection(email);
        if (StringUtils.isNotBlank(configuration.getSmtpUsername()) || StringUtils.isNotBlank(configuration.getSmtpPassword())) {
            email.setAuthentication(configuration.getSmtpUsername(), configuration.getSmtpPassword());
        }
        email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
        email.setSocketTimeout(SOCKET_TIMEOUT);
        email.send();
    } finally {
        Thread.currentThread().setContextClassLoader(classloader);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SimpleEmail(org.apache.commons.mail.SimpleEmail) URL(java.net.URL)

Example 2 with SimpleEmail

use of org.apache.commons.mail.SimpleEmail in project openhab1-addons by openhab.

the class Mail method sendMail.

/**
     * Sends an email with attachment(s) via SMTP
     *
     * @param to the email address of the recipient
     * @param subject the subject of the email
     * @param message the body of the email
     * @param attachmentUrlList a list of URL strings of the contents to send as attachments
     *
     * @return <code>true</code>, if sending the email has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends an email with attachment via SMTP")
public static boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }
        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setStartTLSEnabled(startTLSEnabled);
        email.setSSLOnConnect(sslOnConnect);
        if (isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }
        try {
            if (isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!isEmpty(subject)) {
                email.setSubject(subject);
            }
            if (!isEmpty(message)) {
                email.setMsg(message);
            }
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error("Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', startTLSEnabled: {}, sslOnConnect: {}, username: '{}', password '{}'", new Object[] { hostname, String.valueOf(port), from, String.valueOf(startTLSEnabled), String.valueOf(sslOnConnect), username, password });
    }
    return success;
}
Also used : MalformedURLException(java.net.MalformedURLException) Email(org.apache.commons.mail.Email) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) EmailException(org.apache.commons.mail.EmailException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail) URL(java.net.URL) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 3 with SimpleEmail

use of org.apache.commons.mail.SimpleEmail in project killbill by killbill.

the class DefaultEmailSender method sendPlainTextEmail.

@Override
public void sendPlainTextEmail(final List<String> to, final List<String> cc, final String subject, final String body) throws IOException, EmailApiException {
    final SimpleEmail email = new SimpleEmail();
    try {
        email.setMsg(body);
    } catch (EmailException e) {
        throw new EmailApiException(e, ErrorCode.EMAIL_SENDING_FAILED);
    }
    sendEmail(to, cc, subject, email);
}
Also used : EmailException(org.apache.commons.mail.EmailException) SimpleEmail(org.apache.commons.mail.SimpleEmail)

Example 4 with SimpleEmail

use of org.apache.commons.mail.SimpleEmail in project sling by apache.

the class SimpleMailBuilder method build.

@Override
public Email build(@Nonnull final String message, @Nonnull final String recipient, @Nonnull final Map data) throws EmailException {
    final Map configuration = (Map) data.getOrDefault("mail", Collections.EMPTY_MAP);
    final String subject = (String) configuration.getOrDefault(SUBJECT_KEY, this.configuration.subject());
    final String from = (String) configuration.getOrDefault(FROM_KEY, this.configuration.from());
    final String charset = (String) configuration.getOrDefault(CHARSET_KEY, this.configuration.charset());
    final String smtpHostname = (String) configuration.getOrDefault(SMTP_HOSTNAME_KEY, this.configuration.smtpHostname());
    final int smtpPort = (Integer) configuration.getOrDefault(SMTP_PORT_KEY, this.configuration.smtpPort());
    final String smtpUsername = (String) configuration.getOrDefault(SMTP_USERNAME_KEY, this.configuration.smtpUsername());
    final String smtpPassword = (String) configuration.getOrDefault(SMTP_PASSWORD_KEY, this.configuration.smtpPassword());
    final Email email = new SimpleEmail();
    email.setCharset(charset);
    email.setMsg(message);
    email.addTo(recipient);
    email.setSubject(subject);
    email.setFrom(from);
    email.setHostName(smtpHostname);
    email.setSmtpPort(smtpPort);
    email.setAuthentication(smtpUsername, smtpPassword);
    return email;
}
Also used : Email(org.apache.commons.mail.Email) SimpleEmail(org.apache.commons.mail.SimpleEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) Map(java.util.Map)

Example 5 with SimpleEmail

use of org.apache.commons.mail.SimpleEmail in project graylog2-server by Graylog2.

the class FormattedEmailAlertSender method sendEmail.

private void sendEmail(String emailAddress, Stream stream, AlertCondition.CheckResult checkResult, List<Message> backlog) throws TransportConfigurationException, EmailException {
    LOG.debug("Sending mail to " + emailAddress);
    if (!configuration.isEnabled()) {
        throw new TransportConfigurationException("Email transport is not enabled in server configuration file!");
    }
    final Email email = new SimpleEmail();
    email.setCharset(EmailConstants.UTF_8);
    if (isNullOrEmpty(configuration.getHostname())) {
        throw new TransportConfigurationException("No hostname configured for email transport while trying to send alert email!");
    } else {
        email.setHostName(configuration.getHostname());
    }
    email.setSmtpPort(configuration.getPort());
    if (configuration.isUseSsl()) {
        email.setSslSmtpPort(Integer.toString(configuration.getPort()));
    }
    if (configuration.isUseAuth()) {
        email.setAuthenticator(new DefaultAuthenticator(Strings.nullToEmpty(configuration.getUsername()), Strings.nullToEmpty(configuration.getPassword())));
    }
    email.setSSLOnConnect(configuration.isUseSsl());
    email.setStartTLSEnabled(configuration.isUseTls());
    if (pluginConfig != null && !isNullOrEmpty(pluginConfig.getString("sender"))) {
        email.setFrom(pluginConfig.getString("sender"));
    } else {
        email.setFrom(configuration.getFromEmail());
    }
    email.setSubject(buildSubject(stream, checkResult, backlog));
    email.setMsg(buildBody(stream, checkResult, backlog));
    email.addTo(emailAddress);
    email.send();
}
Also used : Email(org.apache.commons.mail.Email) SimpleEmail(org.apache.commons.mail.SimpleEmail) TransportConfigurationException(org.graylog2.plugin.alarms.transports.TransportConfigurationException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail)

Aggregations

SimpleEmail (org.apache.commons.mail.SimpleEmail)6 Email (org.apache.commons.mail.Email)4 DefaultAuthenticator (org.apache.commons.mail.DefaultAuthenticator)3 EmailException (org.apache.commons.mail.EmailException)3 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 MultiPartEmail (org.apache.commons.mail.MultiPartEmail)2 Map (java.util.Map)1 EmailAttachment (org.apache.commons.mail.EmailAttachment)1 HtmlEmail (org.apache.commons.mail.HtmlEmail)1 ImageHtmlEmail (org.apache.commons.mail.ImageHtmlEmail)1 TransportConfigurationException (org.graylog2.plugin.alarms.transports.TransportConfigurationException)1 ActionDoc (org.openhab.core.scriptengine.action.ActionDoc)1