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

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

Introduction

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

Prototype

public void setCharset(final String newCharset) 

Source Link

Document

Set the charset of the message.

Usage

From source file:com.reizes.shiva.net.mail.EmailSender.java

public static String sendHtmlMail(String host, int port, String from, String to, String subject, String html)
        throws IOException, EmailException {

    if (to != null && host != null) {
        String[] emailTo = StringUtils.split(to, ';');

        MultiPartEmail email = new MultiPartEmail();

        email.setCharset("UTF-8");
        email.setHostName(host);//from w  ww  . j  av a 2s  . c  o  m
        email.setSmtpPort(port);
        email.setFrom(from);

        for (String recv : emailTo) {
            email.addTo(recv);
        }

        email.setSubject(subject);
        email.setMsg(html);

        return email.send();
    }

    return null;
}

From source file:com.pushinginertia.commons.net.email.EmailUtils.java

/**
 * Populates a newly instantiated {@link MultiPartEmail} with the given arguments.
 * @param email email instance to populate
 * @param smtpHost SMTP host that the message will be sent to
 * @param msg container object for the email's headers and contents
 * @throws IllegalArgumentException if the inputs are not valid
 * @throws EmailException if a problem occurs constructing the email
 */// w  w w .  j  a v a 2 s. c o m
public static void populateMultiPartEmail(final MultiPartEmail email, final String smtpHost,
        final EmailMessage msg) throws IllegalArgumentException, EmailException {
    ValidateAs.notNull(email, "email");
    ValidateAs.notNull(smtpHost, "smtpHost");
    ValidateAs.notNull(msg, "msg");

    email.setHostName(smtpHost);
    email.setCharset(UTF_8);
    email.setFrom(msg.getSender().getEmail(), msg.getSender().getName(), UTF_8);
    email.addTo(msg.getRecipient().getEmail(), msg.getRecipient().getName(), UTF_8);

    final NameEmail replyTo = msg.getReplyTo();
    if (replyTo != null) {
        email.addReplyTo(replyTo.getEmail(), replyTo.getName(), UTF_8);
    }

    final String bounceEmailAddress = msg.getBounceEmailAddress();
    if (bounceEmailAddress != null) {
        email.setBounceAddress(bounceEmailAddress);
    }

    email.setSubject(msg.getSubject());

    final String languageId = msg.getRecipient().getLanguage();
    if (languageId != null) {
        email.addHeader("Language", languageId);
        email.addHeader("Content-Language", languageId);
    }

    // add optional headers
    final EmailMessageHeaders headers = msg.getHeaders();
    if (headers != null) {
        for (final Map.Entry<String, String> header : headers.getHeaders().entrySet()) {
            email.addHeader(header.getKey(), header.getValue());
        }
    }

    // generate email body
    try {
        final MimeMultipart mm = new MimeMultipart("alternative; charset=UTF-8");

        final MimeBodyPart text = new MimeBodyPart();
        text.setContent(msg.getTextContent(), "text/plain; charset=UTF-8");
        mm.addBodyPart(text);

        final MimeBodyPart html = new MimeBodyPart();
        html.setContent(msg.getHtmlContent(), "text/html; charset=UTF-8");
        mm.addBodyPart(html);

        email.setContent(mm);
    } catch (MessagingException e) {
        throw new EmailException(e);
    }

}

From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java

private MultiPartEmail makeSimpleEmailWithAttachment(MsunMail mail, String charset) throws EmailException {
    MultiPartEmail email = new MultiPartEmail();
    email.setCharset(charset);
    email.setMsg(mail.getMessage());/*from   w ww.j a va  2  s  .  com*/
    return email;
}

From source file:eu.ggnet.dwoss.redtape.DocumentSupporterOperation.java

/**
 * This method send document to the e-Mail address that is in the customer set.
 * <p/>//w  ww  .j a va2s. c  o  m
 * @param document This is the Document that will be send.
 * @throws UserInfoException if the sending of the Mail is not successful.
 * @throws RuntimeException  if problems exist in the JasperExporter
 */
