Example usage for javax.mail Multipart addBodyPart

List of usage examples for javax.mail Multipart addBodyPart

Introduction

In this page you can find the example usage for javax.mail Multipart addBodyPart.

Prototype

public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:com.enonic.esl.net.Mail.java

/**
 * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is
 * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance.
 * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p>
 *//* ww  w .j  av  a 2s . com*/
public void send() throws ESLException {
    // smtp server
    Properties smtpProperties = new Properties();
    if (smtpHost != null) {
        smtpProperties.put("mail.smtp.host", smtpHost);
        System.setProperty("mail.smtp.host", smtpHost);
    } else {
        smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST);
        System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST);
    }
    Session session = Session.getDefaultInstance(smtpProperties, null);

    try {
        // create message
        Message msg = new MimeMessage(session);
        // set from address
        InternetAddress addressFrom = new InternetAddress();
        if (from_email != null) {
            addressFrom.setAddress(from_email);
        }
        if (from_name != null) {
            addressFrom.setPersonal(from_name, ENCODING);
        }
        ((MimeMessage) msg).setFrom(addressFrom);

        if ((to.size() == 0 && bcc.size() == 0) || subject == null
                || (message == null && htmlMessage == null)) {
            LOG.error("Missing data. Unable to send mail.");
            throw new ESLException("Missing data. Unable to send mail.");
        }

        // set to:
        for (int i = 0; i < to.size(); ++i) {
            String[] recipient = to.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo);
        }

        // set bcc:
        for (int i = 0; i < bcc.size(); ++i) {
            String[] recipient = bcc.get(i);
            InternetAddress addressTo = null;
            try {
                addressTo = new InternetAddress(recipient[1]);
            } catch (Exception e) {
                System.err.println("exception on address: " + recipient[1]);
                continue;
            }
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo);
        }

        // set cc:
        for (int i = 0; i < cc.size(); ++i) {
            String[] recipient = cc.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo);
        }

        // Setting subject and content type
        ((MimeMessage) msg).setSubject(subject, ENCODING);

        if (message != null) {
            message = RegexpUtil.substituteAll("\\\\n", "\n", message);
        }

        // if there are any attachments, treat this as a multipart message.
        if (attachments.size() > 0) {
            BodyPart messageBodyPart = new MimeBodyPart();
            if (message != null) {
                ((MimeBodyPart) messageBodyPart).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler);
            }
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // add all attachments
            for (int i = 0; i < attachments.size(); ++i) {
                Object obj = attachments.get(i);
                if (obj instanceof String) {
                    System.err.println("attachment is String");
                    messageBodyPart = new MimeBodyPart();
                    ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING);
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof File) {
                    messageBodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource((File) obj);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof FileItem) {
                    FileItem fileItem = (FileItem) obj;
                    messageBodyPart = new MimeBodyPart();
                    FileItemDataSource fds = new FileItemDataSource(fileItem);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else {
                    // byte array
                    messageBodyPart = new MimeBodyPart();
                    ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING);
                    messageBodyPart.setDataHandler(new DataHandler(bads));
                    messageBodyPart.setFileName(bads.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            msg.setContent(multipart);
        } else {
            if (message != null) {
                ((MimeMessage) msg).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeMessage) msg).setDataHandler(dataHandler);
            }
        }

        // send message
        Transport.send(msg);
    } catch (AddressException e) {
        String MESSAGE_30 = "Error in email address: " + e.getMessage();
        LOG.warn(MESSAGE_30);
        throw new ESLException(MESSAGE_30, e);
    } catch (UnsupportedEncodingException e) {
        String MESSAGE_40 = "Unsupported encoding: " + e.getMessage();
        LOG.error(MESSAGE_40, e);
        throw new ESLException(MESSAGE_40, e);
    } catch (SendFailedException sfe) {
        Throwable t = null;
        Exception e = sfe.getNextException();
        while (e != null) {
            t = e;
            if (t instanceof SendFailedException) {
                e = ((SendFailedException) e).getNextException();
            } else {
                e = null;
            }
        }
        if (t != null) {
            String MESSAGE_50 = "Error sending mail: " + t.getMessage();
            throw new ESLException(MESSAGE_50, t);
        } else {
            String MESSAGE_50 = "Error sending mail: " + sfe.getMessage();
            throw new ESLException(MESSAGE_50, sfe);
        }
    } catch (MessagingException e) {
        String MESSAGE_50 = "Error sending mail: " + e.getMessage();
        LOG.error(MESSAGE_50, e);
        throw new ESLException(MESSAGE_50, e);
    }
}

