Example usage for javax.mail.internet MimeMessage setFrom

List of usage examples for javax.mail.internet MimeMessage setFrom

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

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

/**
 * Sends email with attachments//from   w w  w.ja va2 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);
        }
    }
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w  .j av  a 2s  . com
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendEmailMessageUser(final EmailMessageUser emailMessageUser) {
    try {
        if (!StringUtils.isBlank(emailMessageUser.getUser().getMail())) {
            //            SimpleMailMessage message = new SimpleMailMessage();
            //            message.setFrom(getMailFrom());
            //            message.setTo(emailMessageUser.getUser().getMail());
            //            message.setSubject(emailMessageUser.getSubject());
            //            message.setText(emailMessageUser.getBody());

            MimeMessagePreparator preparator = new MimeMessagePreparator() {

                @Override
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    mimeMessage.setFrom(new InternetAddress(getMailFrom()));
                    mimeMessage.setRecipient(Message.RecipientType.TO,
                            new InternetAddress(emailMessageUser.getUser().getMail()));
                    mimeMessage.setSubject(emailMessageUser.getSubject());
                    mimeMessage.setText(emailMessageUser.getBody(), "utf-8", "html");
                }
            };

            getJavaMailSender().send(preparator);
            emailMessageUser.setMailSended(Boolean.TRUE);
            emailMessageUser.setMailSendedDate(new Date());
            getEmailMessageUserDAO().merge(emailMessageUser);
        } else {
            logger.error("Email message not sended for user " + emailMessageUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + emailMessageUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

@Override
public Message sendMail(AppockMail appockMail) throws MessagingException {

    if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) {
        log.warn("Mail non envoy, liste des destinataires vide : " + appockMail);
        return null;
    }// w w  w  . ja v a 2  s  .  c o m

    MimeMessage msg = new MimeMessage(mailServer);
    msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom());

    String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] ";
    msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail());

    StringBuilder infoAdditionnelle = new StringBuilder();

    for (InternetAddress adresse : appockMail.getListeDestinataire()) {
        if (isModeProduction()) {
            // on est en production, envoi rel de mail au destinataire
            msg.addRecipient(Message.RecipientType.TO, adresse);
        } else {
            // en test, on envoie le mail  la personne connecte
            InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur();
            if (adresseTesteur != null) {
                msg.addRecipient(Message.RecipientType.TO, adresseTesteur);
            }
            List<String> listeAdresseMail = new ArrayList<>();
            for (InternetAddress internetAddress : appockMail.getListeDestinataire()) {
                listeAdresseMail.add(internetAddress.getAddress());
            }
            infoAdditionnelle.append("En production cet email serait envoy vers ")
                    .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>");
            break;
        }
    }

    String contenuFinal = "";
    if (!StringUtils.isBlank(infoAdditionnelle.toString())) {
        contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>";
    }

    contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>"
            + configService.getPiedDeMail();

    gereBonLivraisonDansMail(appockMail, msg, contenuFinal);

    if (!ArrayUtils.isEmpty(msg.getAllRecipients())) {
        Transport.send(msg);
    }

    return msg;
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public boolean sendSystemEmail(String to, String subject, String messageText) {

    boolean sent = false;
    String rootDataverseName = dataverseService.findRootDataverse().getName();
    String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing",
            Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName)));
    logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body);
    try {/*from  w  w w . ja va 2s  .com*/
        MimeMessage msg = new MimeMessage(session);
        InternetAddress systemAddress = getSystemAddress();
        if (systemAddress != null) {
            msg.setFrom(systemAddress);
            msg.setSentDate(new Date());
            String[] recipientStrings = to.split(",");
            InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
            for (int i = 0; i < recipients.length; i++) {
                try {
                    recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset);
                } catch (UnsupportedEncodingException ex) {
                    logger.severe(ex.getMessage());
                }
            }
            msg.setRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject, charset);
            msg.setText(body, charset);
            try {
                Transport.send(msg, recipients);
                sent = true;
            } catch (SMTPSendFailedException ssfe) {
                logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)");
            }
        } else {
            logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set ("
                    + Key.SystemEmail + " setting).");
        }
    } catch (AddressException ae) {
        logger.warning("Failed to send mail to " + to);
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        logger.warning("Failed to send mail to " + to);
        me.printStackTrace(System.out);
    }
    return sent;
}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }//from   w w  w  .j av  a 2  s .c  om
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateNotAddUser() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailetConfig.setInitParameter("addUser", "false");

    mailet.init(mailetConfig);//from   w ww  .  ja  v a2 s  .  c  o  m

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    String from = "from@example.com";
    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:org.tightblog.service.EmailService.java

/**
 * This method is used to send an HTML Message
 *
 * @param from    e-mail address of sender
 * @param to      e-mail address(es) of recipients
 * @param subject subject of e-mail//from   w  w w.j av  a 2s .c  om
 * @param content the body of the e-mail
 */
private void sendMessage(String from, String[] to, String[] cc, String subject, String content) {
    try {
        MimeMessage message = mailSender.createMimeMessage();

        // n.b. any default from address is expected to be determined by caller.
        if (!StringUtils.isEmpty(from)) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            log.debug("e-mail from: {}", sentFrom);
        }

        if (to != null) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress(to[i]);
                log.debug("sending e-mail to: {}", to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress(cc[i]);
                log.debug("copying e-mail to: {}", cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }

        message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
        message.setContent(content, "text/html; charset=utf-8");
        message.setSentDate(new java.util.Date());

        // First collect all the addresses together.
        boolean bFailedToSome = false;
        SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            mailSender.send(message);
        } catch (MailAuthenticationException | MailSendException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);
        }

        if (bFailedToSome) {
            throw sendex;
        }
    } catch (MessagingException e) {
        log.error("ERROR: Problem sending email with subject {}", subject, e);
    }
}

From source file:fsi_admin.JSmtpConn.java

private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY,
        StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart,
        MimeMultipart multipart) {//from  w w w  . j av a2s .  c om
    // Create a message with the specified information. 
    try {
        mmsg.setFrom(new InternetAddress(FROM));
        mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        mmsg.setSubject(SUBJECT);
        messagebodypart.setContent(BODY, MIMETYPE);
        multipart.addBodyPart(messagebodypart);
        return true;
    } catch (AddressException e) {
        e.printStackTrace();
        msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage());
        return false;
    } catch (MessagingException e) {
        e.printStackTrace();
        msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage());
        return false;
    }
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }// w w  w  . jav a2  s  . c  om
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

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

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined/*from w  w w .  ja v a  2  s . c  om*/
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale);
    final String html = composeDeclineMailMessage(team, locale, "html");
    final String plainText = composeDeclineMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}