@Override
public void mail(Document document, DocumentViewType jtype) throws UserInfoException, RuntimeException {
    UiCustomer customer = customerService.asUiCustomer(document.getDossier().getCustomerId());

    String customerMailAddress = customerService.asCustomerMetaData(document.getDossier().getCustomerId())
            .getEmail();
    if (customerMailAddress == null) {
        throw new UserInfoException(
                "Kunde hat keine E-Mail Hinterlegt! Senden einer E-Mail ist nicht Mglich!");
    }

    String doctype = (jtype == DocumentViewType.DEFAULT ? document.getType().getName() : jtype.getName());

    try (InputStream is = mandator.getMailTemplateLocation().toURL().openStream();
            InputStreamReader templateReader = new InputStreamReader(is)) {
        String text = new MailDocumentParameter(customer.toTitleNameLine(), doctype)
                .eval(IOUtils.toString(templateReader));
        MultiPartEmail email = mandator.prepareDirectMail();

        email.setCharset("UTF-8");

        email.addTo(customerMailAddress);
        email.setSubject(document.getType().getName() + " | " + document.getDossier().getIdentifier());
        email.setMsg(text + mandator.getDefaultMailSignature());
        email.attach(new ByteArrayDataSource(JasperExportManager.exportReportToPdf(jasper(document, jtype)),
                "application/pdf"), "Dokument.pdf", "Das ist das Dokument zu Ihrem Aufrag als PDF.");
        for (MandatorMailAttachment mma : mandator.getDefaultMailAttachment()) {
            email.attach(mma.getAttachmentData().toURL(), mma.getAttachmentName(),
                    mma.getAttachmentDescription());
        }
        email.send();
    } catch (EmailException ex) {
        L.error("Error on Mail sending", ex);
        throw new UserInfoException("Das senden der Mail war nicht erfolgreich!\n" + ex.getMessage());
    } catch (IOException | JRException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!//from ww w. j a  v a2  s .  c  o m
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:eu.ggnet.dwoss.mandator.api.value.Mandator.java

/**
 * Prepares a eMail to be send direct over the mandator smtp configuration.
 * The email is missing: to, subject, message and optional attachments.
 *
 * @return the email/*ww w  .j a  va 2 s . c o m*/
 * @throws EmailException if something is wrong in the subsystem.
 */
public MultiPartEmail prepareDirectMail() throws EmailException {
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(smtpConfiguration.getHostname());
    email.addBcc(company.getEmail());
    email.setFrom(company.getEmail(), company.getEmailName());
    email.setAuthentication(smtpConfiguration.getSmtpAuthenticationUser(),
            smtpConfiguration.getSmtpAuthenticationPass());
    email.setStartTLSEnabled(false);
    email.setSSLCheckServerIdentity(false);
    email.setSSLOnConnect(false);
    email.setCharset(smtpConfiguration.getCharset());
    return email;
}

From source file:br.com.hslife.catu.service.EmailService.java

/**
 * envia email com arquivo anexo/*from   www  .  ja  v a2  s  . c  om*/
 * @throws EmailException
 */
public void enviaEmailComAnexo(String nomeRementente, String emailRemetente, String nomeDestinatario,
        String emailDestinatario, String assunto, StringBuilder mensagem, List<String> anexos)
        throws EmailException, MalformedURLException {

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.hslife.com.br"); // o servidor SMTP para envio do e-mail
    email.addTo(emailDestinatario, nomeDestinatario); //destinatrio
    email.setFrom(emailRemetente, nomeRementente); // remetente
    email.setSubject(assunto); // assunto do e-mail
    email.setMsg(mensagem.toString()); //conteudo do e-mail
    email.setAuthentication("realimoveis@hslife.com.br", "real123");
    email.setCharset("UTF8");
    //email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);
    // adiciona arquivo(s) anexo(s)
    EmailAttachment anexo = new EmailAttachment();
    for (String arquivo : anexos) {
        anexo.setPath("/home/hslife/" + arquivo); //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt)
        anexo.setDisposition(EmailAttachment.ATTACHMENT);
        anexo.setName(arquivo);
        email.attach(anexo);
        anexo = new EmailAttachment();
    }
    // Envia o e-mail
    email.send();
}

From source file:dk.cubing.liveresults.action.admin.ScoresheetAction.java

/**
 * @return// www. jav  a2 s . c  om
 */
public String exportResults() {
    if (competitionId != null) {
        Competition competitionTemplate = getCompetitionService().find(competitionId);
        if (competitionTemplate == null) {
            log.error("Could not load competition: {}", competitionId);
            return Action.ERROR;
        }
        setCompetition(competitionTemplate);

        try {
            // load WCA template from file
            InputStream is = ServletActionContext.getServletContext()
                    .getResourceAsStream(getSpreadSheetFilename());
            Workbook workBook;
            workBook = WorkbookFactory.create(is);
            is.close();

            // build special registration sheet
            generateRegistrationSheet(workBook, getCompetition());

            // build result sheets
            generateResultSheets(workBook, getCompetition());

            // set default selected sheet
            workBook.setActiveSheet(workBook.getSheetIndex(SHEET_TYPE_REGISTRATION));

            // email or just output to pdf?
            if (isSubmitResultsToWCA()) {
                // write workbook to temp file
                File temp = File.createTempFile(getCompetitionId(), ".xls");
                temp.deleteOnExit();
                OutputStream os = new FileOutputStream(temp);
                workBook.write(os);
                os.close();

                // Create the attachment
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(temp.getPath());
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName(getCompetitionId() + ".xls");

                // send email
                MultiPartEmail email = new MultiPartEmail();
                email.setCharset(Email.ISO_8859_1);
                email.setHostName(getText("email.smtp.server"));
                if (!getText("email.username").isEmpty() && !getText("email.password").isEmpty()) {
                    email.setAuthentication(getText("email.username"), getText("email.password"));
                }
                email.setSSL("true".equals(getText("email.ssl")));
                email.setSubject("Results from " + getCompetition().getName());
                email.setMsg(getText("admin.export.message",
                        new String[] { getCompetition().getName(), getCompetition().getOrganiser() }));
                email.setFrom(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addTo(getText("admin.export.resultsteamEmail"), getText("admin.export.resultsteam"));
                email.addCc(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addCc(getCompetition().getWcaDelegateEmail(), getCompetition().getWcaDelegate());
                email.attach(attachment);
                email.send();

                return Action.SUCCESS;
            } else {
                // output generated spreadsheet
                log.debug("Ouputting generated workbook");
                out = new ByteArrayOutputStream();
                workBook.write(out);
                out.close();

                return "spreadsheet";
            }
        } catch (InvalidFormatException e) {
            log.error("Spreadsheet template are using an unsupported format.", e);
        } catch (IOException e) {
            log.error("Error reading spreadsheet template.", e);
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
        }
        return Action.ERROR;
    } else {
        return Action.INPUT;
    }
}

From source file:ninja.postoffice.commonsmail.CommonsmailHelperImpl.java

@Override
public void doPopulateMultipartMailWithContent(MultiPartEmail multiPartEmail, Mail mail)
        throws AddressException, EmailException {

    String charset = "utf-8";
    if (mail.getCharset() != null) {
        charset = mail.getCharset();/*ww w. j  av a 2s.c  o m*/
    }

    multiPartEmail.setCharset(charset);

    String subject = "";
    if (mail.getSubject() != null) {
        subject = mail.getSubject();
    }

    multiPartEmail.setSubject(subject);

    if (mail.getFrom() != null) {

        Tuple<String, String> from = createValidEmailFromString(mail.getFrom());

        if (from.y != null) {
            multiPartEmail.setFrom(from.x, from.y);
        } else {
            multiPartEmail.setFrom(from.x);
        }

    }

    if (mail.getTos() != null) {
        if (!mail.getTos().isEmpty()) {
            List<Tuple<String, String>> emails = createListOfAddresses(mail.getTos());
            for (Tuple<String, String> email : emails) {

                if (email.y != null) {
                    multiPartEmail.addTo(email.x, email.y);
                } else {
                    multiPartEmail.addTo(email.x);
                }

            }
        }
    }

    if (mail.getReplyTo() != null) {
        if (!mail.getReplyTo().isEmpty()) {
            List<Tuple<String, String>> emails = createListOfAddresses(mail.getReplyTo());
            for (Tuple<String, String> email : emails) {
                multiPartEmail.addReplyTo(email.x, email.y);
            }
        }
    }

    if (mail.getCcs() != null) {
        if (!mail.getCcs().isEmpty()) {
            List<Tuple<String, String>> emails = createListOfAddresses(mail.getCcs());
            for (Tuple<String, String> email : emails) {
                multiPartEmail.addCc(email.x, email.y);
            }
        }
    }

    if (mail.getBccs() != null) {
        if (!mail.getBccs().isEmpty()) {
            List<Tuple<String, String>> emails = createListOfAddresses(mail.getBccs());
            for (Tuple<String, String> email : emails) {
                multiPartEmail.addBcc(email.x, email.y);
            }
        }
    }

    if (mail.getHeaders() != null) {
        multiPartEmail.setHeaders(mail.getHeaders());
    }

}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Sends the attachment of an email./*from   w  ww . j av  a 2 s  .com*/
 */
public static boolean sendEmailAttachment(String from, String to_adrList, String cc_adrList, String subject,
        String txt, byte[] att_data, String att_name, String att_type) {
    boolean result = true;

    try {
        // Create the email message
        MultiPartEmail email = new MultiPartEmail();
        email.setCharset("UTF-8");
        email.setHostName(getSmtpMailRelayHostname());
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(txt);

        // bounces and reply forwarded to assistance@agnitas.de
        email.addReplyTo("assistance@agnitas.de");
        email.setBounceAddress("assistance@agnitas.de");

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            for (InternetAddress singleAdr : toAddresses) {
                email.addTo(singleAdr.getAddress());
            }
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            for (InternetAddress singleAdr : ccAddresses) {
                email.addCc(singleAdr.getAddress());
            }
        }

        // Create and add the attachment
        ByteArrayDataSource attachment = new ByteArrayDataSource(att_data, att_type);
        email.attach(attachment, att_name, "EMM-Report");

        // send the email
        email.send();
    } catch (Exception e) {
        logger.error("sendEmailAttachment: " + e.getMessage(), e);
        result = false;
    }

    return result;
}