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

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

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

Capture and email a traceback in Python

import traceback, smtplib, StringIO
fp = StringIO.StringIO()
traceback.print_exc(file=fp)
message = fp.getvalue()
server = smtplib.SMTP(FAILURE_SERVER)
server.sendmail(
  FAILURE_FROM,
  FAILURE_TO,
  FAILURE_MESSAGE + '\n\n' + message,
)
server.quit()

Send email with attachment(s) in Python

Can't remember if I wrote this or found it on the Web or a combination, so I won't take credit per se -- I'm just posting it as reference.

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

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

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

  msg.attach( MIMEText(text) )

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

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS