Example usage for javax.mail.internet MimeBodyPart addHeader

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

Introduction

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

Prototype

@Override
public void addHeader(String name, String value) throws MessagingException 

Source Link

Document

Add this value to the existing values for this header_name.

Usage

From source file:com.zimbra.cs.service.FeedManager.java

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr,
        Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext();) {
            if (it.next().getLocation() == null) {
                it.remove();//w  ww .j av a2s . co  m
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();

    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }

    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);

        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }

        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}

From source file:it.cnr.icar.eric.common.RepositoryItemImpl.java

/**
 * Packages the RepositoryItem as a MimeMultiPart and returns it
 *
 * @deprecated sigElement/multipart attachment is not used anymore.
 *///w  w  w .  j  av  a  2 s  .co  m
public MimeMultipart getMimeMultipart() throws RegistryException {
    MimeMultipart mp = null;
    try {
        //Create a multipart with two bodyparts
        //First bodypart is an XMLDSIG and second is the attached file
        mp = new MimeMultipart();

        //The signature part
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.transform(new DOMSource(sigElement), new StreamResult(os));

        MimeBodyPart bp1 = new MimeBodyPart();
        bp1.addHeader("Content-ID", "payload1");
        bp1.setText(os.toString(), "utf-8");
        mp.addBodyPart(bp1);

        //The payload part
        MimeBodyPart bp2 = new MimeBodyPart();
        bp2.setDataHandler(handler);
        bp2.addHeader("Content-Type", handler.getContentType());
        bp2.addHeader("Content-ID", "payload2");
        mp.addBodyPart(bp2);
    } catch (MessagingException e) {
        throw new RegistryException(e);
    } catch (TransformerException e) {
        throw new RegistryException(e);
    }
    return mp;
}

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

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }/*  w  w w . j  a  va2 s  .  c  om*/

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:lucee.runtime.net.mail.HtmlEmailImpl.java

/**
 * Embeds an URL in the HTML./*  w w  w  .ja  v  a  2 s  .c o  m*/
 *
 * <p>This method allows to embed a file located by an URL into
 * the mail body.  It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
 * returned by the embed function.
 *
 * <p>Example of use:<br><code><pre>
 * HtmlEmail he = new HtmlEmail();
 * he.setHtmlMsg("&lt;html&gt;&lt;img src=cid:" +
 *  embed("file:/my/image.gif","image.gif") +
 *  "&gt;&lt;/html&gt;");
 * // code to set the others email fields (not shown)
 * </pre></code>
 *
 * @param url The URL of the file.
 * @param cid A String with the Content-ID of the file.
 * @param name The name that will be set in the filename header
 * field.
 * @throws EmailException when URL supplied is invalid
 *  also see javax.mail.internet.MimeBodyPart for definitions
 *
 */
