Example usage for javax.mail.internet MimeBodyPart setContentID

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

Introduction

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

Prototype

public void setContentID(String cid) throws MessagingException 

Source Link

Document

Set the "Content-ID" header field of this body part.

Usage

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java

protected void setBlob(Blob blob, String id) throws MessagingException, IOException {
    MimeBodyPart part = new MimeBodyPart();
    if (blob instanceof HasFile) {
        part.attachFile(((HasFile) blob).getFile());
    } else {//ww w  .  ja  v  a  2 s.c o m
        part.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        part.setFileName(blob.getFileName());
    }
    part.setHeader("Content-Type", blob.getMimeType());
    part.setHeader("Content-Transfer-Encoding", "binary");
    int length = blob.getLength();
    if (length > -1) {
        part.setHeader("Content-Length", Integer.toString(length));
    }
    part.setContentID(id);
    mp.addBodyPart(part);
}

From source file:eagle.common.email.EagleMailClient.java

public boolean send(String from, String to, String cc, String title, String templatePath,
        VelocityContext context, Map<String, File> attachments) {
    if (attachments == null || attachments.isEmpty()) {
        return send(from, to, cc, title, templatePath, context);
    }/* ww  w . j  a va  2  s  .c om*/
    Template t = null;

    List<MimeBodyPart> mimeBodyParts = new ArrayList<MimeBodyPart>();
    Map<String, String> cid = new HashMap<String, String>();

    for (Map.Entry<String, File> entry : attachments.entrySet()) {
        final String attachment = entry.getKey();
        final File attachmentFile = entry.getValue();
        final MimeBodyPart mimeBodyPart = new MimeBodyPart();
        if (attachmentFile != null && attachmentFile.exists()) {
            DataSource source = new FileDataSource(attachmentFile);
            try {
                mimeBodyPart.setDataHandler(new DataHandler(source));
                mimeBodyPart.setFileName(attachment);
                mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                mimeBodyPart.setContentID(attachment);
                cid.put(attachment, mimeBodyPart.getContentID());
                mimeBodyParts.add(mimeBodyPart);
            } catch (MessagingException e) {
                LOG.error("Generate mail failed, got exception while attaching files: " + e.getMessage(), e);
            }
        } else {
            LOG.error("Attachment: " + attachment + " is null or not exists");
        }
    }
    //TODO remove cid, because not used at all
    if (LOG.isDebugEnabled())
        LOG.debug("Cid maps: " + cid);
    context.put("cid", cid);

    try {
        t = velocityEngine.getTemplate(BASE_PATH + templatePath);
    } catch (ResourceNotFoundException ex) {
        //         LOGGER.error("Template not found:"+BASE_PATH + templatePath, ex);
    }

    if (t == null) {
        try {
            t = velocityEngine.getTemplate(templatePath);
        } catch (ResourceNotFoundException e) {
            try {
                t = velocityEngine.getTemplate("/" + templatePath);
            } catch (Exception ex) {
                LOG.error("Template not found:" + "/" + templatePath, ex);
            }
        }
    }

    final StringWriter writer = new StringWriter();
    t.merge(context, writer);
    if (LOG.isDebugEnabled())
        LOG.debug(writer.toString());
    return this._send(from, to, cc, title, writer.toString(), mimeBodyParts);
}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper,
        String defaultEncoding) throws Exception {
    Map cache = new HashMap();
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart part = new MimeBodyPart();
    multipart.addBodyPart(part);//  ww  w . ja  v a 2 s  . co m

    String encoding = defaultEncoding;
    if (submission.getEncoding() != null) {
        encoding = submission.getEncoding();
    }

    if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) {
        part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding),
                encoding);
    } else {
        part.setText(node.getTextContent());
    }
    part.setContentID("<instance.xml@start>");
    part.addHeader("Content-Type", "application/xml");
    part.addHeader("Content-Transfer-Encoding", "base64");
    part.setDisposition("attachment");
    part.setFileName("instance.xml");

    multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\"");
    // FIXME: Is this a global http header or a local mime header?
    wrapper.getBodyStream()
            .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n")
                    .getBytes(encoding));
    multipart.writeTo(wrapper.getBodyStream());
}

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

protected void populateMimeBodyPart(MimeBodyPart mimeBodyPart, Attachment attachment, byte[] data,
        String attachmentContentType, String attachmentCharacterEncoding) throws MessagingException {
    String fullContentType = attachmentContentType + "; charset=" + attachmentCharacterEncoding;
    mimeBodyPart.setFileName(attachment.name());
    mimeBodyPart.setContent(data, fullContentType);
    mimeBodyPart.setDisposition(attachment.disposition().toString());
    if (attachment.isInline()) {
        mimeBodyPart.setContentID("<" + attachment.name() + ">");
    }/*from w w  w.  j a v a2 s.  c  o m*/
}

From source file:immf.MyHtmlEmail.java

/**
 * Embeds the specified <code>DataSource</code> in the HTML using the
 * specified Content-ID. Returns the specified Content-ID string.
 *
 * @param dataSource the <code>DataSource</code> to embed
 * @param name the name that will be set in the filename header field
 * @param cid the Content-ID to use for this <code>DataSource</code>
 * @return the supplied Content-ID for this <code>DataSource</code>
 * @throws EmailException if the embedding fails or if <code>name</code> is
 * null or empty/*from  w  ww  .j  a  va 2s .com*/
 * @since 1.1
 */
