Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart() 

Source Link

Document

Default constructor.

Usage

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*  w w  w . j  a v  a2s  .c om*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:bo.com.offercruzmail.imp.FormadorMensajes.java

public static Multipart enviarEntidadNoExiste(String id) throws MessagingException {
    Multipart cuerpo = new MimeMultipart();
    cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto("El regitro con Id <b>" + id + "</b> no existe"));
    return cuerpo;
}

From source file:com.gitlab.anlar.lunatic.server.ServerTest.java

private void sendMultiPartEmail(String from, String to, String subject, String body) throws MessagingException {
    Properties props = createEmailProps(serverPort);
    Session session = Session.getInstance(props);

    Message msg = createBaseMessage(from, to, subject, session);

    MimeBodyPart p1 = new MimeBodyPart();
    p1.setText(body);/*w ww.  java 2 s . co m*/

    MimeBodyPart p2 = new MimeBodyPart();
    p2.setText("Second part");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);

    msg.setContent(mp);

    Transport.send(msg);
}

From source file:servlets.mail_ResetPassword.java

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

    try {/*from w  w w.j  a  va  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: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);
    }/*from   w w w . ja v  a2s.  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:bo.com.offercruzmail.imp.FormadorMensajes.java

public static Multipart enviarIdCargarNoValido() throws MessagingException {
    Multipart cuerpo = new MimeMultipart();
    StringBuilder texto = new StringBuilder();
    texto.append(escapeHtml4(//from  w w w  .  ja  v  a2s.  c  o  m
            "No se pudo recuperar el Id especificado, debe enviar un nmero vlido o la cadena "));
    texto.append("<b>todos</b> para recuperar todos los registros.");
    cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(texto.toString()));
    return cuerpo;

}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//  ww w. j a  v a 2s .  c o  m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Creates a MimeMultipart, so that we can have an attachment.
 *
 * @param message/*  w ww  .  j  av  a 2s.  c  o m*/
 * @return
 */
private MimeMultipart createMultipart(Message message) throws Exception {
    MimeMultipart toReturn = new MimeMultipart();

    MimeBodyPart textContent = new MimeBodyPart();
    textContent.setContent(message.getContent(), message.getContentType());

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setContent(message.getAttachment(), message.getAttachmentContentType());
    attachment.setFileName(message.getAttachmentFileName());

    toReturn.addBodyPart(textContent);
    toReturn.addBodyPart(attachment);

    return toReturn;
}

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");
        }/*  w w w  . j  av  a  2 s  .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());

    }

}