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.mule.transport.email.MailUtilsTestCase.java

@Test
public void testGetAttachmentName() throws Exception {
    @SuppressWarnings("unchecked")
    Map<String, Part> attachments = new HashedMap();

    String key = "test.txt";
    assertEquals(key, MailUtils.getAttachmentName(key, attachments));

    attachments.put(key, new MimeBodyPart());
    assertEquals("0_" + key, MailUtils.getAttachmentName(key, attachments));
}

From source file:org.wf.dp.dniprorada.util.Mail.java

public Mail _Attach(String sBody) {
    try {/*from w w w  .  ja  v a2 s. c o m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();
        //oMimeBodyPart.setText(sBody,DEFAULT_ENCODING,"Content-Type: text/html;");
        oMimeBodyPart.setText(sBody, DEFAULT_ENCODING);
        //         oMimeBodyPart.setHeader("Content-Type", "text/html");
        oMimeBodyPart.setHeader("Content-Type", "text/html;charset=utf-8");
        oMultiparts.addBodyPart(oMimeBodyPart);
        log.info("[_Attach:sBody]:sBody=" + sBody);
    } catch (Exception oException) {
        log.error("[_Attach:sBody]", oException);
    }
    return this;
}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }//  w  w  w  . ja va  2 s  .  co  m

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:com.spartasystems.holdmail.util.TestMailClient.java

private BodyPart createTextBodyPart(String messageBody) throws MessagingException {
    BodyPart textPart = new MimeBodyPart();
    textPart.setText(messageBody);//from w  w w  . ja  va2 s.c  om
    return textPart;
}

From source file:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java

public MimeMessage send(final @NonNull Email email, final @NonNull String template,
        final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures)
        throws CannotSendEmailException {
    email.setSentAt(new Date());
    final MimeMessage mimeMessage = toMimeMessage(email);
    try {//from   ww w . ja  va 2 s.c  om
        final MimeMultipart content = new MimeMultipart("related");

        String text = templateService.mergeTemplateIntoString(template,
                fromNullable(modelObject).or(ImmutableMap.of()));

        for (final InlinePicture inlinePicture : inlinePictures) {
            final String cid = UUID.randomUUID().toString();

            //Set the cid in the template
            text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid);

            //Set the image part
            final MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.attachFile(inlinePicture.getFile());
            imagePart.setContentID('<' + cid + '>');
            imagePart.setDisposition(MimeBodyPart.INLINE);
            imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType());
            content.addBodyPart(imagePart);
        }

        //Set the HTML text part
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(text, email.getEncoding().displayName(), "html");
        content.addBodyPart(textPart);

        mimeMessage.setContent(content);
        javaMailSender.send(mimeMessage);
    } catch (IOException e) {
        log.error("The template file cannot be read", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the template file", e);
    } catch (TemplateException e) {
        log.error("The template file cannot be processed", e);
        throw new CannotSendEmailException(
                "Error while processing the template file with the given model object", e);
    } catch (MessagingException e) {
        log.error("The mime message cannot be created", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the mime content", e);
    }
    return mimeMessage;
}

From source file:servlets.mail_ResetPassword.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//  w  w w .j a v a 2  s  .  c  o  m
        System.out.println("Reached @ mail_ResetPassword.");
        String emailid = request.getParameter("email");

        Random r = new Random();
        int Low = 1000;
        int High = 9999;
        int R = r.nextInt(High - Low) + Low;

        String ResetCode = "RC" + String.valueOf(R);

        Connection co = null;
        String OSflag = getServletContext().getInitParameter("OSflag");
        String host = null, driver = null, userName = null, password = null;
        switch (OSflag) {
        case "0": {
            host = getServletContext().getInitParameter("host");
            driver = getServletContext().getInitParameter("driver");
            userName = getServletContext().getInitParameter("userName");
            password = getServletContext().getInitParameter("password");
            break;
        }
        case "1": {
            host = "jdbc:mysql://" + System.getenv("OPENSHIFT_MYSQL_DB_HOST") + ":"
                    + System.getenv("OPENSHIFT_MYSQL_DB_PORT") + "/npreportingsuite";
            userName = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
            password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
            driver = getServletContext().getInitParameter("driver");
            break;
        }
        }

        Class.forName(driver);
        co = DriverManager.getConnection(host, userName, password);
        Statement st = co.createStatement();

        st.executeUpdate("UPDATE user_accounts SET passwordresetcode ='" + ResetCode + "' WHERE emailid = '"
                + emailid + "'");

        String emailMessage = "Hi!" + "<br>"
                + "Follow this <a href=\"https://npreportingsuite.com/NPReportDeck/resetPassword.jsp\">link</a> and enter the following Reset Code to reset your password."
                + "<br><br>" + "Reset Code : <b>" + ResetCode + "</b>" + "<br><br>" + "Warm Regards," + "<br>"
                + "NPReportingSuite Team" + "<br><br>";

        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        email.addTo(emailid);

        email.setFrom("reporting@groupnp.com");
        email.setSubject("NPReportingSuite : Reset Password Request Follow-up");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        email.send();

    } catch (EmailException | MessagingException | SQLException | ClassNotFoundException ex) {
        Logger.getLogger(mail_ResetPassword.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);//w w  w. ja v  a 2 s  .  c  o  m
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void setMimeMessageContent(SendingMessage sendingMessage, MimeMultipart content,
        MimeMultipart textPart) throws MessagingException {
    MimeBodyPart textBodyPart = new MimeBodyPart();
    MimeBodyPart contentBodyPart = new MimeBodyPart();
    String bodyContentType = getContentBodyType(sendingMessage);

    contentBodyPart.setContent(sendingMessage.getContentText(), bodyContentType);
    textPart.addBodyPart(contentBodyPart);
    textBodyPart.setContent(textPart);//from  w  ww.ja v a 2  s  .c om
    content.addBodyPart(textBodyPart);
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

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

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

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

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

    }

}

From source file:com.email.SendEmailCalInvite.java

/**
 * Builds the body for the email//from   w w w.  ja  va2s  .c  om
 *
 * @param eml EmailOutInvitesModel
 * @return String (Body)
 */
private static BodyPart body(EmailOutInvitesModel eml) {
    MimeBodyPart descriptionPart = new MimeBodyPart();
    try {
        String content = eml.getEmailBody() + "\n\n\n";
        descriptionPart.setContent(content, "text/html; charset=utf-8");
    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return descriptionPart;
}