Example usage for org.apache.commons.mail Email setCharset

List of usage examples for org.apache.commons.mail Email setCharset

Introduction

In this page you can find the example usage for org.apache.commons.mail Email setCharset.

Prototype

public void setCharset(final String newCharset) 

Source Link

Document

Set the charset of the message.

Usage

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailBuilder.java

@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);//  w ww  . j a v  a 2  s  .  c  om
    email.addTo(recipient);
    email.setSubject(subject);
    email.setFrom(from);
    email.setHostName(smtpHostname);
    email.setSmtpPort(smtpPort);
    email.setAuthentication(smtpUsername, smtpPassword);
    return email;
}

From source file:org.camunda.bpm.quickstart.TaskAssignmentListener.java

public void notify(DelegateTask delegateTask) {

    String assignee = delegateTask.getAssignee();
    String taskId = delegateTask.getId();

    if (assignee != null) {

        // Get User Profile from User Management
        IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
        User user = identityService.createUserQuery().userId(assignee).singleResult();

        if (user != null) {

            // Get Email Address from User Profile
            String recipient = user.getEmail();

            if (recipient != null && !recipient.isEmpty()) {

                Email email = new SimpleEmail();
                email.setCharset("utf-8");
                email.setHostName(HOST);
                email.setAuthentication(USER, PWD);

                try {
                    email.setFrom("noreply@camunda.org");
                    email.setSubject("Task assigned: " + delegateTask.getName());
                    email.setMsg("Please complete: http://localhost:8080/camunda/app/tasklist/default/#/task/"
                            + taskId);/*from   ww  w. j ava2s. c om*/

                    email.addTo(recipient);

                    email.send();
                    LOGGER.info("Task Assignment Email successfully sent to user '" + assignee
                            + "' with address '" + recipient + "'.");

                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Could not send email to assignee", e);
                }

            } else {
                LOGGER.warning("Not sending email to user " + assignee + "', user has no email address.");
            }

        } else {
            LOGGER.warning(
                    "Not sending email to user " + assignee + "', user is not enrolled with identity service.");
        }

    }

}

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a plain text message.//from  ww  w  .  j  a  v  a2s .  co  m
 *
 * @param headers    the mail headers
 * @param body      the mail body (text based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendPlainTextMail(MailMessageHeaders headers, String body, DataSource... dataSources) {
    try {
        Email email = new SimpleEmail();

        if (dataSources != null && dataSources.length > 0) {
            MultiPartEmail multiPart = new MultiPartEmail();

            for (DataSource dataSource : dataSources)
                multiPart.attach(dataSource, dataSource.getName(), dataSource.getName());

            email = multiPart;
        }

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        email.setCharset(headers.getCharset());
        try {
            email.setMsg(new String(body.getBytes(), headers.getCharset()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.graylog2.alerts.FormattedEmailAlertSender.java

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!");
    }/*w w w.ja va2 s .  c  o  m*/

    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();
}

From source file:org.graylog2.alerts.StaticEmailAlertSender.java

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!");
    }/*from w  ww  . j  av  a2 s.  c o  m*/

    final Email email = new SimpleEmail();
    email.setCharset(EmailConstants.UTF_8);

    if (Strings.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 && !Strings.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();
}

From source file:org.ms123.common.workflow.tasks.TaskMailExecutor.java

public void execute(DelegateExecution execution) {
    TaskContext tc = new TaskContext(execution);
    showVariablenNames(tc);//from www .ja  v a  2s . c om
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String attachmentStr = getStringFromField(attachment, execution);
    String charSetStr = getStringFromField(charset, execution);

    Email email = createEmail(execution, textStr, htmlStr, attachmentStr);

    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    //setCharset(email, charSetStr);

    try {
        email.setCharset("utf-8");
        email.send();
    } catch (EmailException e) {
        throw new RuntimeException("TaskMailExecutor.Could not send e-mail", e);
    }
}

From source file:org.ms123.common.workflow.TaskSendExecutor.java

public void execute(DelegateExecution execution) {
    TaskContext tc = new TaskContext();
    tc.setExecution(execution);/*from  w  ww  .j a v  a 2  s . c  o  m*/
    setCategory(tc);
    showVariablenNames(tc);
    String toStr = getStringFromField(to, execution);
    String fromStr = getStringFromField(from, execution);
    String ccStr = getStringFromField(cc, execution);
    String bccStr = getStringFromField(bcc, execution);
    String subjectStr = getStringFromField(subject, execution);
    String textStr = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String attachmentStr = getStringFromField(attachment, execution);
    String charSetStr = getStringFromField(charset, execution);

    Email email = createEmail(execution, textStr, htmlStr, attachmentStr);

    addTo(email, toStr);
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    //setCharset(email, charSetStr);

    try {
        email.setCharset("utf-8");
        email.send();
    } catch (EmailException e) {
        throw new RuntimeException("TaskSendExecutor.Could not send e-mail", e);
    }
}

From source file:org.openhab.action.mail.internal.Mail.java

/**
 * Sends an email with attachment(s) via SMTP
 * /*from   w  w  w .  j a v a2s  .c  o  m*/
 * @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")
static public 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(StringUtils.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.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            if (StringUtils.isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.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 '{}', useTLS: {}, username: '{}', password '{}'",
                new Object[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}

From source file:org.polymap.rhei.um.operations.NewPasswordOperation.java

@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    try {/*w ww  .ja  v a2 s  .  c  om*/
        // password hash
        PasswordEncryptor encryptor = PasswordEncryptor.instance();
        String password = encryptor.createPassword(8);
        String hash = encryptor.encryptPassword(password);
        user.passwordHash().set(hash);
        log.debug("Neues Passwort: " + password + " -> " + hash);

        // username <= email
        String username = user.email().get();
        assert username != null && username.length() > 0;
        user.username().set(username);
        log.info("username: " + user.username().get());

        // commit
        UserRepository.instance().commitChanges();

        // XXX email
        String salu = user.salutation().get() != null ? user.salutation().get() : "";
        String header = (salu.equalsIgnoreCase("Herr") ? "r Herr " : " ") + salu + " " + user.name().get();
        Email email = new SimpleEmail();
        email.setCharset("ISO-8859-1");
        email.addTo(username).setSubject(i18n.get("emailSubject"))
                .setMsg(i18n.get("email", header, username, password));

        EmailService.instance().send(email);

        return Status.OK_STATUS;
    } catch (EmailException e) {
        throw new ExecutionException(i18n.get("errorMsg", e.getLocalizedMessage()), e);
    }
}

From source file:org.polymap.rhei.um.operations.NewUserOperation.java

@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    try {/*from  w w  w .j a  va 2  s  . co m*/
        // password hash
        PasswordEncryptor encryptor = PasswordEncryptor.instance();
        String password = encryptor.createPassword(8);
        String hash = encryptor.encryptPassword(password);
        user.passwordHash().set(hash);

        // username <= email
        String username = user.email().get();
        assert username != null && username.length() > 0;
        user.username().set(username);
        log.info("username: " + user.username().get());

        // commit
        UserRepository.instance().commitChanges();

        String salu = user.salutation().get() != null ? user.salutation().get() : "";
        String header = (salu.equalsIgnoreCase("Herr") ? "r " : " ") + salu + " " + user.name().get();
        Email email = new SimpleEmail();
        email.setCharset("ISO-8859-1");
        email.addTo(username).setSubject(emailSubject)
                .setMsg(new MessageFormat(emailContent, Polymap.getSessionLocale())
                        .format(new Object[] { header, username, password }));
        //                    .setMsg( i18n.get( "email", header, username, password ) );

        EmailService.instance().send(email);

        return Status.OK_STATUS;

    } catch (EmailException e) {
        throw new ExecutionException(i18n.get("errorMsg", e.getLocalizedMessage()), e);
    }
}