From source file:org.etudes.jforum.util.mail.Spammer.java

/**
 * prepare attachment message//from w ww.j  av  a2s .c o m
 * @param addresses Addresses
 * @param params Message params
 * @param subject Message subject
 * @param messageFile Message file
 * @param attachments Attachments
 * @throws EmailException
 */
protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject,
        String messageFile, List attachments) throws EmailException {
    if (logger.isDebugEnabled())
        logger.debug("prepareAttachmentMessage with attachments entering.....");

    this.message = new MimeMessage(session);

    try {
        InternetAddress[] recipients = new InternetAddress[addresses.size()];

        String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);

        this.message.setSentDate(new Date());
        // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
        String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@"
                + ServerConfigurationService.getServerName() + ">";
        this.message.setFrom(new InternetAddress(from));
        this.message.setSubject(subject, charset);

        this.messageText = this.getMessageText(params, messageFile);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        String messagetype = "";

        // message
        if (messageFormat == MESSAGE_HTML) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(this.messageText, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(this.messageText, messagetype);
        }

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        // attachments
        Attachment attachment = null;
        Iterator iterAttach = attachments.iterator();
        while (iterAttach.hasNext()) {
            attachment = (Attachment) iterAttach.next();
            // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename();
            String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/"
                    + attachment.getInfo().getPhysicalFilename();

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filePath);
            try {
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getInfo().getRealFilename());

                multipart.addBodyPart(messageBodyPart);
            } catch (MessagingException e) {
                if (logger.isWarnEnabled())
                    logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e);
            }
        }

        message.setContent(multipart);

        int i = 0;
        for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) {
            recipients[i] = new InternetAddress((String) iter.next());
        }

        this.message.setRecipients(Message.RecipientType.TO, recipients);
    } catch (Exception e) {
        logger.warn(e);
        throw new EmailException(e);
    }
    if (logger.isDebugEnabled())
        logger.debug("prepareAttachmentMessage with attachments exiting.....");
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*  www .  j  a va2 s. c  om*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java

private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray)
        throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients",
            FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);

    final Sender sender = Bennu.getInstance().getSystemSender();

    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualizao");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    Multipart multipart = new MimeMultipart();

    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);//from w ww.  j av a  2 s. c  om

    Transport.send(message);
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public void attach(BodyPart createNewAttach) {
    try {//w  ww.j  av  a 2  s.com
        Object content = getMail().getMessage().getContent();
        if (content instanceof Multipart) {
            Multipart multi = (Multipart) content;
            multi.addBodyPart(createNewAttach);
        } else {
            Multipart multiPart = new MimeMultipart();
            multiPart.addBodyPart(createNewAttach);
            getMail().getMessage().setContent(multiPart);
        }
        getMail().getMessage().saveChanges();
    } catch (Exception e) {
        log.error("Could not attach html for the email. EmailId: " + getMessagePlatformId() + " - "
                + e.getClass().getName() + " - " + e.getMessage());
        throw new RuntimeException("Could not attach html for email " + getMessagePlatformId());
    }
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

@Test
public void sendingMailSynchronouslyValidMailWithReplyTo() throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name");
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content).setReplyToRequired();

    // Sending mail
    mailSending.sendSynchronously();//from   w ww .  j  ava 2 s.c  o  m

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(true));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend);
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

@Test
public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues()
        throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM);
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content);//from  ww  w  .  ja v  a2  s  . com

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(false));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend);
}

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

