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(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:it.infn.ct.downtime.Downtime.java

private void sendHTMLEmail(String TO, String FROM, String SMTP_HOST, File file) {

    String[] downtime_text = new String[4];

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {//from   w  ww  .  j  av a2  s .co  m
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        //Build Document
        Document document = builder.parse(file);

        //Normalize the XML Structure; It's just too important !!
        document.getDocumentElement().normalize();

        //Here comes the root node
        Element root = document.getDocumentElement();
        NodeList List = document.getElementsByTagName("DOWNTIME");

        for (int i = 0; i < List.getLength(); i++) {
            Node node = List.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) node;

                // Downtime period
                downtime_text[0] = "SCHEDULED Downtime period <br/>";
                downtime_text[0] += "Start of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_START_DATE").item(0).getTextContent()
                        + "<br/>";
                downtime_text[0] += "End  of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_END_DATE").item(0).getTextContent()
                        + "<br/><br/>";

                // Entities in downtime
                downtime_text[1] = "<b><u>Entities in downtime:</u></b><br/>";
                downtime_text[1] += "Server Host: "
                        + eElement.getElementsByTagName("HOSTED_BY").item(0).getTextContent() + "<br/><br/>";
                for (int k = 0; k < eElement.getElementsByTagName("SERVICE").getLength(); k++) {
                    downtime_text[1] += "Nodes: "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Service Type: "
                            + eElement.getElementsByTagName("SERVICE_TYPE").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Hosted service(s): "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/><br/>";
                }

                // Description
                downtime_text[2] = "<b><u>Description:</u></b><br/>";
                downtime_text[2] += eElement.getElementsByTagName("DESCRIPTION").item(0).getTextContent()
                        + "<br/>";
                downtime_text[2] += "More details are available in this <a href="
                        + eElement.getElementsByTagName("GOCDB_PORTAL_URL").item(0).getTextContent()
                        + "> link</a>" + "<br/><br/>";

                // Severity
                downtime_text[3] = "<b><u>Severity:</u></b> ";
                downtime_text[3] += eElement.getElementsByTagName("SEVERITY").item(0).getTextContent()
                        + "<br/><br/>";

                // Sending notification                
                // Create a default MimeMessage object.
                javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

                // Set From: header field of the header.
                message.setFrom(new javax.mail.internet.InternetAddress(FROM));

                // Set To: header field of the header.
                message.addRecipient(javax.mail.Message.RecipientType.TO,
                        new javax.mail.internet.InternetAddress(TO));
                //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

                // Set Subject: header field
                message.setSubject(" [EGI DOWNTIME] ANNOUNCEMENT ");

                Date currentDate = new Date();
                currentDate.setTime(currentDate.getTime());

                // Send the actual HTML message, as big as you like
                message.setContent("<br/><H4>"
                        + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                        + "</H4>" + "Long Tail of Science (LToS) services in downtime<br/><br/>"
                        + downtime_text[0] + downtime_text[1] + downtime_text[2] + downtime_text[3]
                        + "<b><u>TimeStamp:</u></b><br/>" + currentDate + "<br/><br/>"
                        + "<b><u>Disclaimer:</u></b><br/>"
                        + "<i>This is an automatic message sent by the LToS Science Gateway based on Liferay technology."
                        + "<br/><br/>", "text/html");

                // Send notification to the user
                javax.mail.Transport.send(message);
            }
        }
    } catch (MessagingException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.cloudcoder.healthmonitor.HealthMonitor.java

private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews,
        boolean badNews, String reportEmailAddress) throws MessagingException, AddressException {
    Session session = createMailSession(config);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(reportEmailAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress));
    message.setSubject("CloudCoder health monitor report");

    StringBuilder body = new StringBuilder();
    body.append("<h1>CloudCoder health monitor report</h1>\n");

    if (badNews) {
        body.append("<h2>Unhealthy instances</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.badNews()) {
                appendReportItem(body, item, infoMap);
            }/*from w ww  .j  a  v  a2  s .c o  m*/
        }
        body.append("</ul>\n");
    }

    if (goodNews) {
        body.append("<h2>Healthy instances (back on line)</h2>\n");
        body.append("<ul>\n");
        for (ReportItem item : reportItems) {
            if (item.goodNews()) {
                appendReportItem(body, item, infoMap);
            }
        }
        body.append("</ul>\n");
    }

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

    Transport.send(message);
}