public String embed(DataSource dataSource, String name, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:immf.MyHtmlEmail.java

public String embed(DataSource dataSource, String name, String nameCharset, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }/*from  w w  w.java 2  s .com*/

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        Util.setFileName(mbp, name, nameCharset, null);
        //mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //from   w  w  w . j  a  v  a  2s. c  o  m
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    String name = attachment.getFilename();
    byte[] stream = attachment.getContent();
    File temp = File.createTempFile("tmpfile", ".tmp");
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(stream);
    fos.close();
    DataSource source = new FileDataSource(temp);
    MimeBodyPart part = new MimeBodyPart();
    String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

    part.setDataHandler(new DataHandler(source));
    part.setHeader("Content-Type", mimeType);
    part.setFileName(name);
    part.setContentID("<" + name + ">");
    part.setDisposition("inline");

    temp.deleteOnExit();

    return part;
}

From source file:lucee.runtime.net.smtp.SMTPClient.java

public MimeBodyPart toMimeBodyPart(Multipart mp, lucee.runtime.config.Config config, Attachment att)
        throws MessagingException {

    MimeBodyPart mbp = new MimeBodyPart();

    // set Data Source
    String strRes = att.getAbsolutePath();
    if (!StringUtil.isEmpty(strRes)) {

        mbp.setDataHandler(new DataHandler(new ResourceDataSource(config.getResource(strRes))));
    } else//from  ww w.ja  v  a2  s  .  co  m
        mbp.setDataHandler(new DataHandler(new URLDataSource2(att.getURL())));

    mbp.setFileName(att.getFileName());
    if (!StringUtil.isEmpty(att.getType()))
        mbp.setHeader("Content-Type", att.getType());
    if (!StringUtil.isEmpty(att.getDisposition())) {
        mbp.setDisposition(att.getDisposition());
        /*if(mp instanceof MimeMultipart) {
           ((MimeMultipart)mp).setSubType("related");
        }*/

    }
    if (!StringUtil.isEmpty(att.getContentID()))
        mbp.setContentID(att.getContentID());

    return mbp;
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

private void addMtomPart(MimeMultipart mp, RequestableHttpVariable variable, Object httpVariableValue)
        throws IOException, MessagingException {
    String stringValue = ParameterUtils.toString(httpVariableValue);
    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue,
            getProject().getName());//  ww  w .  j  a v  a2s.co m
    String cid = variable.getMtomCid(stringValue);

    Engine.logBeans.debug("(HttpConnector) Prepare the MTOM attachment with cid: " + cid
            + ". Converting the path '" + stringValue + "' to '" + filepath + "'");

    MimeBodyPart bp = new MimeBodyPart();
    bp.attachFile(filepath);
    bp.setContentID(cid);
    mp.addBodyPart(bp);
}

From source file:net.spfbl.http.ServerHTTP.java

private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email)
        throws MessagingException {
    if (url == null) {
        return false;
    } else if (!Core.hasOutputSMTP()) {
        return false;
    } else if (!Core.hasAdminEmail()) {
        return false;
    } else if (!Domain.isEmail(email)) {
        return false;
    } else if (NoReply.contains(email, true)) {
        return false;
    } else {/*from  w  ww .j  a  v a2s.  c o  m*/
        try {
            Server.logDebug("sending unblock by e-mail.");
            User user = User.get(email);
            InternetAddress[] recipients;
            if (user == null) {
                recipients = InternetAddress.parse(email);
            } else {
                recipients = new InternetAddress[1];
                recipients[0] = user.getInternetAddress();
            }
            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setHeader("Date", Core.getEmailDate());
            message.setFrom(Core.getAdminInternetAddress());
            message.addRecipients(Message.RecipientType.TO, recipients);
            String subject;
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                subject = "Chave de desbloqueio SPFBL";
            } else {
                subject = "Unblocking key SPFBL";
            }
            message.setSubject(subject);
            // Corpo da mensagem.
            StringBuilder builder = new StringBuilder();
            builder.append("<!DOCTYPE html>\n");
            builder.append("<html lang=\"");
            builder.append(locale.getLanguage());
            builder.append("\">\n");
            builder.append("  <head>\n");
            builder.append("    <meta charset=\"UTF-8\">\n");
            builder.append("    <title>");
            builder.append(subject);
            builder.append("</title>\n");
            loadStyleCSS(builder);
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildConfirmAction(builder, "Desbloquear IP", url,
                        "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net",
                        "http://spfbl.net/");
            } else {
                buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL",
                        "SPFBL.net", "http://spfbl.net/en/");
            }
            builder.append("  </head>\n");
            builder.append("  <body>\n");
            builder.append("    <div id=\"container\">\n");
            builder.append("      <div id=\"divlogo\">\n");
            builder.append("        <img src=\"cid:logo\">\n");
            builder.append("      </div>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL");
                buildText(builder,
                        "Se voc  o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:");
            } else {
                buildMessage(builder, "Unblock of IP " + ip + " at DNSBL");
                buildText(builder,
                        "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:");
            }
            buildText(builder, "<a href=\"" + url + "\">" + url + "</a>");
            buildFooter(builder, locale);
            builder.append("    </div>\n");
            builder.append("  </body>\n");
            builder.append("</html>\n");
            // Making HTML part.
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8");
            // Making logo part.
            MimeBodyPart logoPart = new MimeBodyPart();
            File logoFile = getWebFile("logo.png");
            logoPart.attachFile(logoFile);
            logoPart.setContentID("<logo>");
            logoPart.addHeader("Content-Type", "image/png");
            logoPart.setDisposition(MimeBodyPart.INLINE);
            // Join both parts.
            MimeMultipart content = new MimeMultipart("related");
            content.addBodyPart(htmlPart);
            content.addBodyPart(logoPart);
            // Set multiplart content.
            message.setContent(content);
            message.saveChanges();
            // Enviar mensagem.
            return Core.sendMessage(message, 30000);
        } catch (MailConnectException ex) {
            throw ex;
        } catch (SendFailedException ex) {
            throw ex;
        } catch (MessagingException ex) {
            throw ex;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        }
    }
}