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 35 total  RSS 

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

Quick and dirty email server checker, python

// description of your code here
This sends an email from a gmail account with a GUID for the subject to another email account, and then writes this GUID to file. On the other end, the other half of the program checks the GUID in the recieved message and matches it to the GUID in the file to verify that the message has been recieved. I schedule the sender to run every ten minutes, and the reciever/checker to run every minute. The reciever has a threshold value of 20 so if it has checked 20 times and not recieved the email it sends an IM to my gmail account. Whew is that contrived or what.
// First part, email sender, schedule to run every 10 minutes or so
// this uses GUID from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604

from smtplib import SMTP
from socket import sslerror         #if desired
import Guid
import os

guidSubj = Guid.generate()
guidBod1 = Guid.generate()
guidBod2 = Guid.generate()

if not os.path.exists("sent.txt"):   #check whether the file exists, if not create it
    fileHandle = open('sent.txt','w')
    fileHandle.write (guidSubj)
    fileHandle.close()
    server = SMTP('smtp.gmail.com',587)
    server.set_debuglevel(1) # or 1 for verbosity
    server.ehlo('user@gmail.com')
    server.starttls()
    server.ehlo('user@gmail.com')  # say hello again
    server.login('user@gmail.com', 'password')
    # i have a suspicion that smptlib does not add the required newline dot newline so i do it myself
    server.sendmail('user@gmail.com', 'user@place.com', "Subject:Ping," + guidSubj + '\n\n' + guidBod1 + '\n\n' + guidBod2 + '\n.\n')
    # next line generates the ignorable socket.sslerror
    server.quit()

// Second email checker/reciever, check every minute or so
# This script is a helper to clean POP3 mailboxes
# containing malformed mails that hangs MUA's, that 
# are too large, or whatever...
#
# It iterates over the non-retrieved mails, prints
# selected elements from the headers and prompt the 
# user to delete bogus messages.
#
# Written by Xavier Defrang <xavier.defrang@brutele.be>
# 

# 
import getpass, poplib, re, os, fileinput, sys, xmpp

def sendIM(toAddress=None):
    
    # Google Talk constants
    FROM_GMAIL_ID = "user@gmail.com"
    GMAIL_PASS = "pass"
    GTALK_SERVER = "talk.google.com"
    TO_GMAIL_ID = "user@gmail.com"
    jid=xmpp.protocol.JID(FROM_GMAIL_ID)
    cl=xmpp.Client(jid.getDomain(),debug=[])
    if not cl.connect((GTALK_SERVER,5222)):
        raise IOError('Can not connect to server.')
    if not cl.auth(jid.getNode(),GMAIL_PASS):
        raise IOError('Can not auth with server.')

    cl.send( xmpp.Message( TO_GMAIL_ID ,"Fix your email!" ) )
    cl.disconnect()

# Change this to your needs
POPHOST = "131.0.0.1"
POPUSER = "user"
POPPASS = "pass"

# How many lines of message body to retrieve
MAXLINES = 10

# Headers we're actually interrested in
rx_headers  = re.compile(r"^(Subject)")

try:

    # Connect to the POPer and identify user
    pop = poplib.POP3(POPHOST)
    pop.user(POPUSER)

    if not POPPASS:
        # If no password was supplied, ask for it
        POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST))

    # Authenticate user
    pop.pass_(POPPASS)

    # Get some general informations (msg_count, box_size)
    stat = pop.stat()

    bye = 0
    count_del = 0
    
    #for n in range(stat[0]):

    msgnum = stat[0]

    # Retrieve headers
    response, lines, bytes = pop.top(msgnum, MAXLINES)

    # Print message info and headers we're interrested in
    test = "".join(filter(rx_headers.match, lines))
    num = test.split(',')
    out = num[1]
    

    #Read the sent.txt file to get the GUID
    fileHandle = open ( 'sent.txt' )
    sentGuid = fileHandle.readline()
    print sentGuid
    fileHandle.close()
    
    if out == sentGuid:
        print "They match!! yay"
        pop.dele(msgnum)
        print "Message %d marked for deletion" % msgnum
        count_del += 1
        #delete the retry.txt and sent.txt file
        os.remove("retry.txt")
        os.remove("sent.txt")
    else:

        #There are no messages yet, so we will increment the retry value
        if not os.path.exists("retry.txt"):
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write('1')
            fileHandle.close()
        else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

   # Summary
    print "Deleting %d message(s) in mailbox %s@%s" % (count_del, POPUSER, POPHOST)

    # Commit operations and disconnect from server
    print "Closing POP3 session"
    pop.quit()

except poplib.error_proto, detail:

    # Fancy error handling
    print "POP3 Protocol Error:", detail

    #There are no messages yet, so we will increment the retry value
    if not os.path.exists("retry.txt"):
        fileHandle = open ( 'retry.txt','a')
        fileHandle.write('1')
        fileHandle.close()
    else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

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