Example usage for javax.mail.internet MimeBodyPart setContent

List of usage examples for javax.mail.internet MimeBodyPart setContent

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this body part's content.

Usage

From source file:org.xwiki.mail.internal.HTMLMimeBodyPartFactory.java

private MimeBodyPart createHTMLBodyPart(String content, boolean hasAttachments) throws MessagingException {
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(content, "text/html; charset=" + StandardCharsets.UTF_8.name());
    htmlPart.setHeader("Content-Type", "text/html");
    if (hasAttachments) {
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
    }//from  w  ww .j  ava  2 s  .  c  o  m
    return htmlPart;
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

private MimeBodyPart createHTMLBodyPart(String content, boolean hasAttachments) throws MessagingException {
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(content, TEXT_HTML_CONTENT_TYPE);
    htmlPart.setHeader("Content-Type", TEXT_HTML_CONTENT_TYPE);
    if (hasAttachments) {
        htmlPart.setHeader("Content-Disposition", "inline");
        htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
    }//from w ww .  j av a 2s .c  o m
    return htmlPart;
}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*from   w  w w.j ava2s .  co m*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*  ww  w .  j av a  2 s. c  o m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

private void addBodyPart(MimeMultipart content, String textBody, String type) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(textBody, type);
    content.addBodyPart(bodyPart);//from  www  .j av  a  2 s.  c o  m
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void notifyEmailUpdated(String oldAddress, String newAddress) {
    try {/*from  w  ww. j a v  a  2s.c  om*/
        //Create the message body
        final MimeBodyPart msg = new MimeBodyPart();
        msg.setContent(
                "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n"
                        + "New Email Address: " + newAddress + "\n" + "\n"
                        + "If you have any questions, please contact your Human Resources department.",
                "text/plain");

        final MimeMessage message = this.javaMailSender.createMimeMessage();
        final Address[] recipients;
        if (StringUtils.isNotEmpty(oldAddress)) {
            recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) };
        } else {
            recipients = new Address[] { new InternetAddress(newAddress) };
        }
        message.setRecipients(RecipientType.TO, recipients);
        message.setFrom(new InternetAddress("payroll@ohr.wisc.edu"));
        message.setSubject("Business Email Address Change");

        // sign the message body
        if (this.smimeSignedGenerator != null) {
            final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC");
            message.setContent(mm, mm.getContentType());
        }
        // no signing keystore configured, send the message unsigned
        else {
            message.setContent(msg.getContent(), msg.getContentType());
        }

        message.saveChanges();

        this.javaMailSender.send(message);

        this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress);
    } catch (Exception e) {
        this.logger.error(
                "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e);
    }
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void sendMail(MailTransport mailTransport) {
    log.debug("Mail delivery started");
    File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile();
    Properties config = new Properties();

    try {/*  w  w  w .j av a  2 s .  co m*/
        config.load(new FileReader(propertyfile));
    } catch (IOException e) {
        log.error(e);
    }

    Session session = Session.getDefaultInstance(config);

    log.debug("Received session");

    MimeMessage message = new MimeMessage(session);

    String to = mailTransport.getTo();
    String from = mailTransport.getFrom();
    String replyTo = mailTransport.getReplyTo();
    String subject = mailTransport.getSubject();
    String html = mailTransport.getHtml();
    String text = mailTransport.getText();

    try {
        Address fromAdr = new InternetAddress(from);
        Address toAdr = new InternetAddress(to);
        Address rplyAdr = new InternetAddress(replyTo);

        message.setSubject(subject);
        message.setFrom(fromAdr);
        message.setRecipient(Message.RecipientType.TO, toAdr);
        message.setReplyTo(new Address[] { rplyAdr });
        message.setSender(fromAdr);
        message.addHeader("Return-path", replyTo);
        message.addHeader("X-TRV-MID", mailTransport.getmId());
        message.addHeader("X-TRV-UID", mailTransport.getuId());

        // Content
        MimeBodyPart messageTextPart = new MimeBodyPart();
        messageTextPart.setText(text);
        messageTextPart.setContent(html, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageTextPart);

        // Put parts in message
        message.setContent(multipart);

        log.debug("Dispatching message");
        Transport.send(message);
        log.debug("Mail delivery ended");
    } catch (MessagingException e) {
        log.error(e);
    }

}

From source file:org.unitime.commons.Email.java

public void setText(String message) throws MessagingException {
    MimeBodyPart text = new MimeBodyPart();
    text.setContent(message, "text/plain; charset=UTF-8");
    iBody.addBodyPart(text);// w w w .j a  v a 2  s  .  c o  m
}

From source file:org.unitime.commons.Email.java

public void setHTML(String message) throws MessagingException {
    MimeBodyPart text = new MimeBodyPart();
    text.setContent(message, "text/html; charset=UTF-8");
    iBody.addBodyPart(text);//from   ww  w . j  a  v  a 2s .c om
}

From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java

@Override
public String execute() throws Exception {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", config.getEmailHost());
    properties.put("mail.smtp.port", config.getEmailPort());

    Session session = Session.getInstance(properties, new Authenticator() {

        @Override//from   ww w .j  a v  a 2s .co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword());
        }
    });

    // Create a new message
    MimeMessage msg = new MimeMessage(session) {

        @Override
        protected void updateMessageID() throws MessagingException {
            if (this.getHeader("Message-ID") == null) {
                super.updateMessageID();
            }
        }
    };

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false));
    msg.setSubject("Test email");
    msg.setSentDate(new Date());
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.",
            "text; charset=utf-8");

    Thread thread = new Thread() {

        @Override
        public void run() {

            sent = false;
            int i = 0;
            while (!sent) {
                try {
                    Transport.send(sendMail);
                    LOG.info("Message sent TRIED#: " + i + " \n" + "Test email");
                    sent = true;

                } catch (MessagingException e) {
                    LOG.info("Message  DON'T sent: \n" + "Test email");

                    i++;
                    if (i == 10) {
                        break;

                    }
                    try {
                        Thread.sleep(1 * // minutes to sleep
                        60 * // seconds to a minute
                        1000);
                    } catch (InterruptedException e1) {

                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }

            }

        };
    };

    thread.run();

    if (sent) {
        return SUCCESS;
    } else {
        return INPUT;
    }
}