Example usage for javax.mail BodyPart setContent

List of usage examples for javax.mail BodyPart setContent

Introduction

In this page you can find the example usage for javax.mail BodyPart setContent.

Prototype

public void setContent(Object obj, String type) throws MessagingException;

Source Link

Document

A convenience method for setting this part's content.

Usage

From source file:gov.nih.nci.caarray.util.EmailUtil.java

private static void addBodyPart(Multipart mp, String content, String contentType) throws MessagingException {
    BodyPart bp = new MimeBodyPart();
    bp.setContent(content, contentType);
    mp.addBodyPart(bp);/*w  w  w  .j ava  2  s . co m*/
}

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

public static BodyPart getBodyPartEnvuelto(String texto) throws MessagingException {
    BodyPart cuerpo = new MimeBodyPart();
    cuerpo.setContent(plantillaGeneral.replace("{texto}", texto), "text/html");
    return cuerpo;
}

From source file:com.fiveamsolutions.nci.commons.util.MailUtils.java

/**
 * Send an email./*w  w  w.java  2  s  . co m*/
 * @param u the recipient of the message
 * @param title the subject of the message
 * @param html the html content of the message
 * @param plainText the plain text content of the message
 * @throws MessagingException on error.
 */
public static void sendEmail(AbstractUser u, String title, String html, String plainText)
        throws MessagingException {
    if (!isMailEnabled()) {
        LOG.info("sending email to " + u.getEmail() + " with title " + title);
        LOG.info("plain text: " + plainText);
        LOG.info("html: " + html);
        return;
    }
    MimeMessage msg = new MimeMessage(getMailSession());
    msg.setFrom(new InternetAddress(getFromAddress()));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));
    msg.setSubject(title);
    Multipart mp = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(html, "text/html");
    mp.addBodyPart(bp);

    bp = new MimeBodyPart();
    bp.setContent(plainText, "text/plain");
    mp.addBodyPart(bp);

    msg.setContent(mp);

    Transport.send(msg);
}

From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java

private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content)
        throws ConfigurationException {
    try {/* ww  w.j a va2  s.  c  o  m*/
        log.debug("Sending mail.");
        MiscUtil.assertNotNull(subject, "subject");
        MiscUtil.assertNotNull(recipient, "recipient");
        MiscUtil.assertNotNull(content, "content");

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", config.getSMTPMailHost());
        log.trace("Mail host: " + config.getSMTPMailHost());
        if (config.getSMTPMailPort() != null) {
            log.trace("Mail port: " + config.getSMTPMailPort());
            props.setProperty("mail.port", config.getSMTPMailPort());
        }
        if (config.getSMTPMailUsername() != null) {
            log.trace("Mail user: " + config.getSMTPMailUsername());
            props.setProperty("mail.user", config.getSMTPMailUsername());
        }
        if (config.getSMTPMailPassword() != null) {
            log.trace("Mail password: " + config.getSMTPMailPassword());
            props.setProperty("mail.password", config.getSMTPMailPassword());
        }

        Session mailSession = Session.getDefaultInstance(props, null);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress());
        message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName()));
        log.trace("Recipient: " + recipient);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        log.trace("Creating multipart content of mail.");
        MimeMultipart multipart = new MimeMultipart("related");

        log.trace("Adding first part (html)");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15");
        multipart.addBodyPart(messageBodyPart);

        //         log.trace("Adding mail images");
        //         messageBodyPart = new MimeBodyPart();
        //         for (Image image : images) {
        //            messageBodyPart.setDataHandler(new DataHandler(image));
        //            messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">");
        //            multipart.addBodyPart(messageBodyPart);
        //         }

        message.setContent(multipart);
        transport.connect();
        log.trace("Sending mail message.");
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        log.trace("Successfully sent.");
        transport.close();

    } catch (MessagingException e) {
        throw new ConfigurationException(e);

    } catch (UnsupportedEncodingException e) {
        throw new ConfigurationException(e);

    }
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {// ww  w  .  j  a va  2 s.c o m
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        InternetAddress addressFrom = new InternetAddress(emailFrom);
        message.setFrom(addressFrom);

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

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

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a calendar message.//  ww  w .  ja  v  a  2 s.c om
 * @param strRecipientsTo The list of the main recipients email. Every
 *            recipient must be separated by the mail separator defined in
 *            config.properties
 * @param strRecipientsCc The recipients list of the carbon copies .
 * @param strRecipientsBcc The recipients list of the blind carbon copies .
 * @param strSenderName The sender name.
 * @param strSenderEmail The sender email address.
 * @param strSubject The message subject.
 * @param strMessage The HTML message.
 * @param strCalendarMessage The calendar message.
 * @param bCreateEvent True to create the event, false to remove it
 * @param transport the smtp transport object
 * @param session the smtp session object
 * @throws AddressException If invalid address
 * @throws SendFailedException If an error occurred during sending
 * @throws MessagingException If a messaging error occurred
 */
protected static void sendMessageCalendar(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, String strCalendarMessage, boolean bCreateEvent, Transport transport,
        Session session) throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    MimeMultipart multipart = new MimeMultipart();
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));

    multipart.addBodyPart(msgBodyPart);

    BodyPart calendarBodyPart = new MimeBodyPart();
    //        calendarBodyPart.addHeader( "Content-Class", "urn:content-classes:calendarmessage" );
    calendarBodyPart.setContent(strCalendarMessage,
            AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_CALENDAR)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET)
                    + AppPropertiesService.getProperty(PROPERTY_CALENDAR_SEPARATOR)
                    + AppPropertiesService.getProperty(
                            bCreateEvent ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL));
    calendarBodyPart.addHeader(HEADER_NAME, CONSTANT_BASE64);
    multipart.addBodyPart(calendarBodyPart);

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:SendMime.java

/** Do the work: send the mail to the SMTP server. */
public void doSend() throws IOException, MessagingException {

    // Create the Session object
    session = Session.getDefaultInstance(null, null);
    session.setDebug(true); // Verbose!

    try {//from   w  ww .j  a  v  a  2s  . c om
        // create a message
        mesg = new MimeMessage(session);

        // From Address - this should come from a Properties...
        mesg.setFrom(new InternetAddress("nobody@host.domain"));

        // TO Address
        InternetAddress toAddress = new InternetAddress(message_recip);
        mesg.addRecipient(Message.RecipientType.TO, toAddress);

        // CC Address
        InternetAddress ccAddress = new InternetAddress(message_cc);
        mesg.addRecipient(Message.RecipientType.CC, ccAddress);

        // The Subject
        mesg.setSubject(message_subject);

        // Now the message body.
        Multipart mp = new MimeMultipart();

        BodyPart textPart = new MimeBodyPart();
        textPart.setText(message_body); // sets type to "text/plain"

        BodyPart pixPart = new MimeBodyPart();
        pixPart.setContent(html_data, "text/html");

        // Collect the Parts into the MultiPart
        mp.addBodyPart(textPart);
        mp.addBodyPart(pixPart);

        // Put the MultiPart into the Message
        mesg.setContent(mp);

        // Finally, send the message!
        Transport.send(mesg);

    } catch (MessagingException ex) {
        System.err.println(ex);
        ex.printStackTrace(System.err);
    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {//from  w  ww .  ja  va 2 s.  co  m
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

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

private BodyPart createHtmlBodyPart(String htmlMessageBody) throws MessagingException {
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlMessageBody, "text/html");
    return htmlPart;

}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

private void addBody(Multipart multipart, String content, String contentType) throws MessagingException {
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(content, contentType);
    multipart.addBodyPart(messageBodyPart);
}