email snippets

Validating an email address in Java

Tagged email, validator, regexp, java, rfc 2822  Languages java

The source of the regexp is this site: Email unlimited. According to Wikipedia the regexp on the source page validates the email address according to RFC 2822 - Internet Message Format. I have still to write a comprehensive test suite, but the tests I do have for this validator pass.

public class EmailValidator {
  public static boolean validate(final String emailAddress) {
    if ( emailAddress == null ) return false;
    String patternStr = "^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$";
    Pattern emailPattern = Pattern.compile(patternStr);
    return emailPattern.matcher(emailAddress).matches();
  }
}

How to send both HTML and text emails with PHP and PHPMailer

Tagged send, email, smtp, php, phpmailer, html  Languages php

This is an example on how to use PHPMailer to send an HTML email. It also shows how to include a text only version of the same email for clients, such as mutt, that don't support HTML emails.

$mail = new PHPMailer();

$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->IsSMTP();

$mail->WordWrap = 80;
$mail->Host = "smtp.thehost.com"; 
$mail->SMTPAuth = false;

$mail->From = $from;
$mail->FromName = $from; // First name, last name
$mail->AddAddress($to, "First name last name");
#$mail->AddReplyTo("reply@thehost.com", "Reply to address");

$mail->Subject =  $subject;
$mail->Body =  $htmlMessage; 
$mail->AltBody  =  $textMessage;    # This automatically sets the email to multipart/alternative. This body can be read by mail clients that do not have HTML email capability such as mutt.

if(!$mail->Send())
{
  throw new Exception("Mailer Error: " . $mail->ErrorInfo);
}

Sending Devise Emails Manually

Tagged devise, email  Languages ruby
user = User.new email: 'bill@gates.com'
Devise.mailer_sender = 'no-reply@gates.com'
Devise.mailer.confirmation_instructions(user, self).deliver!

Sending email with Linux CLI through SMTP.

Tagged email, cli scripting, smtp  Languages bash

Great for scripting e.g motion to send the captured images + movie into your email. No public ssh keys, no passwords, no hassles. Install on Debian with apt-get install sendemail. The email address below has naturally been altered to not be picked up by harvesters.

sendEmail -f marko_haapala@aktagon_com -t marko_haapala@aktagon_com -m "$(date -I)" -u "Possible intruder" -s smtp.aktagon.com -a /tmp/motion/file.jpg

How to use the Hominid Ruby gem to send newsletters through MailChimp’s API

Tagged email, newsletter, mailchimp, hominid  Languages ruby

This example uses an existing campaign as a template for subsequent campaigns:

require 'hominid' # https://github.com/terra-firma/hominid

key = 'xxx' # MailChimp API key

h = Hominid::API.new(key, {:secure => true, :timeout => 60})

#
# List campaigns & templates
#
campaigns = h.campaigns
templates = h.templates
lists = h.lists

# From the lists above
campaign_id = '111'
list_id = '222'
template_id = 333

#
# Create a campaign
#
# http://apidocs.mailchimp.com/1.3/campaigncreate.func.php

options = { :list_id => list_id, :template_id => template_id, :subject => 'xxx' }
campaign = h.campaign_create('regular', options, content)

#
# Copy a campaign
#
new_campaign_id = h.campaign_replicate(campaign_id)

#
# Update a campaign
# 
html_title = 'XXX'
html_description = 'Hello!'
html_content = %Q{
  <div>
    <h2>WOW</h2>
  </div>
}

#
# In this example we have a template with 3 editable content areas
# that are marked with mc:edit="title", mc:edit="description", mc:edit="content"
# See templates documentation for details
#
content = { 'html_title' => html_title, 'html_description' => html_description, 'html_content' => html_content }

result = h.campaign_update(new_campaign_id, :content, content)

#
# Send a campaign
#
# http://apidocs.mailchimp.com/1.3/campaignsendnow.func.php
# http://apidocs.mailchimp.com/1.3/campaignsendtest.func.php
#
result = h.campaign_send_now(new_campaign_id, %w(bill.gates@gmail.com))

#
# Templates
#
# http://kb.mailchimp.com/article/getting-started-with-mailchimps-template-language
# http://kb.mailchimp.com/article/template-language-creating-editable-content-areas/

#
# View available content areas:
#
result = h.campaign_template_content(new_campaign_id)

How to set up email alerts for ModSecurity

Tagged alerts, modsecurity, email  Languages lua

Sending email alerts/notifications from ModSecurity is easy with Lua. Just put this script somewhere:

from = "hell@hell.com"
to = "heaven@heaven.com"

-- We use the mail command to send emails. You could also use the lua socket library:
-- http://w3.impa.br/~diego/software/luasocket/smtp.html
function main()
  -- create email
  local subject = m.getvar("TX.email_subject")
  local body = m.getvar("TX.email_body")

  if subject == nil then
    return nil
  end

  if body == nil then
    body = subject .. ":\n" ..
     "IP:\t " .. m.getvar("REMOTE_ADDR") .. "\n " ..
     "HOST:\t " .. m.getvar("REMOTE_HOST") .. "\n " ..
     "URI:\t " .. m.getvar("REQUEST_URI")
  end

  m.log(4, "Sending email " .. subject)
  m.log(5, body)

  -- use the mail command to send emails
  local cmd = "echo -e \"" .. body .. "\" | mail -s \"" .. subject .. "\" ".. from .." -- -r \"" .. to .. "\""

  -- remove variables
  m.setvar('tx.email_subject', nil)
  m.setvar('tx.email_body', nil)

  -- execute command
  local f = io.popen(cmd)

  -- read result
  local l = f:read("*a")
  m.log(5, "mail output: " .. l)
  f:close()
  --print(l)
  return nil
end

Next set up a rule that executes the script after a user has been blocked:

SecRule IP:bf_ip_counter "@gt 3" \
                "phase:5,pass,t:none, \
                setvar:'tx.email_subject=Blocking IP. Too many authentication failures.',exec:/xxx/email.lua, \
        ...

Now verify that it works. Note that this script uses the mail command, so make sure sending mails with Postfix and mail works.

Updating Passwords and Emails When Using Active Admin and Devise

Tagged active_admin, password, email, devise  Languages ruby

With Active Admin and Devise, we want to: * Skip email confirmations * Require password and email confirmations, but only when changing the email or password

This code supports our requirements:

ActiveAdmin.register User do
  controller do
    def update
      if params[:user][:password].blank?
        params[:user].delete("password")
        params[:user].delete("password_confirmation")
      end
      if params[:user][:email].blank?
        params[:user].delete("email")
        params[:user].delete("email_confirmation")
      end
      super
    end
  end

  before_save do |user|
    user.skip_confirmation!
    user.skip_reconfirmation!
  end
end

See the Active Admin DSL for details