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 11-20 of 35 total

Validate email and domain

// Vlidate email and domain name
<?php

function validate_email($email){

$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

if(eregi($exp,$email)){
	if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
		print("$email is ok.<br>");
			}else{
			print("$email is ok. But domain is not.<br>");
			}
				}else{
				print("$email is not ok.<br>");
				}   
}

validate_email("shantanu.ok");
validate_email("shantanu.ok@gmail.com");
validate_email("shantanu.ok@fsjaldkfjlsfjsljflsfjsldk.com");

?>

Email User Control VB .NET

Save as an .ascx file and insert into your project.
Set properties via the properties window.
Includes the form, code, validation, and css.

<%@ Control Language="VB" ClassName="Email" %>
<%@ Import Namespace="System.Net.Mail" %>



<script runat="server">
    Public Property Email() As String
        Get
            Return recipientEmail
        End Get
        Set(ByVal value As String)
            recipientEmail = value
        End Set
    End Property


    Public Property Host() As String
        Get
            Return mhost
        End Get
        Set(ByVal value As String)
            mhost = value
        End Set
    End Property


    Public Property Port() As String
        Get
            Return mport
        End Get
        Set(ByVal value As String)
            mport = value
        End Set
    End Property


    Public Property Message() As String
        Get
            Return sentMessage
        End Get
        Set(ByVal value As String)
            sentMessage = value
        End Set
    End Property
    
    Dim recipientEmail As String
    Dim mhost As String
    Dim mport As Integer
    Dim sentMessage As String
    Dim client As New Net.Mail.SmtpClient()

    Protected Sub btnSendMail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendMail.Click

        client.Host = Host
        client.Port = Port
        client.Send(txtSenderEmail.Text, recipientEmail, txtSubject.Text, txtMessage.Text)
        lblMessage.Text = sentMessage
    End Sub
</script>

<style type="text/css">
  label
  {
   	   float: left;
   	   width:10em;
   	   text-align:right;
   	   clear:left;
   	   margin-right: 7px;
   	   font-family: Tahoma, Sans-Serif;
   	   font-size:12px;
   	   font-weight:bold;
  	    padding:4px;
   		background:#FFFFFF;
   		color:#333333;
  }
  
  .validate
  {
    font-family: Tahoma, Sans-Serif;
   	font-size:12px;
  }
  
  </style>
  
<label>Email:</label><asp:TextBox ID="txtSenderEmail" runat="server" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSenderEmail"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />

<label>Subject:</label><asp:TextBox ID="txtSubject" runat="server" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtSubject"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />
<label>Message:</label><asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"
        Height="160px" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtMessage"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />
<label><asp:Label ID="lblMessage" runat="server"></asp:Label></label><asp:Button ID="btnSendMail"
        runat="server" Text="Send" />

Ultra-simplistic Ruby SMTP server

You'll know if you need this, otherwise steer clear ;-)

require 'gserver'

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

  def process_line(line)
    if (line =~ /^(HELO|EHLO)/)
      return true, "220 and..?\r\n"
    end
    if (line =~ /^QUIT/)
      return false, "bye\r\n"
    end
    if (line =~ /^MAIL FROM\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^RCPT TO\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^DATA/)
      @data_mode = true
      return true, "354 Enter message, ending with \".\" on a line by itself\r\n"
    end
    if (@data_mode) && (line.chomp =~ /^.$/)
      @data_mode = false
      return true, "220 OK\r\n"
    end
    if @data_mode
      puts line 
      return true, ""
    else
      return true, "500 ERROR\r\n"
    end
  end
end

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

Automate Defrag of Windows Host via Python

Automation script to defrag a Windows machine. The defrag results will be emailed to specified email address. This script can also handle running defrag over multiple volumes. NOTE: if you are running this on Windows 2003 64-bit you have to place a copy of defrag.exe in the same directory as the python script. Otherwise Windows will barf and say it doesn't know what defrag is. Don't know why this happens.

#*****************************************************************#
#                                                                 #
# Filename:             autodefrag.py                             #
# Date Written:         4/27/2007                                 #
#                                                                 #
# Purpose:              Intelligent interface to Windows defrag   #
#                       command. Emails results when complete.    #
#                       Can handle multiple volumes. Add this     #
#                       script to Windows task scheduler to       #
#                       fully automate defragmentation.           #
#                                                                 #
# OS:        		Windows 2003, XP                          #
#                                                                 #
#*****************************************************************#

import smtplib, sys, MimeWriter, StringIO, base64, os, time

##VARIABLES########################################################

drives = ["C:","D:","E:"]           # list of volumes to defragment
SMTP_server = "somemailserver.com"  #SMTP email server
email_to = "someone@example.com"   
email_from = "someone2@example.com"
logfile_path = "c:/"               #path to where logfile is saved

##END_VARIABLES####################################################

def mail(serverURL=None, sender='', to='', subject='', text=''):

    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('Subject', subject)
    writer.startmultipartbody('mixed')

    # start off with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    body.write(text)

    # now add an attachment
    part = writer.nextpart()
    part.addheader('Content-Transfer-Encoding', 'base64')
    body = part.startbody('text/plain')
    base64.encode(open(filename, 'rb'), body)

    # finish off
    writer.lastpart()

    # send the mail
    smtp = smtplib.SMTP(serverURL)
    smtp.sendmail(sender, to, message.getvalue())
    smtp.quit()

def timestamp():
    #mytime = time.asctime(time.localtime())
    mytime = time.strftime("%Y%m%d", time.localtime())
    return mytime

##MAIN#############################################################
#get the host name
hs = os.popen('hostname')
computer_name = hs.read()
hs.close()

mytime = timestamp()
filename = logfile_path + "DEFRAG" + mytime + ".log"

#execute the defrag command for each drive
for d in drives:
    cmd = "defrag.exe -v " + d + " >>" + filename
    print "Starting defragment: ", cmd
    errorlevel = os.system(cmd)
    if errorlevel == 0:
        print "Emailing results"
        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Complete','Disk defragmentation finished\n')
    else:
        print "Error occurred! Emailing results"
        mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Error','Disk defragmentation encountered an error')

        #hold the cmd window open if error occurred - remove this if you want window to exit
        hold = raw_input('\nPress ENTER to exit')


Obfuscate email addresses in TextMate

// Textmate / e command for obfuscating email addresses

#!/usr/bin/env ruby

email = STDIN.read
url_email = email.gsub(/./) { |c| '%' + c.unpack('H2' * c.size).join('%').upcase }
html_email = url_email[1..-1].split(/%/).collect { |c| sprintf("&#%03d;", c.to_i(16)) }.join

print "<a href=\"mailto:#{url_email}\">#{html_email}</a>"

Send Email in Python with Text File Attachment

// description of your code here
Send an email in python with a text attachment. You can change the attachment type by adjusting the part.startbody label in the attachment section (ie, 'image/jpg' or whatever)

import smtplib, sys, MimeWriter, StringIO, base64
import os
def mail(serverURL=None, sender='', to='', subject='', text=''):
    """
    Usage:
    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')
    """
    message = StringIO.StringIO()
    writer = MimeWriter.MimeWriter(message)
    writer.addheader('Subject', subject)
    writer.startmultipartbody('mixed')

    # start off with a text/plain part
    part = writer.nextpart()
    body = part.startbody('text/plain')
    body.write(text)

    # now add an attachment
    part = writer.nextpart()
    part.addheader('Content-Transfer-Encoding', 'base64')
    body = part.startbody('text/plain')
    base64.encode(open('myfile.txt', 'rb'), body)

    # finish off
    writer.lastpart()

    # send the mail
    smtp = smtplib.SMTP(serverURL)
    smtp.sendmail(sender, to, message.getvalue())
    smtp.quit()

Send an Email from Python

// description of your code here
Not sure where I got this from, but it does its job. Sends a simple smtp email message in python.
import smtplib
def mail(serverURL=None, sender='', to='', subject='', text=''):
    """
    Usage:
    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')
    """
    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
    message = headers + text
    mailServer = smtplib.SMTP(serverURL)
    mailServer.sendmail(sender, to, message)
    mailServer.quit()

javasrcritpt email to avoid spam

// email is written with javascript to hide it aganst scanning.
// if javascript is off, the email is obfuscated
<script type="text/javascript" language=javascript>
<!--
name=('hugo');
at=('@');
domain=('mueller');
dot=('.');
ext=('de');
document.write('<a href="mailto:' + name + at + domain + dot + ext + '">' + name + at + domain + dot + ext + '<\/a>');
//-->
</script>
<noscript>hugo (at) mueller (dot) de</noscript>

backup subversion repository over email

#!/bin/bash
#
# $Id: repodiff 3 2006-09-21 18:48:39Z sevkin $
#
# subversion repository incremental backup over e-mail
#
# (c) 2006 Vsevolod Balashov under terms of GNU GPL v.2 or later

SVNROOT=/var/svn
EMAIL=your@email.here
STORE=`mktemp -d`
GPGCRYPT=n

for REPO in `ls $SVNROOT`; do 
	REPOPATH=$SVNROOT/$REPO;
	if [ -r $REPOPATH/youngest ]; then
		LATEST=`cat $REPOPATH/youngest`
		YOUNGEST=`svnlook youngest $REPOPATH`
		if [ $LATEST -lt $YOUNGEST ]; then
			svnadmin dump $REPOPATH --incremental -r $LATEST:$YOUNGEST >$STORE/$REPO 2>/dev/null
		fi
	else
		svnadmin dump $REPOPATH --incremental >$STORE/$REPO 2>/dev/null
	fi 
	echo $YOUNGEST >$REPOPATH/youngest 
done

if [ `ls $STORE | wc -w` -gt 0 ]; then
	BACKUP=repodiff_`date -u +%Y%m%d%H%M%S`.tar.bz2
	ATTACH=$STORE/../$BACKUP
	tar  -C $STORE -cjf $ATTACH .
	if [ $GPGCRYPT = y ]; then
		gpg -e -r $EMAIL $ATTACH
		ATTACH=$ATTACH.gpg
	fi
	echo "." | mutt -c $EMAIL -a $ATTACH -s "repository incremental backup"
	rm -f $ATTACH
fi

rm -rf $STORE

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);
}
?>
« Newer Snippets
Older Snippets »
Showing 11-20 of 35 total