@Test
public void sendingMailSynchronouslyValidMailWithReplyTo(GreenMailOperations mail) throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name");
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content).setReplyToRequired();

    // Sending mail
    mailSending.sendSynchronously();/*w  ww  . ja  va  2  s.c  o m*/

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(true));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend, mail);
}

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

@Test
public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues(
        GreenMailOperations mail) throws Exception {
    MailAddress senderEmail = MailAddress.eMail(COMMON_FROM);
    MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name");
    String subject = "A subject";
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE);
    content.addBodyPart(mimeBodyPart);
    MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject)
            .withContent(content);/*from w  w w  .j  av a  2  s  .co  m*/

    // Sending mail
    mailSending.sendSynchronously();

    // Verifying sent data
    MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend;
    assertThat(mailToSend.getFrom(), is(senderEmail));
    assertThat(mailToSend.getTo(), hasItem(receiverEmail));
    assertThat(mailToSend.getSubject(), is(subject));
    assertThat(mailToSend.getContent().isHtml(), is(true));
    assertThat(mailToSend.getContent().toString(), is(content.toString()));
    assertThat(mailToSend.isReplyToRequired(), is(false));
    assertThat(mailToSend.isAsynchronous(), is(false));
    assertMailSent(mailToSend, mail);
}

From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java

/**
 * Sends email with attachments//from   w  w  w.j a  v  a 2 s. c  o  m
 * 
 * @param from
 *        The address this message is to be listed as coming from.
 * @param to
 *        The address(es) this message should be sent to.
 * @param subject
 *        The subject of this message.
 * @param content
 *        The body of the message.
 * @param headerToStr
 *        If specified, this is placed into the message header, but "to" is used for the recipients.
 * @param replyTo
 *        If specified, this is the reply to header address(es).
 * @param additionalHeaders
 *        Additional email headers to send (List of String). For example, content type or forwarded headers (may be null)        
 * @param messageAttachments
 *         Message attachments
 */
protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject,
        String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders,
        List<EmailAttachment> emailAttachments) {
    if (testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments);
        return;
    }

    if (smtp == null || smtp.trim().length() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMailWithAttachments: smtp not set");
        }
        return;
    }

    if (from == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: from is needed to send email");
        }
        return;
    }

    if (to == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: to is needed to send email");
        }
        return;
    }

    if (content == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: content is needed to send email");
        }
        return;
    }

    if (emailAttachments == null || emailAttachments.size() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: emailAttachments are needed to send email with attachments");
        }
        return;
    }

    try {
        if (session == null) {
            if (logger.isWarnEnabled()) {
                logger.warn("mail session is null");
            }
            return;

        }
        MimeMessage message = new MimeMessage(session);

        // default charset
        String charset = "UTF-8";

        message.setSentDate(new Date());
        message.setFrom(from);
        message.setSubject(subject, charset);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        // Content-Type: text/plain; text/html;
        String contentType = null, contentTypeValue = null;

        if (additionalHeaders != null) {
            for (String header : additionalHeaders) {
                if (header.toLowerCase().startsWith("content-type:")) {
                    contentType = header;

                    contentTypeValue = contentType.substring(
                            contentType.indexOf("content-type:") + "content-type:".length(),
                            contentType.length());
                    break;
                }
            }
        }

        // message
        String messagetype = "";
        if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        }

        //messageBodyPart.setContent(content, "text/html; charset="+ charset);

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        String jforumAttachmentStoreDir = serverConfigurationService()
                .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR);
        if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) {
            if (logger.isWarnEnabled()) {
                logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR
                        + ") property is not set in sakai.properties ");
            }
        } else {
            // attachments
            for (EmailAttachment emailAttachment : emailAttachments) {

                String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName();

                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filePath);
                try {
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(emailAttachment.getRealFileName());

                    multipart.addBodyPart(messageBodyPart);
                } catch (MessagingException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Error while attaching attachments: " + e, e);
                    }
                }
            }
        }

        message.setContent(multipart);

        Transport.send(message, to);

    } catch (MessagingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: Error in sending email: " + e, e);
        }
    }
}