Example usage for javax.mail Multipart addBodyPart

List of usage examples for javax.mail Multipart addBodyPart

Introduction

In this page you can find the example usage for javax.mail Multipart addBodyPart.

Prototype

public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void sendGRUP(String from, String password, String bcc, String sub, String msg, String filename)
        throws Exception {
    //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, password);
        }/*  w ww . j av a 2  s  .  c  o m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));

        message.setSubject(sub);
        message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automat");

        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);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);
        System.out.println("message sent successfully");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, 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");
        }//from w  ww  .  ja  v  a  2  s  .  c  om
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        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);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(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(// w  w w .jav a 2  s. co 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:com.sat.common.CustomReport.java

/**
 * Sendmail./*from   ww  w . j a v a2  s.com*/
 * 
 * @param msg
 *            the msg
 * @throws AddressException
 *             the address exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {

    ConfigFileHandlerManager miscConfigFileHandlerManager = new ConfigFileHandlerManager();
    miscConfigFileHandlerManager.loadPropertiesBasedonPropertyFileName("com.cisco.lms.lms");
    Validate miscValidate = new Validate();

    String from = miscValidate.readsystemvariable("MAIL.FROM");
    String host = miscValidate.readsystemvariable("MAIL.SMTP.HOST");
    String to = miscValidate.readsystemvariable("MAIL.TO");

    String subject = miscValidate.readsystemvariable("MAIL.SUBJECT");
    String personal = miscValidate.readsystemvariable("MAIL.FROM.PERSONAL");

    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from, personal));

        message.addRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject);
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/*from w  w  w .  j  a va 2  s . com*/

        //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");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //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());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);//w w  w. ja  va2s. c  o  m

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

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * Sendmail.//from  w  w  w  . j  av a 2 s.  co m
 *
 * @param msg the msg
 * @throws AddressException the address exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {
    //Properties CustomReport_CONFIG = new Properties();
    //FileInputStream fn = new FileInputStream(System.getProperty("user.dir")+ "/src/it/resources/config.properties");
    //CustomReport_CONFIG.load(fn);
    String from = "automationreportmailer@cisco.com";
    // String from = "sitaut@cisco.com";
    //String host = System.getProperty("MAIL.SMTP.HOST");
    String host = "outbound.cisco.com";
    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    // String ecsip = CustomReport_CONFIG.getProperty("ecsip");
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from
        // ));
                , "Automation Report Mailer"));
        //message.addRecipients(Message.RecipientType.TO, System.getProperty("MAIL.TO"));
        //message.setSubject(System.getProperty("mail.subject"));

        message.addRecipients(Message.RecipientType.TO, "maparame@cisco.com");
        message.setSubject("VCS consle report");
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java

/**
 * Fill the body of a message already created.
 * The result message depends on the information given. 
 * //from w  w  w  .j ava  2s .c  o  m
 * @param message
 * @param text
 * @param html
 * @param parts
 * @return The composed message
 * @throws MessagingException
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
public static Message composeMessage(Message message, String text, String html, List parts)
        throws MessagingException, IOException {

    MimeBodyPart txtPart = null;
    MimeBodyPart htmlPart = null;
    MimeMultipart mimeMultipart = null;

    if (text == null && html == null) {
        text = "";
    }
    if (text != null) {
        txtPart = new MimeBodyPart();
        txtPart.setContent(text, "text/plain");
    }
    if (html != null) {
        htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html");
    }
    if (html != null && text != null) {
        mimeMultipart = new MimeMultipart();
        mimeMultipart.setSubType("alternative");
        mimeMultipart.addBodyPart(txtPart);
        mimeMultipart.addBodyPart(htmlPart);
    }

    if (parts == null || parts.isEmpty()) {
        if (mimeMultipart != null) {
            message.setContent(mimeMultipart);
        } else if (html != null) {
            message.setText(html);
            message.setHeader("Content-type", "text/html");
        } else if (text != null) {
            message.setText(text);
        }
    } else {
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (mimeMultipart != null) {
            bodyPart.setContent(mimeMultipart);
        } else if (html != null) {
            bodyPart.setText(html);
            bodyPart.setHeader("Content-type", "text/html");
        } else if (text != null) {
            bodyPart.setText(text);
        }
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
        for (Object attachment : parts) {
            if (attachment instanceof FileItem) {
                multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment));
            } else {
                multipart.addBodyPart((BodyPart) attachment);
            }
        }
        message.setContent(multipart);
    }

    message.saveChanges();
    return message;

}

From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java

/**
 * Fill the body of a message already created.
 * The result message depends on the information given.
 *
 * @param message//from   www .  jav  a2  s  . co m
 * @param text
 * @param html
 * @param parts
 * @return The composed message
 * @throws MessagingException
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
public static Message composeMessage(Message message, String text, String html, List parts)
        throws MessagingException, IOException {

    MimeBodyPart txtPart = null;
    MimeBodyPart htmlPart = null;
    MimeMultipart mimeMultipart = null;

    if (text == null && html == null) {
        text = "";
    }
    if (text != null) {
        txtPart = new MimeBodyPart();
        txtPart.setContent(text, "text/plain; charset=UTF-8");
    }
    if (html != null) {
        htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html; charset=UTF-8");
    }
    if (html != null && text != null) {
        mimeMultipart = new MimeMultipart();
        mimeMultipart.setSubType("alternative");
        mimeMultipart.addBodyPart(txtPart);
        mimeMultipart.addBodyPart(htmlPart);
    }

    if (parts == null || parts.isEmpty()) {
        if (mimeMultipart != null) {
            message.setContent(mimeMultipart);
        } else if (html != null) {
            message.setText(html);
            message.setHeader("Content-type", "text/html");
        } else if (text != null) {
            message.setText(text);
        }
    } else {
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (mimeMultipart != null) {
            bodyPart.setContent(mimeMultipart);
        } else if (html != null) {
            bodyPart.setText(html);
            bodyPart.setHeader("Content-type", "text/html");
        } else if (text != null) {
            bodyPart.setText(text);
        }
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
        for (Object attachment : parts) {
            if (attachment instanceof FileItem) {
                multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment));
            } else {
                multipart.addBodyPart((BodyPart) attachment);
            }
        }
        message.setContent(multipart);
    }

    message.saveChanges();
    return message;

}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder, deletes all messages which match the magic subject and
 * creates a new message with an attachment which contains the object serialized
 *///from w ww  .  j  ava  2  s .co m
protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore,
        String folderName, String subject, Object object)
        throws MessagingException, IOException, InterruptedException {
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName);

    if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        // Serialize the object
        ByteArrayOutputStream fout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray());

        // Create a new message with an attachment which has the serialized object
        MimeMessage message = new MimeMessage(session);
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain");
        multipart.addBodyPart(txtPart);
        FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE);
        multipart.addBodyPart(MessageUtils.fileitemToBodypart(item));
        message.setContent(multipart);
        message.saveChanges();

        // It seems it's not possible to modify the content of an existing message using the API
        // So I delete the previous message storing the preferences and I create a new one
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (subject.equals(msg.getSubject())) {
                msg.setFlag(Flag.DELETED, true);
            }
        }

        // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler)
        message = new MimeMessage((MimeMessage) message);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });
        folder.close(true);
        logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user);
    } else {
        logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user "
                + user);
    }
}