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

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

Introduction

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

Prototype

public Email addTo(final String email, final String name) throws EmailException 

Source Link

Document

Add a recipient TO to the email using the specified address and the specified personal name.

Usage

From source file:emailworkshop.EmailWorkshop.java

public static void enviaEmailComAnexo(String mailFrom, String senhaFrom, String emailTo, String nomeTo)
        throws EmailException {
    // cria o anexo 1.
    EmailAttachment anexo1 = new EmailAttachment();
    anexo1.setPath("Certificado.pdf"); //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt)
    anexo1.setDisposition(EmailAttachment.ATTACHMENT);
    anexo1.setDescription("anexo");
    anexo1.setName("Certificado.pdf");

    // configura o email
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail
    email.addTo(emailTo, nomeTo); //destinatrio
    email.setFrom(mailFrom, "UFPR"); // remetente
    email.setSubject("Certificado II Workshop de Inovao"); // assunto do e-mail
    email.setMsg("Segue anexo o Certificado de participaao no II Workshop, Obrigado pela presena! \n "
            + emailTo); //conteudo do e-mail
    email.setAuthentication(mailFrom, senhaFrom);
    email.setSmtpPort(465);//from   www  . j a  va 2  s.  c  o m
    email.setSSL(true);
    email.setTLS(true);
    // adiciona arquivo(s) anexo(s)
    email.attach(anexo1);
    // envia o email
    email.send();
}

From source file:de.xirp.mail.MailManager.java

/**
 * Transports the given {@link de.xirp.mail.Mail} via
 * a SMTP server.//  w  w  w .j  av  a  2  s . co  m
 * 
 * @param mail
 *            The mail to transport.
 * @throws EmailException
 *             if something is wrong with the given mail or the
 *             mail settings.
 * @see de.xirp.mail.Mail
 * @see de.xirp.mail.Contact
 * @see de.xirp.mail.Attachment
 */
private static void transport(Mail mail) throws EmailException {
    // Create the email message
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(PropertiesManager.getSmtpHost());
    email.setSmtpPort(PropertiesManager.getSmtpPort());

    if (PropertiesManager.isNeedsAuthentication()) {
        email.setAuthentication(PropertiesManager.getSmtpUser(),
                Util.decrypt(PropertiesManager.getSmtpPassword()));
    }

    for (Contact c : mail.getTo()) {
        email.addTo(c.getMail(), c.getFirstName() + " " + c.getLastName()); //$NON-NLS-1$
    }
    for (Contact c : mail.getCc()) {
        email.addCc(c.getMail(), c.getFirstName() + " " + c.getLastName()); //$NON-NLS-1$
    }

    email.setFrom(PropertiesManager.getNoReplyAddress(), Constants.APP_NAME);
    email.setSubject(mail.getSubject());
    email.setMsg(mail.getText() + I18n.getString(I18n.getString("MailManager.mail.footer", //$NON-NLS-1$
            Constants.LINE_SEPARATOR, Constants.BASE_NAME_MAJOR_VERSION)));

    // Create attachment
    for (Attachment a : mail.getAttachments()) {
        File file = a.getFile();
        EmailAttachment attachment = new EmailAttachment();

        if (file != null) {
            attachment.setPath(file.getPath());
        } else {
            File tmpFile = null;
            try {
                tmpFile = new File(Constants.TMP_DIR, a.getFileName());
                FileUtils.writeByteArrayToFile(tmpFile, a.getAttachmentFileContent());
                attachment.setPath(tmpFile.getPath());
            } catch (IOException e) {
                tmpFile = null;
            }
        }
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(a.getFileName());
        attachment.setName(a.getFileName());
        email.attach(attachment);
    }

    try {
        email.send();
    } catch (EmailException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        throw e;
    }
}

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

/**
 * envia email com arquivo anexo/*from w w w.j  a v  a  2s .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.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:br.com.hslife.catu.service.EmailService.java

/**
 * envia email com arquivo anexo/*  w ww  .  ja  va 2 s .  co  m*/
 * @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:Email.CommonsEmail.java

