Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message/*from   w  ww .  j  a v a2s . co  m*/
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

    Session session = Session.getInstance(properties, authenticator);
    Message message = new MimeMessage(session);

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, addressTo);

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private static void setFileAsAttachment(Message msg, String message, File file) throws MessagingException {
    MimeBodyPart p1 = new MimeBodyPart();
    p1.setText(message);/* w w w .  j ava 2 s  .co m*/

    // Create second part
    MimeBodyPart p2 = new MimeBodyPart();

    // Put a file in the second part
    FileDataSource fds = new FileDataSource(file);
    p2.setDataHandler(new DataHandler(fds));
    p2.setFileName(fds.getName());

    // Create the Multipart.  Add BodyParts to it.
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);

    // Set Multipart as the message's content
    msg.setContent(mp);
}

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>
 *//*from   w w  w  . j  a  v  a 2  s.  c  o m*/
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: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  .  j  a  v  a 2 s .c  o 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.xwiki.mail.internal.HTMLMimeBodyPartFactory.java

private MimeBodyPart createHTMLBodyPart(String content, boolean hasAttachments) throws MessagingException {
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(content, "text/html; charset=" + StandardCharsets.UTF_8.name());
    htmlPart.setHeader("Content-Type", "text/html");
    if (hasAttachments) {
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
    }//from   ww w .j  ava2  s. c o  m
    return htmlPart;
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private void includeAttachments(MimeMultipart mimeMultipart, List<LabelValueBean> attachments)
        throws MessagingException {
    for (int i = 0; i < attachments.size(); i++) {
        LabelValueBean lvb = attachments.get(i);
        File f = new File(lvb.getValue());
        if (f != null && f.exists()) {
            LOGGER.debug("Use attachment file:" + f.getAbsolutePath());
            MimeBodyPart mbpFile = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(f);
            mbpFile.setDataHandler(new DataHandler(fds));
            mbpFile.setFileName(lvb.getLabel());
            mimeMultipart.addBodyPart(mbpFile);
        } else {/* www .java2 s.  c  om*/
            LOGGER.debug("Attachment file:\"" + lvb.getValue() + "\" not exits!");
        }
    }
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifySubscriptionDeleted(TemporaryMailContainer container) {
    try {//from  w  w  w .ja v a  2 s. c  o m
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        Subscription obj = container.getObj();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s
        //maybe nice to use a template rather then sending raw xml.
        org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(obj, api);
        String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES);
        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
        attachment.setFileName("uddiNotification.xml");
        mp.addBodyPart(attachment);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey()));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

private void addBodyPart(MimeMultipart content, String textBody, String type) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(textBody, type);
    content.addBodyPart(bodyPart);/*from  w ww .  java2  s. c  o m*/
}

From source file:org.unitime.commons.Email.java

public void addAttachement(File file, String name) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(new FileDataSource(file)));
    attachement.setFileName(name == null ? file.getName() : name);
    iBody.addBodyPart(attachement);//from  www.j  a  va2s . com
}

From source file:org.snopoke.util.Emailer.java

public void send() throws MessagingException {
    notNull(from, "From address can not be null");
    isTrue(!to.isEmpty() || !bcc.isEmpty(), "No TO or BCC addresses specified");

    MimeMessage message = getMessasge();

    // Cover wrap
    MimeBodyPart wrap = new MimeBodyPart();
    MimeMultipart cover = getCoverPart();
    wrap.setContent(cover);// w w  w .  ja v  a2  s.  c  om

    MimeMultipart content = new MimeMultipart("related");
    message.setContent(content);
    content.addBodyPart(wrap);

    addAttachments(content);

    Transport.send(message);
}