Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 31-39 of 39 total

Velocity 101 Unit Tests

// Unit tests for the Velocity 101 code. Note that the second test is
// actually a test to confirm that the function returns a failure
// correctly when the Velocity template file is not found.
//
// Be sure to get the test.vm file that goes with these unit tests.

   1  
   2  package com.johnmunsch.util;
   3  
   4  import org.apache.velocity.VelocityContext;
   5  
   6  import junit.framework.TestCase;
   7  
   8  public class BoilerplateTest extends TestCase {
   9      private VelocityContext context = null;
  10      private String testTemplate = null;
  11  
  12      protected void setUp() throws Exception {
  13          context = new VelocityContext();
  14          testTemplate = System.getProperty("testTemplate");
  15      }
  16  
  17      /**
  18       * A very basic test to see if we can get a word inserted into a template
  19       * with the Boilerplate class.
  20       * @throws Exception 
  21       */
  22      public void testApply() throws Exception {
  23          context.put("foo", "Velocity");
  24          
  25          String output = Boilerplate.apply(context, testTemplate);
  26          
  27          assertEquals(output, "<html><body>Hello Velocity World!</body><html>");
  28      }
  29      
  30      /**
  31       * Same sort of test as above except this time we specify a bogus name for
  32       * the template file and we expect to get an exception. The failure occurs
  33       * only if we don't have an exception thrown.
  34       */
  35      public void testApply2() {
  36          context.put("foo", "Velocity");
  37  
  38          try {
  39              Boilerplate.apply(context, "heyheypaula.vm");
  40              
  41              fail();
  42          } catch (Exception e) {
  43              // We expect an exception. Failure is when we don't see one.
  44          }
  45      }
  46  }


// This is a required file for the unit tests in "Velocity 101 Unit Tests".
// Put it into a file and make sure that the filename is passed into the unit
// test above as a System property.

   1  
   2  <html><body>Hello $foo World!</body><html>

Email 101 Unit Tests

// Two unit tests for my Email 101 code. The first expects connection information to
// be in the System properties. That can be setup as part of running the unit tests
// from either Ant or Eclipse. Note: The first test only confirms that the send occurs
// without error, not that the email was actually received or received at the correct
// address.
//
// The second test trashes the SMTP server name and then confirms that it results in
// an exception being thrown from the mail sending code.

   1  
   2  package com.johnmunsch.util;
   3  
   4  import javax.mail.MessagingException;
   5  import javax.mail.internet.AddressException;
   6  
   7  import junit.framework.TestCase;
   8  
   9  public class MailTest extends TestCase {
  10      String from = null;
  11      String to = null;
  12      String title = null;
  13      String textBody = null;
  14      String htmlBody = null;
  15      String smtpServer = null;
  16      
  17      /* (non-Javadoc)
  18       * @see junit.framework.TestCase#setUp()
  19       */
  20      protected void setUp() throws Exception {
  21          from = System.getProperty("from");
  22          to = System.getProperty("to");
  23          title = System.getProperty("title");
  24          textBody = System.getProperty("textBody");
  25          htmlBody = System.getProperty("htmlBody");
  26          smtpServer = System.getProperty("smtpServer");
  27      }
  28  
  29      /**
  30       * This is a terrible test. It could fail just as easily because it is 
  31       * incorrectly supplied with parameters as due to any failure in the code.
  32       * @throws MessagingException 
  33       * @throws AddressException 
  34       */
  35      public void testSendMail() throws AddressException, MessagingException {
  36          Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
  37      }
  38      
  39      /**
  40       * Same test as above except that we screw up the smtpServer address so it
  41       * is absolute garbage. In that case we should see a failure, which we are
  42       * looking for, and we throw an error if we _don't_ see some kind of
  43       * exception.
  44       */
  45      public void testSendMailWithBadServer() {
  46          smtpServer = "garbageingarbageout";
  47          
  48          try {
  49              Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
  50              
  51              fail();
  52          } catch (AddressException e) {
  53              // Exception good, no exception bad.
  54          } catch (MessagingException e) {
  55              // Exception good, no exception bad.
  56          }
  57      }
  58  }

Email 101

