Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java

protected BodyPart getBodyPartForAttachment(DataHandler handler, String name) throws MessagingException {
    BodyPart part = new MimeBodyPart();
    part.setDataHandler(handler);/*from ww w .j  a  v  a  2 s.c o m*/
    part.setDescription(name);

    part.setFileName(StringUtils.defaultString(handler.getName(), name));
    return part;
}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override//from w ww . j  av  a2 s  .  c  o  m
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;/*from www.  j  ava2  s.c  om*/
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }//ww w  .j av  a2 s. c  o  m

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getBcc() != null) {
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
        textBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
        htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private static MimeBodyPart createMessageBodyPart(String body, boolean html) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText(body);/*from w  w w.  jav  a2s  . c  o  m*/
    bodyPart.setHeader("content-type", (html ? "text/html" : "text/plain"));
    return bodyPart;
}

From source file:de.elomagic.mag.AbstractTest.java

protected MimeMessage createMimeMessage(String filename) throws Exception {

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent("This is some text to be displayed inline", "text/plain");
    textPart.setDisposition(Part.INLINE);

    MimeBodyPart binaryPart = new MimeBodyPart();
    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    binaryPart.setContent(getOriginalMailAttachment(), "application/pdf");
    binaryPart.setDisposition(Part.ATTACHMENT);
    binaryPart.setFileName(filename);/*from w w w . j a va2 s.  c  o m*/

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(textPart);
    mp.addBodyPart(binaryPart);

    MimeMessage message = new MimeMessage(greenMail.getImap().createSession());
    message.setRecipients(Message.RecipientType.TO,
            new InternetAddress[] { new InternetAddress("mailuser@localhost.com") });
    message.setSubject("Another test mail subject");
    message.setContent(mp);

    //
    return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup());
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public MimeBodyPart newHtmlBodyPart(String html) throws MessagingException {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(html, "text/html; charset=UTF-8");
    return mimeBodyPart;
}

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

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;/*from w  w  w.j  a  v a 2s .c om*/

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        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);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

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

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * Utility method to allow us to send multipart messages using HTML and plain text.
 *
 * // w w  w . ja v a 2s  .c  o m
 * @param recipient
 *            - string array of recipients that the message should be sent to
 * @param from
 *            - the e-mail address that should be used as the sending address
 * @param replyTo
 *            - (nullable) the e-mail address that should be used as the reply-to address
* @param replyToName
*            - (nullable) the name that should be used as the reply-to name
 * @param subject
 *            - The message subject
 * @param plainText
 *            - The message body
 * @param html
 *            - The message body in html
 * @throws MessagingException
 *             - if we cannot send the message for some reason.
 * @throws AddressException
 *             - if the address is not valid.
 */
public void sendMultiPartMail(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject, final String plainText, final String html)
        throws MessagingException, AddressException, UnsupportedEncodingException {
    Message msg = this.setupMessage(recipient, from, replyTo, replyToName, subject);

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(plainText, "utf-8");

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(html, "text/html; charset=utf-8");

    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart);
    multiPart.addBodyPart(htmlPart);

    msg.setContent(multiPart);

    Transport.send(msg);
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner//ww w .ja v a2s.  c  o m
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}