Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {//  w w w.j ava  2  s . co  m
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

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//from w ww. ja va  2s . com
 */
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:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from  w  w  w .j  a v  a2 s  .  c  om
 *
 * @param from DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param subjectPrefix DOCUMENT ME!
 * @param subjectSuffix DOCUMENT ME!
 * @param msgText DOCUMENT ME!
 * @param message DOCUMENT ME!
 * @param session DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 * @throws IllegalArgumentException DOCUMENT ME!
 */
public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix,
        String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception {
    if (from == null) {
        throw new IllegalArgumentException("from addres cannot be null.");
    }

    if ((to == null) || (to.length <= 0)) {
        throw new IllegalArgumentException("to addres cannot be null.");
    }

    if (message == null) {
        throw new IllegalArgumentException("to message cannot be null.");
    }

    try {
        //Create the message
        MimeMessage newMessage = new MimeMessage(session);

        StringBuffer buffer = new StringBuffer();

        if (subjectPrefix != null) {
            buffer.append(subjectPrefix);
        }

        if (message.getSubject() != null) {
            buffer.append(message.getSubject());
        }

        if (subjectSuffix != null) {
            buffer.append(subjectSuffix);
        }

        if (buffer.length() > 0) {
            newMessage.setSubject(buffer.toString());
        }

        newMessage.setFrom(from);
        newMessage.addRecipients(Message.RecipientType.TO, to);

        //Create your new message part
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(msgText);

        //Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);

        //Create and fill part for the forwarded content
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2.setDataHandler(message.getDataHandler());

        //Add part to multi part
        multipart.addBodyPart(messageBodyPart2);

        //Associate multi-part with message
        newMessage.setContent(multipart);

        newMessage.saveChanges();

        return newMessage;
    } finally {
    }
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }//from   w  w  w .j  av a2  s. co  m
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;/*from  ww w .  ja v  a2 s  .  co m*/
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

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  .ja  va  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:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;/*from w  ww  .ja  va 2s  .com*/
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Sends an email in the correspondent type.
 *//*from w  w  w. j  a va  2s .  c  o m*/
public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject,
        String body_text, String body_html, int mailtype, String charset) {
    try {
        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("system.mail.host", getSmtpMailRelayHostname());
        Session session = Session.getDefaultInstance(props, null);
        // session.setDebug(debug);

        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from_adr));
        msg.setSubject(subject, charset);
        msg.setSentDate(new Date());

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.CC, ccAddresses);
        }

        switch (mailtype) {
        case 0:
            msg.setText(body_text, charset);
            break;

        case 1:
            Multipart mp = new MimeMultipart("alternative");
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setText(body_text, charset);
            mp.addBodyPart(mbp);
            mbp = new MimeBodyPart();
            mbp.setContent(body_html, "text/html; charset=" + charset);
            mp.addBodyPart(mbp);
            msg.setContent(mp);
            break;
        }

        Transport.send(msg);
    } catch (Exception e) {
        logger.error("sendEmail: " + e);
        logger.error(AgnUtils.getStackTrace(e));
        return false;
    }
    return true;
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text,
        final Message previousMailMessage) {
    LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)");
    if (suppressMail) {
        return;/*  w  ww  . j  av  a 2 s  .c  om*/
    }
    setMailProperties();
    MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) {
                setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses());
            }
            if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) {
                setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses());
            }
            if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) {
                setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses());
            }

            if (null != mailMetaData.getFromAddress()) {
                mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName())
                        .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress())
                        .append(MailConstants.GREATER_SYMBOL).toString()));
            }

            if (null != mailMetaData.getSubject() && null != text) {
                mimeMessage.setSubject(mailMetaData.getSubject());
            }

            if (null != text) {
                mimeMessage.setText(text);
            }

            // Create your new message part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE));

            // Create a multi-part to combine the parts
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create and fill part for the forwarded content
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(previousMailMessage.getDataHandler());

            // Add part to multi part
            multipart.addBodyPart(messageBodyPart);

            // Associate multi-part with message
            mimeMessage.setContent(multipart);

        }
    };
    try {
        mailSender.send(messagePreparator);
    } catch (MailException mailException) {
        LOGGER.error("Error while sending mail to configured mail account", mailException);
        throw new SendMailException(
                EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException);
    }
    LOGGER.info("mail sent successfully");
}

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

public String send() {
    List attachmentList = null;//from   ww  w .j  av  a  2 s.c  o  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";
}