public void embed(URL url, String cid, String name) throws EmailException {
    // verify that the URL is valid
    try {
        InputStream is = url.openStream();
        is.close();
    } catch (IOException e) {
        throw new EmailException("Invalid URL");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(new URLDataSource(url)));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.addHeader("Content-ID", "<" + cid + ">");
        this.inlineImages.add(mbp);
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Compresses the payload using the ZLIB algorithm
 */// w ww  . j  a va2 s .  c om
private MimeBodyPart compressPayload(Partner receiver, byte[] data, String contentType)
        throws SMIMEException, MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    bodyPart.addHeader("Content-Type", contentType);
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        bodyPart.addHeader("Content-Transfer-Encoding", "base64");
    } else {
        bodyPart.addHeader("Content-Transfer-Encoding", "binary");
    }
    SMIMECompressedGenerator generator = new SMIMECompressedGenerator();
    if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
        generator.setContentTransferEncoding("base64");
    } else {
        generator.setContentTransferEncoding("binary");
    }
    return (generator.generate(bodyPart, SMIMECompressedGenerator.ZLIB));
}

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);/*from   w  ww .j  a va 2s .c  o 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.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/* w w w .  j a v  a  2 s  .  c om*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *///ww w .j  a  v a  2s. co m
public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType,
        String messageId) throws Exception {
    if (messageId == null) {
        messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification());
    }
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    AS2MessageInfo info = new AS2MessageInfo();
    info.setMessageType(messageType);
    info.setSenderId(sender.getAS2Identification());
    info.setReceiverId(receiver.getAS2Identification());
    info.setSenderEMail(sender.getEmail());
    info.setMessageId(messageId);
    info.setDirection(AS2MessageInfo.DIRECTION_OUT);
    info.setSignType(receiver.getSignType());
    info.setEncryptionType(receiver.getEncryptionType());
    info.setRequestsSyncMDN(receiver.isSyncMDN());
    if (!receiver.isSyncMDN()) {
        info.setAsyncMDNURL(sender.getMdnURL());
    }
    info.setSubject(receiver.getSubject());
    try {
        info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        //nop
    }
    //create message object to return
    AS2Message message = new AS2Message(info);
    //stores all the available body parts that have been prepared
    List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>();
    for (AS2Payload as2Payload : payloads) {
        //add payload
        message.addPayload(as2Payload);
        if (this.runtimeConnection != null) {
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            messageAccess.initializeOrUpdateMessage(info);
        }
        //no MIME message: single payload, unsigned, no CEM
        if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1
                && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
            return (this.createMessageNoMIME(message, receiver));
        }
        //MIME message
        MimeBodyPart bodyPart = new MimeBodyPart();
        String contentType = null;
        if (as2Payload.getContentType() == null) {
            contentType = receiver.getContentType();
        } else {
            contentType = as2Payload.getContentType();
        }
        bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType)));
        bodyPart.addHeader("Content-Type", contentType);
        if (as2Payload.getContentId() != null) {
            bodyPart.addHeader("Content-ID", as2Payload.getContentId());
        }
        if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
            bodyPart.addHeader("Content-Transfer-Encoding", "base64");
        } else {
            bodyPart.addHeader("Content-Transfer-Encoding", "binary");
        }
        //prepare filename to not violate the MIME header rules
        if (as2Payload.getOriginalFilename() == null) {
            as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName());
        }
        String newFilename = as2Payload.getOriginalFilename().replace(' ', '_');
        newFilename = newFilename.replace('@', '_');
        newFilename = newFilename.replace(':', '_');
        newFilename = newFilename.replace(';', '_');
        newFilename = newFilename.replace('(', '_');
        newFilename = newFilename.replace(')', '_');
        bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename);
        contentPartList.add(bodyPart);
    }
    Part contentPart = null;
    //sigle attachment? No CEM? Every CEM is in a multipart/related container
    if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
        contentPart = contentPartList.get(0);
    } else {
        //build up a new MimeMultipart container for the multiple attachments, content-type
        //is "multipart/related"
        MimeMultipart multipart = null;
        //CEM messages are always in a multipart container (even the response which contains only a single
        //payload) with the subtype "application/ediint-cert-exchange+xml".
        if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
            multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\"");
        } else {
            multipart = new MimeMultipart("related");
        }
        for (MimeBodyPart bodyPart : contentPartList) {
            multipart.addBodyPart(bodyPart);
        }
        contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null));
        contentPart.setContent(multipart, multipart.getContentType());
        ((MimeMessage) contentPart).saveChanges();
    }
    //should the content be compressed and enwrapped or just enwrapped?
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = contentPart.getSize();
        contentPart = this.compressPayload(receiver, contentPart);
        int compressedSize = contentPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (uncompressedSize == -1 || compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
    }
    //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1
    String digestOID = null;
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5);
    } else {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    }
    String mic = cryptoHelper.calculateMIC(contentPart, digestOID);
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        info.setReceivedContentMIC(mic + ", md5");
    } else {
        info.setReceivedContentMIC(mic + ", sha1");
    }
    this.enwrappInMessageAndSign(message, contentPart, sender, receiver);
    //encryption requested for the receiver?
    if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    } else {
        message.setRawData(message.getDecryptedRawData());
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
    }
    return (message);
}

From source file:dtw.webmail.util.FormdataMultipart.java

/**
 * Processes a body part of the form-data.
 * Extracts parameters and set values, and
 * leaves over the attachments.//from www.  j  av a  2 s. c  o m
 *
 * @param mbp the <tt>MimeBodyPart</tt> to be processed.
 *
 * @throws IOException if i/o operations fail.
 * @throws MessagingException if parsing or part handling with
 *         Mail API classes fails.
 */
private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException {

    //String contenttype=new String(mbp.getContentType());
    //JwmaKernel.getReference().debugLog().write("Processing "+contenttype);

    //check if a content-type is given
    String[] cts = mbp.getHeader("Content-Type");
    if (cts == null || cts.length == 0) {
        //this is a parameter, get it out and
        //remove the part.
        String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]);

        //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname);
        //retrieve value observing encoding
        InputStream in = mbp.getInputStream();
        String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
        if (encoding != null && encoding.length > 0) {
            in = MimeUtility.decode(in, encoding[0]);
        }

        String value = extractValue(in);
        if (value != null || !value.trim().equals("")) {
            addParameter(controlname, value);
        }
        //flag removal
        m_Removed = true;
        removeBodyPart(mbp);
    } else {
        String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]);

        //normally without file the control should be not successful.
        //but neither netscape nor mircosoft iexploder care much.
        //the only feature is an empty filename.
        if (filename.equals("")) {
            //kick it out too
            m_Removed = true;
            removeBodyPart(mbp);
        } else {

            //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename);

            //IExploder sends files with complete path.
            //jwma doesnt want this.
            int lastindex = filename.lastIndexOf("\\");
            if (lastindex != -1) {
                filename = filename.substring(lastindex + 1, filename.length());
            }

            //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename);

            //Observe a possible encoding
            InputStream in = mbp.getInputStream();
            String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
            if (encoding != null && encoding.length > 0) {
                in = MimeUtility.decode(in, encoding[0]);
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            OutputStream out = (OutputStream) bout;

            int i = 0;
            while ((i = in.read()) != -1) {
                //maybe more efficient in buffers, but well
                out.write(i);
            }
            out.flush();
            out.close();

            //create the datasource
            MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource(
                    //    contenttype,filename,bout.toByteArray()
                    cts[0], filename, bout.toByteArray());

            //Re-set the Content-Disposition header, in case
            //the file name was changed
            mbp.removeHeader("Content-Disposition");
            mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            //set a base64 transferencoding und the data handler
            mbp.addHeader("Content-Transfer-Encoding", "base64");
            mbp.setDataHandler(new DataHandler(mbpds));
        }
    }
}

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 {/*  w ww .j  a  v a  2 s . 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;
        }
    }
}