I'm leaving this code here but I'm recommending against its use. The Jakarta
Commons Email library (http://jakarta.apache.org/commons/email/) is a better
choice. It's just as easy to use but it also has support for more features
of sending email and it will handle one thing in particular that is difficult
to get right on your own.

If you want to send an email with embedded graphics and include all those
graphics in the email (i.e. they aren't just links to graphics on some remote
server) then the Commons Email library will let you do that easily. Trust me,
it beats having to figure out how to do it yourself in a way that works
across email clients.




// This example of sending mail is a little different from the typical one you
// see in Java. For one thing, when you call the function to send the email
// you send in both a plain text version of the email and an HTML version. The
// recipient's email reader will pick the version to display (usually favoring
// the HTML version if it can display both).
//
// The other thing to note is that there is some commented out code in the
// method for dealing with SMTP servers which require authentication. As best
// I can remember this code worked fine but it's not in the current version.

   1  
   2  // Copyright (c) 2002, John Munsch
   3  // All rights reserved.
   4  //
   5  // Redistribution and use in source and binary forms, with or without 
   6  // modification, are permitted provided that the following conditions are met:
   7  //
   8  //     * Redistributions of source code must retain the above copyright notice, 
   9  //       this list of conditions and the following disclaimer.
  10  // 
  11  //     * Redistributions in binary form must reproduce the above copyright 
  12  //       notice, this list of conditions and the following disclaimer in the 
  13  //       documentation and/or other materials provided with the distribution.
  14  // 
  15  //     * Neither the name of the John Munsch nor the names of its contributors 
  16  //       may be used to endorse or promote products derived from this software 
  17  //       without specific prior written permission.
  18  //
  19  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  20  // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  21  // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  22  // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  23  // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  24  // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  25  // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  26  // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  27  // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  28  // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  29  // POSSIBILITY OF SUCH DAMAGE.
  30  // 
  31  // To learn more about open source licenses, please visit: 
  32  // http://opensource.org/index.php
  33  
  34  package com.johnmunsch.util;
  35  
  36  import java.util.Properties;
  37  import javax.mail.*;
  38  import javax.mail.internet.*;
  39  
  40  import org.apache.log4j.*;
  41  
  42  /**
  43   * Handles sending email to a user. Slightly different from some of the examples
  44   * you see in that it will send a multi-format email with both a HTML "pretty"
  45   * version of the email and a straight text version.
  46   */
  47  public class Mail {
  48      private static Logger log = Logger.getLogger(Mail.class.getName());
  49      
  50      /**
  51       * Send an email from one user to another user with a given subject using a
  52       * given SMTP host. You can send both text and HTML versions of the same
  53       * email, and it should in fact be the same email content in both cases,
  54       * because the end user's email program will be the one to pick the version
  55       * to display to the user.
  56       * 
  57       * @param from
  58       * @param to
  59       * @param subject
  60       * @param textBody
  61       * @param htmlBody
  62       * @param host
  63       * @throws AddressException
  64       * @throws MessagingException
  65       */
  66      public static void sendMail(String from, String to, String subject, 
  67              String textBody, String htmlBody, String host) 
  68              throws AddressException, MessagingException {
  69          // Get system properties.
  70          Properties props = System.getProperties();
  71  
  72          // Setup the mail server.
  73          props.put("mail.smtp.host", host);
  74  
  75          // Get a session.
  76          Session session = Session.getInstance(props, null);
  77  
  78          // The following is required for SMTP servers that require 
  79          // authentication in order to send an email.
  80  //        Transport transport = session.getTransport("smtp");
  81  //        transport.connect(host, username, password);
  82  //        props.put("mail.smtp.auth", "true");
  83  
  84          // Define the message.
  85          MimeMessage message = new MimeMessage(session);
  86          message.setFrom(new InternetAddress(from));
  87          message.addRecipient(Message.RecipientType.TO, 
  88            new InternetAddress(to));
  89          message.setSubject(subject);
  90          message.setText(textBody);
  91  
  92          message.setContent(htmlBody, "text/html");
  93  
  94          // Send message
  95          Transport.send(message);
  96      }
  97  }

PHP email validation function

// Simple function to check if an given email adddress is valid

   1  
   2  function is_valid_email($email) {
   3    $result = TRUE;
   4    if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
   5      $result = FALSE;
   6    }
   7    return $result;
   8  }

