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

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

Introduction

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

Prototype

MultiPartEmail

Source Link

Usage

From source file:au.edu.ausstage.utils.EmailManager.java

/**
 * A method for sending a simple email message
 *
 * @param subject the subject of the message
 * @param message the text of the message
 * @param attachmentPath the path to the attachment
 *
 * @return true, if and only if, the email is successfully sent
 *//*from  w  w w  . j a va2 s  .  co m*/
public boolean sendMessageWithAttachment(String subject, String message, String attachmentPath) {

    // check the input parameters
    if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false
            || InputUtils.isValid(attachmentPath) == false) {
        throw new IllegalArgumentException("All parameters are required");
    }

    try {
        // define helper variables
        MultiPartEmail email = new MultiPartEmail();

        // configure the instance of the email class
        email.setSmtpPort(options.getPortAsInt());

        // define authentication if required
        if (InputUtils.isValid(options.getUser()) == true) {
            email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword()));
        }

        // turn on / off debugging
        email.setDebug(DEBUG);

        // set the host name
        email.setHostName(options.getHost());

        // set the from email address
        email.setFrom(options.getFromAddress());

        // set the subject
        email.setSubject(subject);

        // set the message
        email.setMsg(message);

        // set the to address
        String[] addresses = options.getToAddress().split(":");

        for (int i = 0; i < addresses.length; i++) {
            email.addTo(addresses[i]);
        }

        // set the security options
        if (options.getTLS() == true) {
            email.setTLS(true);
        }

        if (options.getSSL() == true) {
            email.setSSL(true);
        }

        // build the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(attachmentPath);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sanitised Twitter Message");
        attachment.setName("twitter-message.txt");

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

        // send the email
        email.send();

    } catch (EmailException ex) {
        if (DEBUG) {
            System.err.println("ERROR: Sending of email failed.\n" + ex.toString());
        }

        return false;
    }
    return true;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassedJava(String from, String grupSephora, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {// w  w  w .ja va2 s .  c  o m

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(filename);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);

        attachment.setDescription("rezultat TC-uri");
        attachment.setName("rezultat TC-uri");

        MultiPartEmail email = new MultiPartEmail();

        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);

        email.setAuthenticator(new DefaultAuthenticator("anda.cristea@contentspeed.ro", "testtest"));
        email.setSSLOnConnect(true);

        email.addTo(grupSephora);

        //email.addBcc(grupSephora);
        email.setFrom(from, "Teste Automate");
        email.setSubject(subject);
        email.setMsg(subject);

        // add the attachment
        //email.attach(attachment);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        email.setContent(writer.toString(), "text/html");
        email.attach(attachment);

        email.send();
        writer.close();
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        ex.printStackTrace();

    }

}

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

/**
 * DOCUMENT ME!/*from   w w w. ja  v  a 2 s.  c  om*/
 *
 * @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:br.com.hslife.imobiliaria.service.EmailService.java

/**
 * envia email com arquivo anexo/*w  w w . java2s . c  o 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.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 w w  .j  a v  a  2s . c o  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:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*w  w  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, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, 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 = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        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) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

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

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

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

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        String mid = getId();

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        } else {
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            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.saveSentMessage(mid, mime, user);

        Thread thread = new Thread(new SendMessageThread(email));
        thread.start();
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:info.toegepaste.controller.StudentController.java

public void stuurMail(Student student) {
    //create attachment
    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription("PDF met uw punten");
    attachment.setName(student.getFirstname() + " " + student.getLastname() + " scores");

    MultiPartEmail email = new MultiPartEmail();
    email.setStartTLSEnabled(true);/*from  w w w.  j  a  va2 s. co  m*/
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);
    email.setAuthentication("bitmescoretracker@gmail.com", "bitmeScore");
    try {
        email.setFrom("bitmescoretracker@gmail.com", "bitme Scoretracker");
        email.setSubject("Gevraagde scores , scoretracker");
        email.setMsg("In de bijlage vind u een pdf met uw scores");
        email.attach(attachment);
        email.send();
    } catch (EmailException ex) {
    }
}

From source file:binky.reportrunner.engine.utils.impl.EmailHandlerImpl.java

public void sendAlertEmail(String destinationEmail, String fromEmail, String smtpServer, String jobName,
        String groupName, boolean success, Date finishTime) throws EmailException, IOException {
    logger.debug("sending email to: " + destinationEmail + " on host " + smtpServer);
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(smtpServer);/*  w  w w. j  av a2s.  co  m*/
    email.setDebug(debug);
    for (String toEmail : destinationEmail.split(",")) {
        email.addTo(toEmail.trim());
    }
    email.setFrom(fromEmail);

    if (success) {
        email.setSubject("Success message for: " + jobName + " [" + groupName + "]");

        email.setMsg("Job completed successfully at " + finishTime);

    } else {
        email.setSubject("Failure message for: " + jobName + " [" + groupName + "]");

        email.setMsg("Job completed with error(s) at " + finishTime);

    }

    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  a va2  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:annis.gui.ReportBugWindow.java

private boolean sendBugReport(String bugEMailAddress, byte[] screenImage, String imageMimeType) {
    MultiPartEmail mail = new MultiPartEmail();
    try {//w  ww . ja  va2  s.  c  o m
        // server setup
        mail.setHostName("localhost");

        // content of the mail
        mail.addReplyTo(form.getField("email").getValue().toString(),
                form.getField("name").getValue().toString());
        mail.setFrom(bugEMailAddress);
        mail.addTo(bugEMailAddress);

        mail.setSubject("[ANNIS BUG] " + form.getField("summary").getValue().toString());

        // TODO: add info about version etc.
        StringBuilder sbMsg = new StringBuilder();

        sbMsg.append("Reporter: ").append(form.getField("name").getValue().toString()).append(" (")
                .append(form.getField("email").getValue().toString()).append(")\n");
        sbMsg.append("Version: ").append(VaadinSession.getCurrent().getAttribute("annis-version")).append("\n");
        sbMsg.append("URL: ").append(UI.getCurrent().getPage().getLocation().toASCIIString()).append("\n");

        sbMsg.append("\n");

        sbMsg.append(form.getField("description").getValue().toString());
        mail.setMsg(sbMsg.toString());

        if (screenImage != null) {
            try {
                mail.attach(new ByteArrayDataSource(screenImage, imageMimeType), "screendump.png",
                        "Screenshot of the browser content at time of bug report");
            } catch (IOException ex) {
                log.error(null, ex);
            }

            File logfile = new File(VaadinService.getCurrent().getBaseDirectory(),
                    "/WEB-INF/log/annis-gui.log");
            if (logfile.exists() && logfile.isFile() && logfile.canRead()) {
                mail.attach(new FileDataSource(logfile), "annis-gui.log",
                        "Logfile of the GUI (shared by all users)");
            }
        }

        mail.send();
        return true;

    } catch (EmailException ex) {
        Notification.show("E-Mail not configured on server",
                "If this is no Kickstarter version please ask the adminstrator of this ANNIS-instance for assistance. "
                        + "Bug reports are not available for ANNIS Kickstarter",
                Notification.Type.ERROR_MESSAGE);
        log.error(null, ex);
        return false;
    }
}