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:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content,
        List<MimeBodyPart> attachments) {
    MimeMessage mail = new MimeMessage(session);
    try {//w  ww . j  a  va 2 s.  c  om
        mail.setFrom(new InternetAddress(from));
        mail.setSubject(title);
        if (to != null) {
            mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }

        //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));

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

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

        for (MimeBodyPart attachment : attachments) {
            multipart.addBodyPart(attachment);
        }

        mail.setContent(multipart);
        //         mail.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(mail);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to/*w  w w. j  a  va2s. c  o  m*/
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

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

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }//from w  w  w.  j  a  v a 2s . co  m
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:org.fireflow.service.email.send.MailSenderImpl.java

/**
 * TODO ?//from   w w  w.  j a va2 s.c  o  m
 * @param mailSession
 * @param mailMessage
 * @return
 * @throws MessagingException 
 * @throws AddressException 
 * @throws ServiceInvocationException
 */
private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage)
        throws AddressException, MessagingException {
    MimeMessage mimeMsg = new MimeMessage(mailSession);

    //1?set from
    //Assert.notNull(mailMessage.getFrom(),"From address must not be null");
    mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom()));

    //2?set mailto
    List<String> mailToList = mailMessage.getMailToList();
    InternetAddress[] addressList = new InternetAddress[mailToList.size()];
    for (int i = 0; i < mailToList.size(); i++) {
        String mailTo = mailToList.get(i);
        addressList[i] = new InternetAddress(mailTo);
    }
    mimeMsg.setRecipients(Message.RecipientType.TO, addressList);

    //3?set cc
    List<String> ccList = mailMessage.getCarbonCopyList();
    if (ccList != null && ccList.size() > 0) {
        addressList = new InternetAddress[ccList.size()];
        for (int i = 0; i < ccList.size(); i++) {
            String mailTo = ccList.get(i);
            addressList[i] = new InternetAddress(mailTo);
        }
        mimeMsg.setRecipients(Message.RecipientType.CC, addressList);
    }

    //4?set subject
    mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset());

    //5?set sentDate
    if (this.sentDate != null) {
        mimeMsg.setSentDate(sentDate);
    }

    //6?set email body
    Multipart multiPart = new MimeMultipart();
    MimeBodyPart bp = new MimeBodyPart();
    if (mailMessage.getBodyIsHtml())
        bp.setContent(mailMessage.getBody(),
                CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset());
    else
        bp.setText(mailMessage.getBody(), mailServiceDef.getCharset());

    multiPart.addBodyPart(bp);
    mimeMsg.setContent(multiPart);

    //7?set attachment
    //TODO ?

    return mimeMsg;
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;//from   ww  w  .ja v a  2  s  .  c o  m
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void setMimeMessageContent(SendingMessage sendingMessage, MimeMultipart content,
        MimeMultipart textPart) throws MessagingException {
    MimeBodyPart textBodyPart = new MimeBodyPart();
    MimeBodyPart contentBodyPart = new MimeBodyPart();
    String bodyContentType = getContentBodyType(sendingMessage);

    contentBodyPart.setContent(sendingMessage.getContentText(), bodyContentType);
    textPart.addBodyPart(contentBodyPart);
    textBodyPart.setContent(textPart);// ww w .  j a  v a  2  s. c o  m
    content.addBodyPart(textBodyPart);
}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//w  w w  . j a  v a 2s .  c o  m
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

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

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:com.threewks.thundr.gmail.GmailMailer.java

private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Set<InternetAddress> toAddresses = getInternetAddresses(to);

    if (!toAddresses.isEmpty()) {
        email.addRecipients(javax.mail.Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[to.size()]));
    }//from ww  w .  ja  v a  2s .co  m

    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/html");
    mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    for (Attachment attachmentPdf : pdfs) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf");
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(attachmentPdf.getFileName());
        multipart.addBodyPart(mimeBodyPart);
        multipart.addBodyPart(attachment);
    }
    email.setContent(multipart);
    return email;
}

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

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override/*from ww w.  j  a  v  a 2 s . co 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:com.threewks.thundr.gmail.GmailMailer.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to       Email address of the receiver.
 * @param from     Email address of the sender, the mailbox account.
 * @param subject  Subject of the email.
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException/*  w w w  .  j  a v a 2s . c o m*/
 */
protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from,
        Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject,
        String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    try {

        email.setFrom(from);

        if (to != null) {
            email.addRecipients(javax.mail.Message.RecipientType.TO,
                    to.toArray(new InternetAddress[to.size()]));
        }
        if (cc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.CC,
                    cc.toArray(new InternetAddress[cc.size()]));
        }
        if (bcc != null) {
            email.addRecipients(javax.mail.Message.RecipientType.BCC,
                    bcc.toArray(new InternetAddress[bcc.size()]));
        }
        if (replyTo != null) {
            email.setReplyTo(new Address[] { replyTo });
        }

        email.setSubject(subject);

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/html");
        mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

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

        if (attachments != null) {
            for (com.threewks.thundr.mail.Attachment attachment : attachments) {
                mimeBodyPart = new MimeBodyPart();

                BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry);
                renderer.render(attachment.view());
                byte[] data = renderer.getOutputAsBytes();
                String attachmentContentType = renderer.getContentType();
                String attachmentCharacterEncoding = renderer.getCharacterEncoding();

                populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType,
                        attachmentCharacterEncoding);

                multipart.addBodyPart(mimeBodyPart);
            }
        }

        email.setContent(multipart);
    } catch (MessagingException e) {
        Logger.error(e.getMessage());
        Logger.error(
                "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d",
                from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to),
                Transformers.InternetAddressesToString.from(cc),
                Transformers.InternetAddressesToString.from(bcc),
                replyTo == null ? "null" : replyTo.getAddress(),
                replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText,
                attachments == null ? 0 : attachments.size());
        throw new GmailException(e);
    }

    return email;
}