commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From francesco <france...@brisa.homelinux.net>
Subject email info
Date Mon, 20 Sep 2004 20:46:01 GMT
Hi, I'm Francesco from italy,

I was using the commons-email package, and I added 2 little changes to 
the code, so I sent email to the lists of develepers of that package, 
but nobody answerred me.

At least If I have done something wrong, I was expecting something like: 
your code is not ok, or you have done some mistake, but nobody answerred 
me, maybe I have to be subscribed to the mailing list ?

however, here I send a copy of the message I treied to send.

Goodbye everybody.
p.s. question: can I send attachments in the mails to this mailing list ?

This is the original message:

Hy, I'm Francesco from Italy,

I used the commons-email packate to create html email and I had one
problem on embedding files:
the function you use to create unique cid is creating bad
characters(@!"£$%&....), which are hard to be well interpreted by my
email-client  (mozilla-thunderbird);

So I replaced the function using htis:

          /** Images embedded, usefull to create the cid ID */
          private int imageCounter=0;

and:

          String cid=new Integer(imageCounter).toString();
          imageCounter++;

in the embed function.

this create a cid like: 1 than 2 and son on....
is still unique and works well.

Then I also writed this function that i think you might find usefull:

It takes as parameter the path to an html file and insert it and it's
src links into the email, creating the appropriated cid values.

I have attached in the zip the replaced htmlEmail.java I modified and a
test example.

let me know if I have done good please

SALUTES
Brisa Francesco

      /**
       * loads an html page from the give path and inserts it in the
email, ll the links in the page are embedded, and the html tags are
replaced with appropriate cids
       * @param htmlFilePosition path to the html page to use
       * @throws IOException file can not be found or loaded
       * @throws MessagingException no valid srcs in html page
       * @return true = succesfully loaded into the body
       * false = something went wrong
       */
      public boolean loadHtmlTemplate(String htmlFilePosition) throws
java.io.IOException,MessagingException {

          // Open the html file conteining text to be used
          if (! (htmlFilePosition.equals(""))) {
              String readLine="";

              String htmlText="";

              java.io.BufferedReader in = new java.io.BufferedReader(new
java.io.FileReader(htmlFilePosition));
              while ((readLine = in.readLine()) != null) {
                  htmlText=htmlText+readLine+"\n";
              }
              in.close();



              // Create a reader on the HTML content
              ArrayList htmlSrcFile=new ArrayList();


              // temp to store changes
              String oldHtmlText="-";



              // while I'm making changes to the html, continue searching
for src tag
              while (! (oldHtmlText.equals(htmlText))) {
                  oldHtmlText=htmlText;

                  java.util.regex.Pattern patt =
java.util.regex.Pattern.compile("src=\"([\\w|\\p{Punct}]*)\"");
                  java.util.regex.Matcher match = patt.matcher(htmlText);


                  if (match.find()) {

                      boolean esci=false;
                      while (match.group(1).indexOf("cid:")>=0) {
                          if (! match.find()) {
                              esci=true;
                              break;
                          }
                      }
                      if (esci) {
                          break;
                      }

                      String pre=htmlText.substring(0, match.start());
                      String fileName=(match.group(1));
                      String post=htmlText.substring(match.end());

                      // strip file: if exists
                      fileName=fileName.replaceFirst("file:","");

                      // strip any // or \\
                      String ori1="";
                      while (! (ori1.equals(fileName))) {
                          ori1=fileName;
                          fileName=fileName.replaceAll("//","/");
                          fileName=fileName.replaceAll("\\\\","\\ ");
                      }


                      // try to open the src file
                      java.io.File fi=new java.io.File(fileName);

                      // maybe we found a relative link, not absolute, so
we have to add directory path of the html file
                      if (! fi.exists()) {
                          fi=new java.io.File((new
java.io.File(htmlFilePosition).getParent())+"/"+fileName);
                      }

                      String
cid="src=\"cid:"+embed(fi.toURL(),fi.getName())+"\"";

                      htmlText=pre+cid+post;
                  }
              }

              // finally set the corrected html file !
              setHtmlMsg(htmlText);

              return true;
          }


          return false;
      }



------------------------------------------------------------------------

/*
 * Copyright 2001-2004 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.mail;

import java.net.URL;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.RandomStringUtils;

/**
 * An HTML multipart email.
 *
 * <p>This class is used to send HTML formatted email.  A text message
 * can also be set for HTML unaware email clients, such as text-based
 * email clients.
 *
 * <p>This class also inherits from MultiPartEmail, so it is easy to
 * add attachents to the email.
 *
 * <p>To send an email in HTML, one should create a HtmlEmail, then
 * use the setFrom, addTo, etc. methods.  The HTML content can be set
 * with the setHtmlMsg method.  The alternate text content can be set
 * with setTextMsg.
 *
 * <p>Either the text or HTML can be omitted, in which case the "main"
 * part of the multipart becomes whichever is supplied rather than a
 * multipart/alternative.
 *
 * @author <a href="mailto:unknown">Regis Koenig</a>
 * @author <a href="mailto:sean@informage.net">Sean Legassick</a>
 * @version $Id: HtmlEmail.java,v 1.8 2004/02/19 22:38:09 scolebourne Exp $
 */
public class HtmlEmail extends MultiPartEmail
{
    /**
     * Text part of the message.  This will be used as alternative text if
     * the email client does not support HTML messages.
     */
    private String text;

    /** Html part of the message */
    private String html;

    /** Embeded images */
    private List inlineImages = new ArrayList();
    
    /** Images embedded, usefull to create the cid ID */
    private int imageCounter=0;

    /**
     * Set the text content.
     *
     * @param text A String.
     * @return An HtmlEmail.
     */
    public HtmlEmail setTextMsg(String text)
    {
        this.text = text;
        return this;
    }

    /**
     * Set the HTML content.
     *
     * @param html A String.
     * @return An HtmlEmail.
     */
    public HtmlEmail setHtmlMsg(String html)
    {
        this.html = html;
        return this;
    }

    /**
     * Set the message.
     *
     * <p>This method overrides the MultiPartEmail setMsg() method in
     * order to send an HTML message instead of a full text message in
     * the mail body. The message is formatted in HTML for the HTML
     * part of the message, it is let as is in the alternate text
     * part.
     *
     * @param msg A String.
     * @return An Email.
     */
    public Email setMsg(String msg)
    {
        setTextMsg(msg);

        setHtmlMsg(new StringBuffer()
                .append("<html><body><pre>")
                .append(msg)
                .append("</pre></body></html>")
                .toString());

        return this;
    }

    /**
     * Embeds an URL in the HTML.
     *
     * <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 name The name that will be set in the filename header
     * field.
     * @return A String with the Content-ID of the file.
     * @exception MessagingException
     */
    public String embed(URL url, String name) throws MessagingException
    {
        MimeBodyPart mbp = new MimeBodyPart();

        mbp.setDataHandler (new DataHandler(new URLDataSource(url)));
        mbp.setFileName(name);
        mbp.setDisposition("inline");

        String cid=new Integer(imageCounter).toString();
        imageCounter++;
        
        mbp.addHeader("Content-ID", cid);

        inlineImages.add(mbp);
        return mbp.getContentID();
    }

    /**
     * Does the work of actually sending the email.
     *
     * @exception MessagingException if there was an error.
     */
    public void send() throws MessagingException
    {
        MimeMultipart container = this.getContainer();
        container.setSubType("related");

        BodyPart msgText = null;
        BodyPart msgHtml = null;

        if (StringUtils.isNotEmpty(html))
        {
            msgHtml = this.getPrimaryBodyPart();
            if (charset != null)
            {
                msgHtml.setContent(html, TEXT_HTML + ";charset=" + charset);
            }
            else
            {
                msgHtml.setContent(html, TEXT_HTML);
            }

            for (Iterator iter = inlineImages.iterator(); iter.hasNext();)
            {
                container.addBodyPart((BodyPart)iter.next());
            }

        }

        if (StringUtils.isNotEmpty(text))
        {
            // if the html part of the message was null, then the text part
            // will become the primary body part
            if (msgHtml == null)
            {
                msgText = getPrimaryBodyPart();
            }
            else
            {
                msgText = new MimeBodyPart();
                container.addBodyPart(msgText);
            }

            if (charset != null)
            {
                msgText.setContent(text, TEXT_PLAIN + ";charset=" + charset);
            }
            else
            {
                msgText.setContent(text, TEXT_PLAIN);
            }

        }

        super.send();
    }

    /**
     * Validates that the supplied string is neither <code>null</code>
     * nor the empty string.
     *
     * @param foo The text to check.
     * @return Whether valid.
     * @deprecated use StringUtils.isNotEmpty instead
     */
    public static final boolean isValid(String foo)
    {
        return StringUtils.isNotEmpty(foo);
    }
    
    
    /**
     * loads an html page from the give path and inserts it in the email, ll the links in
the page are embedded, and the html tags are replaced with appropriate cids
     * @param htmlFilePosition path to the html page to use
     * @throws IOException file can not be found or loaded
     * @throws MessagingException no valid srcs in html page
     * @return true = succesfully loaded into the body
     * false = something went wrong
     */    
    public boolean loadHtmlTemplate(String htmlFilePosition) throws java.io.IOException,MessagingException
{        
        
        // Open the html file conteining text to be used
        if (! (htmlFilePosition.equals(""))) {
            String readLine="";            
            
            String htmlText="";
            
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader(htmlFilePosition));
       
            while ((readLine = in.readLine()) != null) {            
                htmlText=htmlText+readLine+"\n";
            }
            in.close();
            

            
            // Create a reader on the HTML content
            ArrayList htmlSrcFile=new ArrayList();

            
            // temp to store changes
            String oldHtmlText="-";
            
            
            
            // while I'm making changes to the html, continue searching for src tag
            while (! (oldHtmlText.equals(htmlText))) {
                oldHtmlText=htmlText;
                
                java.util.regex.Pattern patt = java.util.regex.Pattern.compile("src=\"([\\w|\\p{Punct}]*)\"");
   
                java.util.regex.Matcher match = patt.matcher(htmlText);
                
                
                if (match.find()) {
                    
                    boolean esci=false;
                    while (match.group(1).indexOf("cid:")>=0) {
                        if (! match.find()) {
                            esci=true;
                            break;
                        }
                    }
                    if (esci) {
                        break;
                    }
                    
                    String pre=htmlText.substring(0, match.start());      
                    String fileName=(match.group(1));                    
                    String post=htmlText.substring(match.end());
                    
                    // strip file: if exists
                    fileName=fileName.replaceFirst("file:","");

                    // strip any // or \\
                    String ori1="";
                    while (! (ori1.equals(fileName))) {
                        ori1=fileName;
                        fileName=fileName.replaceAll("//","/");
                        fileName=fileName.replaceAll("\\\\","\\ ");
                    }


                    // try to open the src file
                    java.io.File fi=new java.io.File(fileName);

                    // maybe we found a relative link, not absolute, so we have to add directory
path of the html file
                    if (! fi.exists()) {
                        fi=new java.io.File((new java.io.File(htmlFilePosition).getParent())+"/"+fileName);
                    }

                    String cid="src=\"cid:"+embed(fi.toURL(),fi.getName())+"\"";
                    
                    htmlText=pre+cid+post;
                }
            }
            
            // finally set the corrected html file !
            setHtmlMsg(htmlText);            
            
            return true;
        }
        
        
        return false;
    }
}






---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message