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 1-10 of 36 total  RSS 

Replace text template for parameter hash table

/*

Replace text template for parameter hash table

Ex:
$mytext = 'Hi, my name is {%name%}, and my address is {%address%}';
rep_templates($mytext, array('name'=>'Steven', 'address'=>'Rua Beira Mar, 12'));
print $text; //Output: Hi, my name is Steven, and my address is Rua Beira Mar, 12

Other ex.

$row = mysql_fetch_assoc($my_result_from_query);

$mytext = file_get_contents('./text_for_email_template.txt');

tranf_dados($mytext, $row);

sendmail($row['email', 'Subject:Hi mane!', $mytext);


*/
function rep_templates(&$t, $d){
    preg_match_all ( '/{\%(\w*)\%\}/' , $t , $matches );
    foreach($matches[1] as $m){
        if($d[$m]!=null){
            $pattern = "/{\%".$m."\%\}/";
            $t = preg_replace( $pattern, $d[$m], $t);
        }
    }
}

rails sendmail settings

config.action_mailer.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.sendmail_settings = {
    :location       => '/usr/sbin/sendmail',
    :arguments      => '-i -t'
}

process email files like unix find

I call this program whitelist. It lets you run a command on a bunch of files depending on whether the file is an email and has a from address in a whitelist.

It's useful for maintaining whitelisted mailboxes and analysing mailboxes. With a few more tests it might be a generically useful tool.

#!/usr/bin/python
# Copyright (C) 2008 by Tapsell-Ferrier Limited

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc.,   51 Franklin Street, Fifth Floor,
# Boston, MA  02110-1301  USA

import commands
import email.Parser
import sys
import re
import getopt
import os
import os.path

try:
    from email.utils import parseaddr
except:
    from rfc822 import parseaddr


def help():
    print """whitelist.py -h
whitelist.py [-v] [-f whitelist filename] command ; filelist [-]

Execute the specified command (which must be shell escaped if calling
from shell) on all the files in the filelist or, if - is present in
the filelist, read from stdin (like xargs) whenever the file is an
email that contains a from address specified in the whitelist.

Like xargs, or find, the command can include {} as a replacement token
for the matched filename.

The command can also be a header reference, for example:

  $FROM

will print the specified mails From address.

Options:

 -v   specifies that the test is to be negated, executing the action if
      the file does NOT contain a from address in the whiltelist.

 -f   specifies a whitelist, the default is $HOME/.addresses

For example:

 whitelist.py -f .wlist wc \{} \: maildir/cur/*

runs wc on each file in maildir/cur with a FROM address matching
something in the whitelist; or:

 find maildir/INBOX/cur -type f | whitelist.py -v mv \{} mailbox/TRASH/cur \; -

mv's all files in the INBOX with FROMs not matching the whitelist into
a TRASH folder.

  find maildir/Greylist/new -type f | whitelist.py -v $TO \; -

displays the TO address of all messages where the from didn't match
the whitelist.
"""


def read_whitelisted(filename):
    fd = open(filename)
    data = fd.read()
    fd.close()
    return data.split()

def get_msg(filename):
    fd = open(filename)
    try:
        msg = email.Parser.HeaderParser().parse(fd, True)
        return msg
    finally:
        fd.close()

action_re = re.compile("\{}")

def handle(filenames_fn, action, whitelist, negate=False):
    for filename in filenames_fn():
        msg = get_msg(filename)
        realname, addr = parseaddr(msg["from"])
        result = addr in whitelist

        if negate:
            result = not result

        if result:
            try:
                m = re.match("\$(.+)", action)
                result = msg[m.group(1)]
            except Exception:
                cmd_str = action_re.sub(filename, action)
                os.system(cmd_str)
            else:
                print result


def main(args):
    negate = False
    whitelist_filename = os.path.join(os.environ["HOME"], ".addresses")
    opts, args = getopt.getopt(args, "hv")
    for o,a in opts:
        if o == "-h":
            help()
            sys.exit(0)

        elif o == "-v":
            negate = True

        elif o == "-f":
            whitelist_filename = a

    if not os.access(whitelist_filename, os.F_OK):
        print >>sys.stderr, "whitelist.py   -  no whitelist filename\n"
        help()
        sys.exit(1)

    cmdstr = " ".join(args)
    m = re.match("(.*) ;([ ]*.*)", cmdstr)
    if not m:
        sys.exit(1)

    cmd = m.group(1)
    files = m.group(2).strip().split(" ")

    def ffn():
        for f in files:
            if f == "-":
                for innerf in sys.stdin:
                    yield innerf.strip()
            else:
                yield f
        return

    whitelist = read_whitelisted(whitelist_filename)
    handle(ffn, cmd, whitelist, negate)


if __name__ == "__main__":
    main(sys.argv[1:])

# End

Ruby SMTP Server - Save to Database

This was something I've searched for in the past but have yet to find. It's a super simple server and I'm sure there's a few bugs left in it, but the idea is simple and in my opinion, necessary. It's easy to send email from websites, but receiving it still seems dubious.

