Showing posts with label programming language. Show all posts
Showing posts with label programming language. Show all posts

Friday, March 30, 2012

Combine gmail and Java mail library to create your email compaign

If you use gmail for your company, you can run your own email campaign without paying those email campaign companies.  Write a small script or Java program to pull user data from your database and create a pretty HTML based email template. If you want to track them, insert the tracking in the HTML content.  Use the following code to start sending emails to your users.  Just be sure not to abuse the gmail account.


import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class Mailman extends javax.mail.Authenticator
{
    private String smtpServer;
    private String from;
    private String password;
    private boolean useAuth;


    public Mailman(String sender)
    {
        from = sender;
        smtpServer = "smtp.gmail.com";
    }


    public String getSmtpServer() { return smtpServer; }
    public void setSmtpServer(String svr) { smtpServer = svr; }


    public String getSender() { return from; }
    public void setSender(String fm) { from = fm; }


    public String getPassword() { return password; }
    public void setPassword(String passwd) {
        password = passwd;
        if (passwd != null && passwd.length() > 0) {
            useAuth = true;
        } else {
            useAuth = false;
        }
    }


    /*
     * This method sends plain text mail.
     */
    public void send(String subject, String body, String to, String cc)
    {
        try
        {
            Message msg = createMessage(subject, to, cc);
            msg.setText(body);
            Transport.send(msg);
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    /*
     * this method sends mail with file attachments
     */
    public void send(String subject, String body, List<String> attachPaths, String to, String cc)
    {
        try
        {
            Message msg = createMessage(subject, to, cc);
            Multipart multipart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);


            for (String fileAttachment : attachPaths) {
                MimeBodyPart attachment = new MimeBodyPart();
                DataSource source = new FileDataSource(fileAttachment);
                attachment.setDataHandler(new DataHandler(source));
                attachment.setFileName(new File(fileAttachment).getName());
                multipart.addBodyPart(attachment);
            }
            msg.setContent(multipart);


            Transport.send(msg);
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    protected Message createMessage(String subject, String to, String cc) throws Exception
    {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);
        Session session = null;
        if ( useAuth ) {
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.smtp.auth", "true"); 
            // SSL
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");


            session = Session.getInstance(props, this);
        } else {
            session = Session.getInstance(props);
        }
        // create a new message
        Message msg = new MimeMessage(session);


        if (from == null) {
          from = System.getProperty("user.name");
        }
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }


        // set the subjecttext
        msg.setSubject(subject);
        // set some other header information
        msg.setHeader("X-Mailer", "s3ar-JavaMail");
        msg.setSentDate(new Date());


        return msg;
    }


    @Override
    public PasswordAuthentication getPasswordAuthentication()
    {
        // you can read the password from a file
        // which should set mode as 0400


        return new PasswordAuthentication(from, password);
    }
}

Thursday, February 23, 2012

Modify grapeConfig.xml to speed up groovy script with @Grab

I had a post on speed up groovy script startup time if Grape @Grab annotation is used in the script.
The cause is described in this post, http://swainya.blogspot.com/2011/09/skip-download-when-groovy-code.html.

The solution described in that post is to add one line in the .groovy/grapeConfig.xml to decrease cache TTL.  Add

<property name="ivy.cache.ttl.default" value="15m"/>

in the <ivysettings> section.

Your grapeConfig.xml will look like this after adding that line


<ivysettings>
  <property name="ivy.cache.ttl.default" value="15m"/>
  <settings defaultResolver="downloadGrapes"/>
......

Friday, September 30, 2011

Find directory path of the current groovy script

Bash or PHP script has a function that returns the directory path of the current script file.

$my_dir=dirname(__FILE__);

Groovy script lacks such a capability but an alternative is available by calling

def my_dir = new File(getClass().protectionDomain.codeSource.location.path).parent

Tuesday, September 27, 2011

Skip download when groovy code annotated with Grapes

Grapes is a great utility to manage class path automation when coding with groovy.
http://groovy.codehaus.org/Grape
But it slows down the start-up if there are a lot of dependent jars to download.  Even all the dependent jar files have been downloaded to local m2 and grapes store previously, the download process still takes place, which slow things down unnecessarily.

Use the following options to ask groovy look into local storage directly.
groovy -Dgroovy.grape.autoDownload=false [groovy file path] [arguments ......]

Wednesday, August 3, 2011

To begin this blog

I am a software engineer, and I code.

I use the Internet as a reference, language features, open-source software, best practices and quick suggestions on day-to-day issues. There are a lot of good articles, but they are easily buried under by other search engine optimized sites. I decided to log what I found and my thoughts on the fine points. This will definitely help myself, and hopefully will help other people.