From source file:com.commoncoupon.mail.EmailProcessor.java

public Integer call() throws Exception {
    MimeMessage message = new MimeMessage(getSession());

    try {/*from   ww  w .  j  a  va  2 s  .  c o m*/
        if (from != null && (from != null && from.trim() != "")) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            if (log.isDebugEnabled())
                log.debug("Email sent from: " + sentFrom);
        }

        if (to != null && to.length > 0) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress((String) to[i]);
                if (log.isDebugEnabled())
                    log.debug("Sending e-mail to: " + to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null && cc.length > 0) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress((String) cc[i]);
                if (log.isDebugEnabled())
                    log.debug("Copying e-mail to: " + cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
    } catch (Exception e) {
        log.error("Failed to send email.", e);
        return (1);
    }

    return (0);
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final void send(String to, String cc, String bcc, String subject, String memo, boolean html)
        throws Exception {
    MimeMessage mimeMessage = new MimeMessage(smtpSession);

    // Add 'to' fields
    StringTokenizer st = new StringTokenizer(to, ", ");
    while (st.hasMoreTokens()) {
        mimeMessage.addRecipients(Message.RecipientType.TO, st.nextToken());
    }//from  ww w  .jav a 2s  . c om

    // Add 'cc' fields
    if (cc != null && cc.length() != 0) {
        st = new StringTokenizer(cc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.CC, st.nextToken());
        }
    }

    // Add 'bcc' fields
    if (bcc != null && bcc.length() != 0) {
        st = new StringTokenizer(bcc, ", ");
        while (st.hasMoreTokens()) {
            mimeMessage.addRecipients(Message.RecipientType.BCC, st.nextToken());
        }
    }

    // Set message
    if (html) {
        mimeMessage.setHeader("Content-Type", "text/html");
        mimeMessage.setContent(memo.trim(), "text/html; charset=UTF-8");
    } else {
        mimeMessage.setHeader("Content-Type", "text/plain");
        mimeMessage.setContent(memo.trim(), "text/plain; charset=UTF-8");
    }

    // Set 'from', 'subject' and date fields
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.setSubject(subject.trim(), "UTF-8");
    mimeMessage.setSentDate(new Date());
    Transport.send(mimeMessage);
}

From source file:com.sangupta.jerry.email.service.impl.SmtpEmailServiceImpl.java

/**
 * @see com.sangupta.jerry.email.service.EmailService#sendEmail(com.sangupta.jerry.email.domain.Email)
 *//*from   ww  w.j  av  a 2  s.  com*/
@Override
public boolean sendEmail(final Email email) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (AssertUtils.isNotEmpty(email.getTo())) {
                for (EmailAddress address : email.getTo()) {
                    mimeMessage.setRecipient(RecipientType.TO, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getCc())) {
                for (EmailAddress address : email.getCc()) {
                    mimeMessage.setRecipient(RecipientType.CC, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getBcc())) {
                for (EmailAddress address : email.getBcc()) {
                    mimeMessage.setRecipient(RecipientType.BCC, address.getInternetAddress());
                }
            }

            if (AssertUtils.isNotEmpty(email.getReplyTo())) {
                Address[] replyTo = new Address[email.getReplyTo().size()];
                int counter = 0;
                for (EmailAddress address : email.getReplyTo()) {
                    replyTo[counter++] = address.getInternetAddress();
                }
                mimeMessage.setReplyTo(replyTo);
            }

            mimeMessage.setFrom(email.getFrom().getInternetAddress());
            mimeMessage.setSubject(email.getSubject());
            mimeMessage.setContent(email.getText(), "text/html; charset=utf-8");
        }

    };

    try {
        this.mailSender.send(preparator);
        return true;
    } catch (MailException e) {
        LOGGER.error("Unable to send email", e);
    }

    return false;
}