I've simply used Peter's(http://snippets.dzone.com/user/peter) ultra simplistic SMTP server and routed the email to a database table called "Emails" via ActiveRecord. It's running GServer so it should be able to handle a decent load. Like I mentioned earlier, it's probably still got some bugs, but it's a decent start.

require 'gserver'
require 'rubygems'  
require 'active_record'  
require 'yaml'
   
dbconfig = YAML::load_file(File.dirname(__FILE__) + '/config/database.yml')
ActiveRecord::Base.establish_connection(dbconfig['development']) 

class Email < ActiveRecord::Base   
end 

class SMTPServer < GServer
  def serve(io)
    @data_mode = false
    @email_message = ""
    puts "Connected"
    io.print "220 hello\r\n"
    loop do
      if IO.select([io], nil, nil, 0.1)
	      data = io.readpartial(4096)
	      puts ">>" + data
	      @email_message << data
	      ok, op = process_line(data)
	      break unless ok
	      puts "<<" + op
	      io.print op
      end
      break if io.closed?
    end
    db_insert(@email_message)
    io.print "221 bye\r\n"
    io.close
  end

  def process_line(line)
    if (@data_mode) && (line.chomp =~ /^\.$/)
      @data_mode = false
      return true, "220 OK\r\n"
    elsif @data_mode
      return true, ""
    elsif (line =~ /^(HELO|EHLO)/)
      return true, "220 and..?\r\n"
    elsif (line =~ /^QUIT/)
      return false, "bye\r\n"
    elsif (line =~ /^MAIL FROM\:/)
      return true, "220 OK\r\n"
    elsif (line =~ /^RCPT TO\:/)
      return true, "220 OK\r\n"
    elsif (line =~ /^DATA/)
      @data_mode = true
      return true, "354 Enter message, ending with \".\" on a line by itself\r\n"
    else
      return true, "500 ERROR\r\n"
    end
  end
  
  def db_insert(email)
    mail_from = (/^MAIL FROM\:<(.+)>.*$/).match(email)[1]
    rcpt_to = (/^RCPT TO\:<(.+)>.*$/).match(email)[1]
    subject = (/^Subject\: (.+)$/).match(email)[1]
    Email.create(:mail_from => mail_from, :rcpt_to => rcpt_to, :subject => subject, :email => email)
  end
  
end

a = SMTPServer.new(25)
a.start
a.join

Email in Bash

//Bash email
#!/bin/bash

function email
{
echo "this is a test" | mail -s "test" "$1"
}

if [ "$1" = "" ]; then
echo "nothing in param"
else
echo "sending mail"

#emailing attachment
#uuencode statsNbaAllStarSim statssim | mail -s "test attachement" atayebali@foxsports.com
#uuencode <filename that will be send> <name for attached file that is sent> |

#passing the param to function
email $1
fi

PHP : Comprobar e-mail válido / Check valid e-mail

Comprobar e-mail válido / Check valid e-mail
Código fuente / Source code :

function esEmailValido($email)
{
    if (ereg("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@([_a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]{2,200}\.[a-zA-Z]{2,6}$", $email ) )
	{
       return true;
    }
	else
	{
       return false;
    }
}

PHP: Email All Form Values

If you need a very basic contact form and don't want to write extra code for putting the value of each field into the email, you can use this basic email. It works best if you name your form fields something legible, such as First_Name

if (isset($_POST['Submit'])) {
	// Prepare message
	$msg = "Time: " . date("m/d/y g:ia", time()) . "\n";
	foreach ($_POST as $field=>$value) {
		if ($field != "submit") $msg .= $field . ": " . $value . "\n";
	}
	
	if (mail("TOEMAIL", "SUBJECT", $msg, "From: FROM_NAME <FROM@ADDRESS.com>")) {
		// Email was sent
	} else {
		// Erro sending email
	}
}

email validation regex

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/ 		

Check email in html form

// description of your code here

 <script type="text/javascript">
        function check_email(email_id,err_id){
            emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;
            var err_mail='Email addres incorect!';
            if(emailRegExp.test(document.getElementById(email_id).value)){
                alert('true');
                return true;
            }else{
                document.getElementById(err_id).innerHTML=err_mail;
                alert(err_mail);
                return false;
            }
        }
    </script>

        <span id="err_msg" style="color: red;"></span>
    <form id="myForm" name="myForm" action="./register.php" method="post" onsubmit="return check_email('email','err_msg');">
        <input type="text" name="email" id="email"/>
        <input  type="submit" name="send" value="Send" />
    </form>

Using POP3 to Retrieve Email for Rails App

Put this in a file called "inbox" in the scripts/ directory of your Rails app. change the host, username, and password to match.

Set up a cron job to run this script every so often (frequency depends on your needs).

#!/usr/bin/env ruby

require 'net/pop'
require File.dirname(__FILE__) + '/../config/environment'

logger = RAILS_DEFAULT_LOGGER

logger.info "Running Mail Importer..." 
Net::POP3.start("localhost", nil, "username", "password") do |pop|
  if pop.mails.empty?
    logger.info "NO MAIL" 
  else
    pop.mails.each do |email|
      begin
        logger.info "receiving mail..." 
        Notifier.receive(email.pop)
        email.delete
      rescue Exception => e
        logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message
      end
    end
  end
end
logger.info "Finished Mail Importer." 

« Newer Snippets
Older Snippets »
Showing 1-10 of 36 total  RSS