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

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

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

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()

Authenticate with SMTP server before sending email

For more info see: http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html

You need activation.jar, smtp.jar, and mailapi.jar in your classpath for this to work.

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
	public static void main(String[] args) throws MessagingException {
		new MailWithPasswordAuthentication().run();
	}

	private void run() throws MessagingException {
		Message message = new MimeMessage(getSession());

		message.addRecipient(RecipientType.TO, new InternetAddress("to@example.com"));
		message.addFrom(new InternetAddress[] { new InternetAddress("from@example.com") });

		message.setSubject("the subject");
		message.setContent("the body", "text/plain");

		Transport.send(message);
	}

	private Session getSession() {
		Authenticator authenticator = new Authenticator();

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("mail.smtp.host", "mail.example.com");
		properties.setProperty("mail.smtp.port", "25");

		return Session.getInstance(properties, authenticator);
	}

	private class Authenticator extends javax.mail.Authenticator {
		private PasswordAuthentication authentication;

		public Authenticator() {
			String username = "auth-user";
			String password = "auth-password";
			authentication = new PasswordAuthentication(username, password);
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return authentication;
		}
	}
}

CPP SMTP Client

An SMTP client in CPP, apparently for a Linux machine. It was found in my old source code folder and so may not be fully working.


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>

#define HELO "HELO\n"
#define DATA "DATA\n"
#define QUIT "QUIT\n"

FILE *fin;
int sock;
struct sockaddr_in server;
struct hostent *hp, *gethostbyname();
char buf[BUFSIZ+1];
int len;
char *host_id;
char *from_id;
char *to_id;
char *file_id;
char wkstr[100];

/*=====Send a string to the socket=====*/

send_socket(char *s)
{
	write(sock,s,strlen(s));
	write(1,s,strlen(s));
}

/*=====Read a string from the socket=====*/

read_socket()
{
	len = read(sock,buf,BUFSIZ);
	write(1,buf,len);
}

/*=====MAIN=====*/
int main(int argc, char* argv[])
{

if(argc != 5)
{
 printf("USAGE: %s <host> <from> <to> <filename>\n\n", argv[0]);
 exit(1);
}

host_id=argv[1];
from_id=argv[2];
to_id=argv[3];
file_id=argv[4];

/*=====Create Socket=====*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock==-1)
{
 perror("opening stream socket");
 exit(1);
}

/*=====Verify host=====*/
server.sin_family = AF_INET;
hp = gethostbyname(host_id);
if (hp==(struct hostent *) 0)
{
 fprintf(stderr, "%s: unknown host\n", host_id);
 exit(2);
}

/*=====Connect to port 25 on remote host=====*/
printf ("hostent %s\n", hp->h_addr_list[0]);
memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);

server.sin_port=htons(25); /* SMTP PORT */

if (connect(sock, (struct sockaddr *) &server, sizeof server)==-1)
{
 perror("connecting stream socket");
 exit(1);
}

/*=====Write some data then read some =====*/

read_socket(); /* SMTP Server logon string */

send_socket(HELO); /* introduce ourselves */
read_socket(); /*Read reply */

send_socket("MAIL from: "); /* Mail from us */
send_socket(from_id);
send_socket("\n");
read_socket(); /* Sender OK */

send_socket("RCPT To: "); /*Mail to*/
send_socket(to_id);
send_socket("\n");
read_socket(); /*Recipient OK*/

send_socket(DATA);/*body to follow*/
read_socket(); /*ok to send */

fin=fopen(file_id, "r"); /* open file */
while(1)
{
 if(fgets(wkstr, 100, fin)==NULL) break; /* exit on EOF */
 send_socket(wkstr);
}
fclose(fin); /* close file */

send_socket(fin); /*send file*/
send_socket(".\n");

read_socket(); /* OK*/
send_socket(QUIT); /* quit */
read_socket(); /* log off */

/*=====Close socket and finish=====*/
close(sock);
exit(0);
}


Simple webform to test mail

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Mail" %>
<script runat="server">    
void btnSubmit_Click(Object sender, EventArgs e) {
  MailMessage mail = new MailMessage();
  mail.To = txtTo.Text;
  mail.From = txtFrom.Text;
  mail.Subject = txtSubject.Text;
  mail.Body = txtMessage.Text;
  mail.Priority = MailPriority.High;
  mail.BodyFormat = MailFormat.Text;
  SmtpMail.SmtpServer = txtSmtpServer.Text;
  if (txtSmtpUsername.Text.Trim() != "") {
    if (txtSmtpPassword.Text.Trim() != "") {
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", txtSmtpUsername.Text);
      mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", txtSmtpPassword.Text);
    }
  }
  try {
    SmtpMail.Send(mail);
    Response.Write("OK!");
  } catch (Exception ex) {
    Response.Write("KO: " + ex.ToString());
  }
}
</script>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Mail test</title>
  </head>
  <body>
    <form runat="server">
      <ul>
        <li>Smtp Server : <asp:TextBox id="txtSmtpServer" runat="server"></asp:TextBox></li>
        <li>Smtp Username : <asp:TextBox id="txtSmtpUsername" runat="server"></asp:TextBox></li>
        <li>Smtp Password : <asp:TextBox id="txtSmtpPassword" runat="server"></asp:TextBox></li>
        <li>From : <asp:TextBox id="txtFrom" runat="server"></asp:TextBox></li>
        <li>To : <asp:TextBox id="txtTo" runat="server"></asp:TextBox></li>
        <li>Subject : <asp:TextBox id="txtSubject" runat="server"></asp:TextBox></li>
        <li>Message : <asp:TextBox id="txtMessage" TextMode="MultiLine" runat="server"></asp:TextBox></li>
      </ul>
      <asp:Button runat="server" id="btnSubmit" OnClick="btnSubmit_Click" Text="Send"></asp:Button>
    </form>
  </body>
</html>

python : send a mail (text), with attachments

import smtplib
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
import os

def sendMail(to, subject, text, files=[],server="localhost"):
    assert type(to)==list
    assert type(files)==list
    fro = "Expediteur <expediteur@mail.com>"

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

    msg.attach( MIMEText(text) )

    for file 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(file))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, to, msg.as_string() )
    smtp.close()


sendMail(
        ["destination@dest.kio"],
        "hello","cheers",
        ["photo.jpg","memo.sxw"]
    )

python : send a mail (text)

import smtplib
from email.MIMEText import MIMEText

def sendTextMail(to,sujet,text,server="localhost"):
    fro = "Expediteur <expediteur@mail.com>"
    mail = MIMEText(text)
    mail['From'] = fro
    mail['Subject'] =sujet
    mail['To'] = to
    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, [to], mail.as_string())
    smtp.close()
    
sendTextMail("toto@titi.com","hello","cheers")

Sending Mail

This code requires JavaMail. Specifically it requires mailapi.jar and smtp.jar from the JavaMail distribution (available at http://java.sun.com/) as well as activation.jar from the JavaBeans Activation Framework (available at http://java.sun.com/beans/glasgow/jaf.html).

Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-host.com");
Session session = Session.getDefaultInstance(props, null);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/plain");

Transport.send(msg);
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS