Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart MimeMultipart.

Prototype

public MimeMultipart() 

Source Link

Document

Default constructor.

Usage

From source file:org.fireflow.service.email.send.MailSenderImpl.java

/**
 * TODO ?//from   w  ww .j a v a 2  s.c  o m
 * @param mailSession
 * @param mailMessage
 * @return
 * @throws MessagingException 
 * @throws AddressException 
 * @throws ServiceInvocationException
 */
private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage)
        throws AddressException, MessagingException {
    MimeMessage mimeMsg = new MimeMessage(mailSession);

    //1?set from
    //Assert.notNull(mailMessage.getFrom(),"From address must not be null");
    mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom()));

    //2?set mailto
    List<String> mailToList = mailMessage.getMailToList();
    InternetAddress[] addressList = new InternetAddress[mailToList.size()];
    for (int i = 0; i < mailToList.size(); i++) {
        String mailTo = mailToList.get(i);
        addressList[i] = new InternetAddress(mailTo);
    }
    mimeMsg.setRecipients(Message.RecipientType.TO, addressList);

    //3?set cc
    List<String> ccList = mailMessage.getCarbonCopyList();
    if (ccList != null && ccList.size() > 0) {
        addressList = new InternetAddress[ccList.size()];
        for (int i = 0; i < ccList.size(); i++) {
            String mailTo = ccList.get(i);
            addressList[i] = new InternetAddress(mailTo);
        }
        mimeMsg.setRecipients(Message.RecipientType.CC, addressList);
    }

    //4?set subject
    mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset());

    //5?set sentDate
    if (this.sentDate != null) {
        mimeMsg.setSentDate(sentDate);
    }

    //6?set email body
    Multipart multiPart = new MimeMultipart();
    MimeBodyPart bp = new MimeBodyPart();
    if (mailMessage.getBodyIsHtml())
        bp.setContent(mailMessage.getBody(),
                CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset());
    else
        bp.setText(mailMessage.getBody(), mailServiceDef.getCharset());

    multiPart.addBodyPart(bp);
    mimeMsg.setContent(multiPart);

    //7?set attachment
    //TODO ?

    return mimeMsg;
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format)
        throws MessagingException {

    // Create the message part
    BodyPart messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    DataSource source = null;/*w  ww  . j  av  a 2  s.  c o  m*/

    // Part two is attachment
    if (outputStream instanceof ByteArrayOutputStream) {
        source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray());
    }
    messageBodyPart = new MimeBase64BodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setDisposition(Part.ATTACHMENT);

    messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\"");

    String contentType = format.getContentType() != null ? format.getContentType()
            : Constants.DEFAULT_CONTENT_TYPE;
    if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction());
        }
    }

    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
        if (messageContext.getSoapAction() != null) {
            messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()
                    + " ; action=\"" + messageContext.getSoapAction() + "\"");
        }
    } else {
        messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding());
    }

    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);

}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/*  w  w  w .  j  a va2  s. co m*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment3() throws MessagingException, IOException {
    Mailet mailet = initMailet();/*from   www .  j  a v a2 s  . c  o  m*/

    // System.setProperty("mail.mime.decodefilename", "true");

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    // message.writeTo(System.out);
    // System.out.println("--------------------------\n\n\n");

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();
    // System.out.println("--------------------------\n\n\n");
    // System.out.println(name);

    Assert.assertTrue(name.startsWith("e_Pubblicita_e_vietata_Milano9052"));

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from  www . java 2s. com*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:org.viafirma.util.SendMailUtil.java

public MultiPartEmail buildMessage(String subject, String mailTo, String texto, String htmlTexto, String alias,
        String password) throws ExcepcionErrorInterno, ExcepcionCertificadoNoEncontrado {

    try {/*from  w w  w .  ja v a 2  s. co m*/
        // 1.- Preparamos el certificado
        // Recuperamos la clave privada asociada al alias
        PrivateKey privateKey = KeyStoreLoader.getPrivateKey(alias, password);
        if (privateKey == null) {
            throw new ExcepcionCertificadoNoEncontrado(
                    "No existe una clave privada para el alias  '" + alias + "'");
        }
        if (log.isDebugEnabled())
            log.info("Firmando el documento con el certificado " + alias);

        // Recuperamos el camino de confianza asociado al certificado
        List<Certificate> chain = KeyStoreLoader.getCertificateChain(alias);

        // Obtenemos los datos del certificado utilizado.
        X509Certificate certificadoX509 = (X509Certificate) chain.get(0);
        CertificadoGenerico datosCertificado = CertificadoGenericoFactory.getInstance()
                .generar(certificadoX509);
        String emailFrom = datosCertificado.getEmail();
        String emailFromDesc = datosCertificado.getCn();
        if (StringUtils.isEmpty(emailFrom)) {
            log.warn("El certificado indicado no tiene un email asociado, No es vlido para firmar emails"
                    + datosCertificado);
            throw new ExcepcionCertificadoNoEncontrado(
                    "El certificado indicado no tiene un email asociado, No es vlido para firmar emails.");
        }

        CertStore certificadosYcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(chain), BouncyCastleProvider.PROVIDER_NAME);

        // 2.- Preparamos el mail
        MimeBodyPart bodyPart = new MimeBodyPart();
        MimeMultipart dataMultiPart = new MimeMultipart();

        MimeBodyPart msgHtml = new MimeBodyPart();
        if (StringUtils.isNotEmpty(htmlTexto)) {
            msgHtml.setContent(htmlTexto, Email.TEXT_HTML + "; charset=UTF-8");
        } else {
            msgHtml.setContent("<p>" + htmlTexto + "</p>", Email.TEXT_PLAIN + "; charset=UTF-8");
        }

        // create the message we want signed
        MimeBodyPart mensajeTexto = new MimeBodyPart();
        if (StringUtils.isNotEmpty(texto)) {
            mensajeTexto.setText(texto, "UTF-8");
        } else if (StringUtils.isEmpty(texto)) {
            mensajeTexto.setText(CadenaUtilities.cleanHtml(htmlTexto), "UTF-8");
        }
        dataMultiPart.addBodyPart(mensajeTexto);
        dataMultiPart.addBodyPart(msgHtml);

        bodyPart.setContent(dataMultiPart);

        // Crea el nuevo mensaje firmado
        MimeMultipart multiPart = createMultipartWithSignature(privateKey, certificadoX509, certificadosYcrls,
                bodyPart);

        // Creamos el mensaje que finalmente sera enviadio.
        MultiPartEmail mail = createMultiPartEmail(subject, mailTo, emailFrom, emailFromDesc, multiPart,
                multiPart.getContentType());

        return mail;
    } catch (InvalidAlgorithmParameterException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (NoSuchProviderException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (MessagingException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (CertificateParsingException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (CertStoreException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (SMIMEException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    } catch (EmailException e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

/**
 * Se encarga de enviar el mensaje de correo electronico *
 *///from  w  w w . ja  v  a2  s. c  om
public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException {
    try {
        Session session;
        Properties properties = System.getProperties();
        properties.put("mail.host", emdto.getHost());
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.port", emdto.getPort());
        properties.put("mail.smtp.starttls.enable", emdto.getStarttls());
        if (emdto.getUser() != null && emdto.getPassword() != null) {
            properties.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emdto.getUser(), emdto.getPassword());
                }
            });
        } else {
            properties.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(properties);
        }

        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask()));
        message.setSubject(emdto.getSubject());

        for (String to : emdto.getToList()) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
        if (emdto.getCcList() != null) {
            for (String cc : emdto.getCcList()) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }
        if (emdto.getCcoList() != null) {
            for (String cco : emdto.getCcoList()) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco));
            }
        }

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage());
        multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (emdto.getFilePaths() != null) {
            for (String filePath : emdto.getFilePaths()) {
                File file = new File(filePath);
                if (file.exists()) {
                    dataSource = new FileDataSource(file);
                    bodyPart = new MimeBodyPart();
                    bodyPart.setDataHandler(new DataHandler(dataSource));
                    bodyPart.setFileName(file.getName());
                    multipart.addBodyPart(bodyPart);
                }
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception",
                ex);
        throw new BusinessException(ex);
    }
    return Boolean.TRUE;
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to       Email address of the receiver.
 * @param from     Email address of the sender, the mailbox account.
 * @param subject  Subject of the email.
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException/* w w w  .jav  a 2  s . c om*/
 */
protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from,
        Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject,
        String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    try {

        email.setFrom(from);

        if (to != null) {
            email.addRecipients(javax.mail.Message.RecipientType.TO,
                    to.toArray(new InternetAddress[to.size()]));
        }
        if (cc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.CC,
                    cc.toArray(new InternetAddress[cc.size()]));
        }
        if (bcc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.BCC,
                    bcc.toArray(new InternetAddress[bcc.size()]));
        }
        if (replyTo != null) {
            email.setReplyTo(new Address[] { replyTo });
        }

        email.setSubject(subject);

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/html");
        mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        if (attachments != null) {
            for (com.threewks.thundr.mail.Attachment attachment : attachments) {
                mimeBodyPart = new MimeBodyPart();

                BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry);
                renderer.render(attachment.view());
                byte[] data = renderer.getOutputAsBytes();
                String attachmentContentType = renderer.getContentType();
                String attachmentCharacterEncoding = renderer.getCharacterEncoding();

                populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType,
                        attachmentCharacterEncoding);

                multipart.addBodyPart(mimeBodyPart);
            }
        }

        email.setContent(multipart);
    } catch (MessagingException e) {
        Logger.error(e.getMessage());
        Logger.error(
                "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d",
                from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to),
                Transformers.InternetAddressesToString.from(cc),
                Transformers.InternetAddressesToString.from(bcc),
                replyTo == null ? "null" : replyTo.getAddress(),
                replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText,
                attachments == null ? 0 : attachments.size());
        throw new GmailException(e);
    }

    return email;
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;// www.ja  v a2  s .  co  m
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:pt.ist.fenix.api.SupportFormResource.java

private void sendEmail(String from, String subject, String body, SupportBean bean) {
    Properties props = new Properties();
    props.put("mail.smtp.host", Objects
            .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from ww  w  .jav a 2  s.c o  m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);

        Multipart multipart = new MimeMultipart();
        {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
        }

        if (!Strings.isNullOrEmpty(bean.attachment)) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType)));
            messageBodyPart.setFileName(bean.fileName);
            multipart.addBodyPart(messageBodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}