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

Retrieve your Gmail messages as an XML feed

This Ruby example shows how to retrieve your most recent email as an atom XML feed from the Google Apps website.

require 'rubygems'
require 'httpclient'

url = "https://mail.google.com/a/yourwebsite.com/feed/atom"
client = HTTPClient.new
client.debug_dev = STDOUT if $DEBUG
client.set_auth(url, 'yourname@yourwebsite.com', 'yourpassword')
resp = client.get(url)


Note: You might require to gem install httpclient.

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

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

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;
		}
	}
}

获�Exchange未读邮件数

// description of your code here

private int GetUnReadMailCount()
{
string url=“http://mail.felixwoo.com/exchange/�; //指定Exchange�务器地� 
System.Net.HttpWebRequest Request;
System.Net.WebResponse Response;
System.Net.CredentialCache MyCredentialCache;
string strUserName = “wufâ€?; //指定登录的用户å??
string strRootURI = url+strUserName ; //得到�访问邮箱的WebDAV地�
string strPassword = “123456�; //指定该用户的密�
string strDomain = “felixwoo.comâ€?; //指定域å??
string strQuery ="";
byte[] bytes = null;
System.IO.Stream RequestStream = null;
System.IO.Stream ResponseStream = null;
XmlDocument ResponseXmlDoc = null;
XmlNodeList HrefNodes= null;
XmlNodeList SizeNodes= null;
int count=0;
try
{
  // 用SQL查询WebDAV返回结果中的unreadcount节点.
  strQuery = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
   + "<D:sql>SELECT \"DAV:displayname\",\"urn:schemas:httpmail:unreadcount\" FROM \"" + strRootURI + "\""
   + "</D:sql></D:searchrequest>";

  // 创建新的CredentialCache对象,构建身份凭�
  MyCredentialCache = new System.Net.CredentialCache();
  MyCredentialCache.Add( new System.Uri(strRootURI),
   "NTLM",
   new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
   );

  // Create the HttpWebRequest object.
  Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strRootURI);

  // 指定HttpWebRequest的身份凭�,此处为关键所在。如果使用之�
  // 创建的MyCredentialCache,则这个身份凭�是�以从Web�务器传递
  // 到Exchange�务器的,但是这样带�的问题也很明显,就是�能够自
  // 动获�当�登录到域的用户的身份。�便已��功登录到域,那也�
  // 能通过formå†?次输入用户å??密ç ?。因此,我在这里用的是
  // Request.Credentials = CredentialCache.DefaultCredentials,
  // 这样便å?¯ä»¥è޷得当å‰?用户的凭æ?®ï¼Œä½†æ˜¯è¿™æ ·å¸¦æ?¥çš„问题便是上é?¢æ??到的
  // 身份凭�无法传递的问题,解决方法请关注下篇文章。
  Request.Credentials = MyCredentialCache;

  // 指定WebDAV的SEARCH方法
  Request.Method = "SEARCH";

  // Encode the body using UTF-8.
  bytes = Encoding.UTF8.GetBytes((string)strQuery);

  // Set the content header length. This must be
  // done before writing data to the request stream.
  Request.ContentLength = bytes.Length;

  // Get a reference to the request stream.
  RequestStream = Request.GetRequestStream();

  // Write the SQL query to the request stream.
  RequestStream.Write(bytes, 0, bytes.Length);

  // Close the Stream object to release the connection
  // for further use.
  RequestStream.Close();

  // Set the content type header.
  Request.ContentType = "text/xml";

  // Send the SEARCH method request and get the
  // response from the server.
  Response = (HttpWebResponse)Request.GetResponse();

  // Get the XML response stream.
  ResponseStream = Response.GetResponseStream();

  // 创建XmlDocument对象,并获�收件箱的unreadcount节点的值
  ResponseXmlDoc = new XmlDocument();
  ResponseXmlDoc.Load(ResponseStream);
  HrefNodes = ResponseXmlDoc.GetElementsByTagName("a:displayname");
  SizeNodes = ResponseXmlDoc.GetElementsByTagName("d:unreadcount");
  for(int i=0;i<HrefNodes.Count;i++)
  {
   if(HrefNodes[i].InnerText=="æ”¶ä»¶ç®±")
    count=int.Parse(SizeNodes[i].InnerText);
  }
  ResponseStream.Close();
  Response.Close();
}
catch(Exception)
{
  // Catch any exceptions. Any error codes from the SEARCH
  // method request on the server will be caught here, also.
  return -1;
}
return count;
} 

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>

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

ezmlm command line reference

List all email addresses in list
ezmlm-list /path/to/mldir


Add an email address to the list
ezmlm-sub /path/to/mldir foo@bar.com



Remove an email address from the list
ezmlm-unsub /path/to/mldir foo@bar.com

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

Simplifying ActionMailer development in Ruby on Rails

Sick of writing almost the same thing over and over in your ActionMailer classes? Skip all that, and use something like this.

class Mailer < ActionMailer::Base

  helper ActionView::Helpers::UrlHelper

  def generic_mailer(options)
    @recipients = options[:recipients] || "me@privacy.net"
    @from = options[:from] || "me@privacy.net"
    @cc = options[:cc] || ""
    @bcc = options[:bcc] || ""
    @subject = options[:subject] || ""
    @body = options[:body] || {}
    @headers = options[:headers] || {}
    @charset = options[:charset] || "utf-8"
  end
  
  # Create placeholders for whichever e-mails you need to deal with.
  # Override mail elements where necessary
  
  def contact_us(options)
    self.generic_mailer(options)
  end

  ...

end


(If you have a configuration loaded into a constant, you could just replace the defaults above and use your app's defaults to make it all cleaner, of course)

And then from your controller you can do stuff like this:

Mailer.deliver_contact_us(
   :recipients => "x@x.com",
   :body => { 
               :name => params[:name],
               :phone => params[:phone],
               :email => params[:email],
               :message => params[:message]
             },
   :from => "y@y.com"
)
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS