January 5, 2015

JavaMail example with Zoho/GMail using SMTPS

Here is a simple example of how to send emails securely using JavaMail via your Gmail or Zoho account.

The first example uses TLS, which should be your preferred encryption mechanism. The second example uses SSL.

The only difference between the two mechanisms is the port number, and the mail.smtp.startXXX.enable property.

For SSL use:

port 465
mail.smtp.startssl.enable

For TLS use:

port 987
mail.smtp.starttls.enable
 
Get the source on GitHub here

Example 1: Zoho/Gmail with TLS

package com.ritchie.email;

import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

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

public class SendEmailService {

    private Logger logger = Logger.getLogger(SendEmailService.class.getName());

    public void sendEmail() {

        final String GMAIL_HOST = "smtp.gmail.com";
        final String ZOHO_HOST = "smtp.zoho.com";
        final String TLS_PORT = "897";

        final String SENDER_EMAIL = "username@zoho.com";
        final String SENDER_USERNAME = "username@zoho.com";
        final String SENDER_PASSWORD = "zoho-password";

        // protocol properties
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", ZOHO_HOST); // change to GMAIL_HOST for gmail                                                         // for gmail
        props.setProperty("mail.smtp.port", TLS_PORT);
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtps.auth", "true");
        // close connection upon quit being sent
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        try {
            // create the message
            final MimeMessage msg = new MimeMessage(session);

            // set recipients and content
            msg.setFrom(new InternetAddress(SENDER_EMAIL));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@gmail.com", false));
            msg.setSubject("Demo");
            msg.setText("Message Sent via JavaMail", "utf-8", "html");
            msg.setSentDate(new Date());

            // this means you do not need socketFactory properties
            Transport transport = session.getTransport("smtps");

            // send the mail
            transport.connect(ZOHO_HOST, SENDER_USERNAME, SENDER_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (MessagingException e) {
            logger.log(Level.SEVERE, "Failed to send message", e);

        }
    }
}

Example 2: Zoho/Gmail with SSL

package com.ritchie.email;

import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

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

public class SendEmailService {

    private Logger logger = Logger.getLogger(SendEmailService.class.getName());

    public void sendEmail() {

        final String GMAIL_HOST = "smtp.gmail.com";
        final String ZOHO_HOST = "smtp.zoho.com";
        final String SSL_PORT = "465";

        final String SENDER_EMAIL = "username@zoho.com";
        final String SENDER_USERNAME = "username@zoho.com";
        final String SENDER_PASSWORD = "zoho-password";

        // protocol properties
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", ZOHO_HOST); // change to GMAIL_HOST for gmail                                                         // for gmail
        props.setProperty("mail.smtp.port", SSL_PORT);
        props.setProperty("mail.smtp.startssl.enable", "true");
        props.setProperty("mail.smtps.auth", "true");
        // close connection upon quit being sent
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        try {
            // create the message
            final MimeMessage msg = new MimeMessage(session);

            // set recipients and content
            msg.setFrom(new InternetAddress(SENDER_EMAIL));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@gmail.com", false));
            msg.setSubject("Demo");
            msg.setText("Message Sent via JavaMail", "utf-8", "html");
            msg.setSentDate(new Date());

            // this means you do not need socketFactory properties
            Transport transport = session.getTransport("smtps");

            // send the mail
            transport.connect(ZOHO_HOST, SENDER_USERNAME, SENDER_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (MessagingException e) {
            logger.log(Level.SEVERE, "Failed to send message", e);

        }
    }
} 


January 3, 2015

Installing Meld on Mac OS using macports

After playing around with various merge tools on Mac, I have come to the conclusion that none match the ease of use that Meld offers. Here is how I managed to install it on my Mac OS X 10.8.5.
  1. First install macports
  2. If you are running Mac OS 10.8 and greater, you will need to install xquartz which provides the X Window system required for Meld. If you have Mac OS prior to 10.8 you can skip this step.
  3. Install Meld and its dependencies:
    sudo port install rarian
    sudo port install meld
    
  4. Set your locale (I hard coded this so I do not have to export it each time) by updating the /opt/local/bin/meld script by changing line 75 from:
    locale.setlocale(locale.LC_ALL,'')
    to
    locale.setlocale(locale.LC_ALL,'en_US')
  5. Start the service at boot
    launchctl load -w /Library/LaunchAgents/org.freedesktop.dbus-session.plist
  6. Finally run meld using spotlight or via the command line: /opt/local/bin/meld

 

Notes: 

If you try to run Meld without having xquartz installed then you will get the following error:
(process:65163): Gtk-WARNING **: Locale not supported by C library.
 Using the fallback 'C' locale.
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
  warnings.warn(str(e), _gtk.Warning)
/opt/local/bin/meld:126: GtkWarning: GtkIconTheme *gtk_icon_theme_get_for_screen(GdkScreen *): assertion 'GDK_IS_SCREEN (screen)' failed
  gtk.icon_theme_get_default().append_search_path(meld.paths.icon_dir())
Traceback (most recent call last):
  File "/opt/local/bin/meld", line 126, in 
    gtk.icon_theme_get_default().append_search_path(meld.paths.icon_dir())
AttributeError: 'NoneType' object has no attribute 'append_search_path'
logout 
 

Reference:

http://support.apple.com/en-us/HT201341
http://thebugfreeblog.blogspot.com/2014/03/installing-meld-on-mac-os-x.html