From source file:it.infn.ct.chipster.Chipster.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String user_emailAddress, String credential, String chipster_HOST) {

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- User's email = " + user_emailAddress);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);
    properties.setProperty("mail.debug", "true");

    //properties.setProperty("mail.smtp.auth", "false");        

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {/* w  ww  . ja v a  2s . c o m*/
        // Create a default MimeMessage object.
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new javax.mail.internet.InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(TO));
        message.addRecipient(javax.mail.Message.RecipientType.CC,
                new javax.mail.internet.InternetAddress(user_emailAddress));
        //new javax.mail.internet.InternetAddress("glarocca75@gmail.com")); // <== Change here!

        // Set Subject: header field
        message.setSubject(" Chipster Account Generator service notification ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                + "</H4><hr><br/>" + "<b>Description:</b> " + ApplicationAcronym
                + " notification service <br/><br/>"
                + "<i>A request to create a new temporary chipster account has been successfully sent from the LToS Science Gateway</i><br/><br/>"
                + "<b>Chipster Front Node:</b> " + chipster_HOST + "<br/>" + "<b>Credentials:</b> " + credential
                + "<br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Catania Science Gateway (CSG) tailored for the EGI Long of Tail Science.<br/><br/>",
                "text/html");

        // Send message
        javax.mail.Transport.send(message);
    } catch (javax.mail.MessagingException ex) {
        Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.tightblog.service.EmailService.java

/**
 * This method is used to send an HTML Message
 *
 * @param from    e-mail address of sender
 * @param to      e-mail address(es) of recipients
 * @param subject subject of e-mail//from  www .jav a2s.  com
 * @param content the body of the e-mail
 */
private void sendMessage(String from, String[] to, String[] cc, String subject, String content) {
    try {
        MimeMessage message = mailSender.createMimeMessage();

        // n.b. any default from address is expected to be determined by caller.
        if (!StringUtils.isEmpty(from)) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            log.debug("e-mail from: {}", sentFrom);
        }

        if (to != null) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress(to[i]);
                log.debug("sending e-mail to: {}", to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress(cc[i]);
                log.debug("copying e-mail to: {}", cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }

        message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
        message.setContent(content, "text/html; charset=utf-8");
        message.setSentDate(new java.util.Date());

        // First collect all the addresses together.
        boolean bFailedToSome = false;
        SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            mailSender.send(message);
        } catch (MailAuthenticationException | MailSendException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);
        }

        if (bFailedToSome) {
            throw sendex;
        }
    } catch (MessagingException e) {
        log.error("ERROR: Problem sending email with subject {}", subject, e);
    }
}

From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java