Mandar mail con ASP.NET 2.0

C#
   1  
   2  MailMessage message = new MailMessage();
   3  message.From = new MailAddress("remitente@lo.que.sea");
   4  message.To.Add(new MailAddress("destinatario@lo.que.sea"));
   5  message.Subject = "Asunto";
   6  message.Body = "Cuerpo";
   7  SmtpClient client = new SmtpClient();
   8  client.Send(message);


web.config
   1  
   2  <system.net>
   3      <mailSettings>
   4          <smtp from="email@algo.com">
   5              <network host="localhost" port="25" defaultCredentials="true" />
   6          </smtp>
   7      </mailSettings>
   8  </system.net>

Hide email address from spammers with Javascript

   1  
   2  function mangle() {
   3  	if (!document.getElementsByTagName && !document.createElement &&
   4  		!document.createTextNode) return;
   5  	var nodes = document.getElementsByTagName("span");
   6  	for(var i=nodes.length-1;i>=0;i--) {
   7  		if (nodes[i].className=="change") {
   8  			var at = / at /;
   9  			var dot = / dot /g;
  10  			var node = document.createElement("a");
  11  			var address = nodes[i].firstChild.nodeValue;
  12  
  13  			address = address.replace(at, "@");
  14  			address = address.replace(dot, ".");
  15  
  16  			address = address.replace(at, "@");
  17  			address = address.replace(dot, ".");
  18  			node.setAttribute("href", "mailto:"+address);
  19  			node.appendChild(document.createTextNode(address));
  20  			
  21  			var prnt = nodes[i].parentNode;
  22  			for(var j=0;j<prnt.childNodes.length;j++)
  23  				if (prnt.childNodes[j] == nodes[i]) {
  24  					if (!prnt.replaceChild) return;
  25  					prnt.replaceChild(node, prnt.childNodes[j]);
  26  					break;
  27  				}
  28  		}
  29  	}
  30  }


You can use this script, if you'd like to post your email address to your homepage, but don't want to see it picked up by spammers.

Just run it in your onload event handler and mark emails in your HTML as:

<span class="change">markos at gaivo dot net</span>

This way they are still recognizable by those who don't use javascript.

If you need help or want to discuss this code, please do it on my blog.

Make anchors from urls and email addresses

This little PHP function will find urls and email addresses in a block of text and turn them into hyperlinks and mailto: anchors respectively.

   1  
   2  function makeLinks($sourceText) {
   3    $destText = preg_replace( "/([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})/", '<a href="mailto:\\0">\\0</a>',$sourceText);
   4    $destText = preg_replace_callback('/\bhttp[^\s]+/',create_function('$matches', 'return "<a href=\"$matches[0]\">" . preg_replace("#(\.|/)#", "&shy;$1", $matches[0]) . "</a>";'),$destText);
   5    return $destText;
   6  }

Mail a file as an attachment from the UNIX prompt

   1  uuencode file.txt file.txt | mail email@address.com

Clearing out a bunch of spam with spoofed emails that were bounced back to some poor guy with a catchall email

We don't really want to delete them all just in case.

   1  
   2  cd /usr/local/scratch/
   3  mkdir junk
   4  find /var/spool/postfix -exec grep "somediscernible-feature.com" '{}' \; | awk '{print($3)}' | xargs -J X mv X ./junk/


The "find" produces

   1  
   2  Binary file /var/spool/postfix/active/D/D8832E38 matches
   3  Binary file /var/spool/postfix/active/D/D78EC1C72 matches
   4  Binary file /var/spool/postfix/active/D/D593D279D matches
   5  Binary file /var/spool/postfix/active/D/D0EB32833 matches


The awk

   1  
   2  /var/spool/postfix/active/D/D8832E38
   3  /var/spool/postfix/active/D/D78EC1C72
   4  /var/spool/postfix/active/D/D593D279D
   5  /var/spool/postfix/active/D/D0EB32833


And then the mv, moves it.
« Newer Snippets
Older Snippets »
Showing 31-39 of 39 total