/**
 * envia email com arquivo anexo// ww  w. ja v  a 2  s .  c o  m
 *
 * @throws EmailException
 */
public void enviaEmailComAnexo() throws EmailException {

    // cria o anexo 1.
    EmailAttachment anexo1 = new EmailAttachment();
    //caminho do arquivo (RAIZ_PROJETO/teste/teste.txt)
    anexo1.setPath("teste/teste.txt");
    anexo1.setDisposition(EmailAttachment.ATTACHMENT);
    anexo1.setDescription("Exemplo de arquivo anexo");
    anexo1.setName("teste.txt");

    // cria o anexo 2.
    EmailAttachment anexo2 = new EmailAttachment();
    //caminho do arquivo (RAIZ_PROJETO/teste/teste2.jsp)
    anexo2.setPath("teste/teste2.jsp");
    anexo2.setDisposition(EmailAttachment.ATTACHMENT);
    anexo2.setDescription("Exemplo de arquivo anexo");
    anexo2.setName("teste2.jsp");

    // configura o email
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.gmail.com"); // o servidor SMTP para envio do e-mail
    email.addTo("teste@gmail.com", "Guilherme"); //destinatrio
    email.setFrom("facom.sisges@gmail.com", "SisGES"); // remetente
    email.setSubject("Teste -> Email com anexos"); // assunto do e-mail
    email.setMsg("Teste de Email utilizando commons-email"); //conteudo do e-mail
    email.setAuthentication("teste", "xxxxx");
    email.setSmtpPort(465);
    //email.setSSL(true);
    //email.setTLS(true);

    // adiciona arquivo(s) anexo(s)
    email.attach(anexo1);
    email.attach(anexo2);
    // envia o email
    email.send();
}

From source file:com.dominion.salud.pedicom.negocio.tools.MAILTest.java

@Ignore
@Test/*from  www .java2 s. com*/
public void send() {
    try {
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName(SMTP);
        email.setAuthenticator(new DefaultAuthenticator(USUARIO, PASSWORD));
        email.setDebug(true);
        email.setSmtpPort(PUERTO);
        email.setStartTLSEnabled(true);

        email.setSSLOnConnect(true);

        email.setFrom(FROM, FROM);
        email.addTo(TO, TO);
        email.setSubject("Correo de Prueba");
        email.attach(new File("/home/jcgonzalez/TMP/a.hl7"));

        email.send();
    } catch (Exception e) {
        logger.error(e.toString());
    }
}

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

/**
 * DOCUMENT ME!//from   ww  w .ja  va  2s  .co  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:dk.cubing.liveresults.action.admin.ScoresheetAction.java

/**
 * @return/*from www .  java2 s .  co  m*/
 */
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. ja va2  s. co 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.apache.niolex.common.mail.MultiPartMail.java

public static void main(String[] args) throws IOException, EmailException {
    // Create the attachment
    EmailAttachment attachment = new EmailAttachment();
    attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription("Apache logo");
    attachment.setName("Apache_logo.gif");

    // Create the email message
    MultiPartEmail email = new MultiPartEmail();
    email.setDebug(true);/* w  w w  . j a  v a2 s.  c om*/
    // Set email host
    email.setHostName("10.7.2.18");
    //        email.setAuthentication("nice_to_meet", "asf_logo_me");
    //        email.setSSL(true);
    // Set email from
    email.setFrom("lei.gao@renren-inc.com", "Commons Email");
    email.setBounceAddress("lei.gao@renren-inc.com");
    // Set email content
    email.addTo("jiyun.xie@renren-inc.com", "Jiyun Xie");
    email.addTo("lei.gao@renren-inc.com", "Lei Gao");
    email.setSubject("Foll Alert The Git test");
    email.setMsg("Here is Apache's logo, please enjoy it!");

    // add the attachment
    email.attach(attachment);

    // send the email
    email.send();
}