public void sendEmail(EmailRecipient[] addresses, String subject, String[] body, String[] htmlBody,
        Integer priority) {/*from   w  w w . ja va 2  s . c o  m*/
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    final StopWatch watch = new StopWatch();

    try {
        InternetAddress from = getFromAddress();
        if (from == null) {
            mimeMessage.setFrom();
        } else {
            mimeMessage.setFrom(from);
        }

        // HHQ-5708
        // remove any possible new line from the subject
        // the subject can be render form 'subject.gsp' file
        mimeMessage.setSubject(subject.replace("\r", "").replace("\n", ""));

        // If priority not null, set it in body 
        if (priority != null) {
            switch (priority.intValue()) {
            case EventConstants.PRIORITY_HIGH:
                mimeMessage.addHeader("X-Priority", "1");
                break;
            case EventConstants.PRIORITY_MEDIUM:
                mimeMessage.addHeader("X-Priority", "2");
                break;
            default:
                break;
            }
        }

        // Send to each recipient individually (for D.B. SMS)
        for (int i = 0; i < addresses.length; i++) {
            mimeMessage.setRecipient(Message.RecipientType.TO, addresses[i].getAddress());

            if (addresses[i].useHtml()) {
                mimeMessage.setContent(htmlBody[i], "text/html; charset=UTF-8");
                if (log.isDebugEnabled()) {
                    log.debug("Sending HTML Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + htmlBody[i]);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Sending Alert notification: " + subject + " to "
                            + addresses[i].getAddress().getAddress() + "\n" + body[i]);
                }
                mimeMessage.setContent(body[i], "text/plain; charset=UTF-8");
            }

            mailSender.send(mimeMessage);
        }
    } catch (MessagingException e) {
        log.error("MessagingException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", e);
    } catch (MailException me) {
        log.error("MailException in sending email: [" + subject + "]\nmailServer = ["
                + mailSession.getProperties() + "]", me);
    } catch (Exception ex) {
        log.error(
                "Error in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]",
                ex);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Sending email using mailServer=" + mailSession.getProperties() + " took "
                    + watch.getElapsed() + " ms.");
        }
        if (watch.getElapsed() >= mailSmtpConnectiontimeout || (watch.getElapsed() >= mailSmtpTimeout)) {
            log.warn("Sending email using mailServer=" + mailSmtpHost + " took " + watch.getElapsed()
                    + " ms.  Please check with your mail administrator.");
        }
    }
}

From source file:org.openbizview.util.Bvt002.java

/**
* Enva notificacin a usuario al cambiar la contrasea
**///from  w  ww.  j a  va 2s .com
private void ChangePassNotification2(String mail, String clave) {
    try {
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(JNDIMAIL);
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);
        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailUserUserChgPass"));
        mm.setText(getMessage("mailNewUserMsj2"));

        // use this is if you want to send html based message
        mm.setContent(getMessage("mailNewUserMsj6") + " " + coduser.toUpperCase() + " / " + clave
                + "<br/><br/> " + getMessage("mailNewUserMsj2"), "text/html; charset=utf-8");

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.intranet.intr.proveedores.EmpControllerGestion.java

public void enviarProvUC(proveedores proveedor) {
    String cuerpo = "";
    String servidorSMTP = "smtp.1and1.es";
    String puertoEnvio = "465";
    Properties props = new Properties();//propiedades a agragar
    props.put("mail.smtp.user", miCorreo);//correo origen
    props.put("mail.smtp.host", servidorSMTP);//tipo de servidor
    props.put("mail.smtp.port", puertoEnvio);//puesto de salida
    props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor
    props.put("mail.smtp.auth", "true");//autentificacion
    props.put("mail.smtp.password", "angel2010");//autentificacion
    props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SecurityManager security = System.getSecurityManager();

    Authenticator auth = new autentificadorSMTP();//autentificar el correo
    Session session = Session.getInstance(props, auth);//se inica una session
    // session.setDebug(true);

    try {// w  ww  . j  a va2s  .c  o  m
        // Creamos un objeto mensaje tipo MimeMessage por defecto.
        MimeMessage mensajeE = new MimeMessage(session);

        // Asignamos el de o from? al header del correo.
        mensajeE.setFrom(new InternetAddress(miCorreo));

        // Asignamos el para o to? al header del correo.
        mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail()));

        // Asignamos el asunto
        mensajeE.setSubject("Su Perfil Personal");

        // Creamos un cuerpo del correo con ayuda de la clase BodyPart
        //BodyPart cuerpoMensaje = new MimeBodyPart();

        // Asignamos el texto del correo
        String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: "
                + proveedor.getContrasenna()
                + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm";
        // Asignamos el texto del correo
        cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>";
        mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>", "text/html");
        //mensaje.setText(text);

        // Creamos un multipart al correo

        // Enviamos el correo
        Transport.send(mensajeE);
        System.out.println("Mensaje enviado");

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}