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 21-30 of 36 total

Email syntax check

// Email syntax check

<?php
function check_email($email)
{
    $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // znaky tvořící uživatelské jméno
    $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // jedna komponenta domény
    return eregi("^$atom+(\\.$atom+)*@($domain?\\.)+$domain\$", $email);
}
?>

Simple "Send Email from Ruby" Method

By Ian Purton and found at http://jiploo.com/blog/simple-email-send-function-in-ruby/

def send_email(from, from_alias, to, to_alias, subject, message)
	msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}
	
#{message}
END_OF_MESSAGE
	
	Net::SMTP.start('localhost') do |smtp|
		smtp.send_message msg, from, to
	end
end

Capture and email a traceback in Python

import traceback, smtplib, StringIO
fp = StringIO.StringIO()
traceback.print_exc(file=fp)
message = fp.getvalue()
server = smtplib.SMTP(FAILURE_SERVER)
server.sendmail(
  FAILURE_FROM,
  FAILURE_TO,
  FAILURE_MESSAGE + '\n\n' + message,
)
server.quit()

Send email with attachment(s) in Python

Can't remember if I wrote this or found it on the Web or a combination, so I won't take credit per se -- I'm just posting it as reference.

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()

EMail Cloaking

Add a class to a span element

<span class="emailCloak">you(at)somewhere.com</span>


Use this Javascript to format it into an anchor tag with the mailto link.

function emailCloak() {
	if (document.getElementById) {
		var alltags = document.all? document.all : document.getElementsByTagName("*");
		for (i=0; i < alltags.length; i++) {
		  if (alltags[i].className == "emailCloak") {
			var oldText = alltags[i].firstChild;
			var emailAddress = alltags[i].firstChild.nodeValue;
			var user = emailAddress.substring(0, emailAddress.indexOf("("));
			var website = emailAddress.substring(emailAddress.indexOf(")")+1, emailAddress.length);
			var newText = user+"@"+website;
			var a = document.createElement("a");
			a.href = "mailto:"+newText;
			var address = document.createTextNode(newText);
			a.appendChild(address);
			alltags[i].replaceChild(a,oldText);
		  }
		}
	}
}
window.onload = emailCloak;

pop2imap

// description of your code here

pop2imap --host1 westk.org --user1 rod@westk.org --password1 password --host2 orderedserver.com --user2 rod@addictedtonew.com --password2 password 

Sending html mail with embedded image

See detail in this recipe.
The code below show the key parts of embedding an image.
# require the new email package
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

...
...
msgRoot = MIMEMultipart('related')
...
...

# Assumes the image is in current directory
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

...
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
...

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.

package com.johnmunsch.util;

import org.apache.velocity.VelocityContext;

import junit.framework.TestCase;

public class BoilerplateTest extends TestCase {
    private VelocityContext context = null;
    private String testTemplate = null;

    protected void setUp() throws Exception {
        context = new VelocityContext();
        testTemplate = System.getProperty("testTemplate");
    }

    /**
     * A very basic test to see if we can get a word inserted into a template
     * with the Boilerplate class.
     * @throws Exception 
     */
    public void testApply() throws Exception {
        context.put("foo", "Velocity");
        
        String output = Boilerplate.apply(context, testTemplate);
        
        assertEquals(output, "<html><body>Hello Velocity World!</body><html>");
    }
    
    /**
     * Same sort of test as above except this time we specify a bogus name for
     * the template file and we expect to get an exception. The failure occurs
     * only if we don't have an exception thrown.
     */
    public void testApply2() {
        context.put("foo", "Velocity");

        try {
            Boilerplate.apply(context, "heyheypaula.vm");
            
            fail();
        } catch (Exception e) {
            // We expect an exception. Failure is when we don't see one.
        }
    }
}


// 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.

<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.

package com.johnmunsch.util;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import junit.framework.TestCase;

public class MailTest extends TestCase {
    String from = null;
    String to = null;
    String title = null;
    String textBody = null;
    String htmlBody = null;
    String smtpServer = null;
    
    /* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        from = System.getProperty("from");
        to = System.getProperty("to");
        title = System.getProperty("title");
        textBody = System.getProperty("textBody");
        htmlBody = System.getProperty("htmlBody");
        smtpServer = System.getProperty("smtpServer");
    }

    /**
     * This is a terrible test. It could fail just as easily because it is 
     * incorrectly supplied with parameters as due to any failure in the code.
     * @throws MessagingException 
     * @throws AddressException 
     */
    public void testSendMail() throws AddressException, MessagingException {
        Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
    }
    
    /**
     * Same test as above except that we screw up the smtpServer address so it
     * is absolute garbage. In that case we should see a failure, which we are
     * looking for, and we throw an error if we _don't_ see some kind of
     * exception.
     */
    public void testSendMailWithBadServer() {
        smtpServer = "garbageingarbageout";
        
        try {
            Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
            
            fail();
        } catch (AddressException e) {
            // Exception good, no exception bad.
        } catch (MessagingException e) {
            // Exception good, no exception bad.
        }
    }
}

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.

// Copyright (c) 2002, John Munsch
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice, 
//       this list of conditions and the following disclaimer.
// 
//     * Redistributions in binary form must reproduce the above copyright 
//       notice, this list of conditions and the following disclaimer in the 
//       documentation and/or other materials provided with the distribution.
// 
//     * Neither the name of the John Munsch nor the names of its contributors 
//       may be used to endorse or promote products derived from this software 
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
// 
// To learn more about open source licenses, please visit: 
// http://opensource.org/index.php

package com.johnmunsch.util;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

import org.apache.log4j.*;

/**
 * Handles sending email to a user. Slightly different from some of the examples
 * you see in that it will send a multi-format email with both a HTML "pretty"
 * version of the email and a straight text version.
 */
public class Mail {
    private static Logger log = Logger.getLogger(Mail.class.getName());
    
    /**
     * Send an email from one user to another user with a given subject using a
     * given SMTP host. You can send both text and HTML versions of the same
     * email, and it should in fact be the same email content in both cases,
     * because the end user's email program will be the one to pick the version
     * to display to the user.
     * 
     * @param from
     * @param to
     * @param subject
     * @param textBody
     * @param htmlBody
     * @param host
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendMail(String from, String to, String subject, 
            String textBody, String htmlBody, String host) 
            throws AddressException, MessagingException {
        // Get system properties.
        Properties props = System.getProperties();

        // Setup the mail server.
        props.put("mail.smtp.host", host);

        // Get a session.
        Session session = Session.getInstance(props, null);

        // The following is required for SMTP servers that require 
        // authentication in order to send an email.
//        Transport transport = session.getTransport("smtp");
//        transport.connect(host, username, password);
//        props.put("mail.smtp.auth", "true");

        // Define the message.
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, 
          new InternetAddress(to));
        message.setSubject(subject);
        message.setText(textBody);

        message.setContent(htmlBody, "text/html");

        // Send message
        Transport.send(message);
    }
}
« Newer Snippets
Older Snippets »
Showing 21-30 of 36 total