Jan 02

The Properties class has a store() method for saving a set of properties to a stream. There are lots of examples on the web that show how to use store() but unfortunately the majority of them fail to close the stream which is a bit misleading for new developers. Closing the stream is the responsibility of the caller (as mentioned in the javadoc), and failure to do it can result in the properties not being written to their ultimate destination.

Here’s an example showing how to write the properties to a file (including closing the stream).

Properties prop = new Properties();
OutputStream out = new FileOutputStream("my.properties"); 
try {
     prop.setProperty("abc", "123");
     prop.store(out, null);
} catch (IOException ex) {
     ex.printStackTrace();
} finally {
     out.close();
}

written by objects \\ tags: , , ,

Oct 12

Googles Gmail SMTP server supports the use of TLS (Transport Layer Security). When using a Gmail SMTP server with Javamail we can configure Javamail to use TLS using the session properties.

	    Properties props = new Properties();
	    props.put("mail.transport.protocol", "smtp"); 
	    props.put("mail.smtp.starttls.enable", "true"); 
	    props.put("mail.smtp.host", "smtp.gmail.com"); 
	    props.put("mail.smtp.auth", "true"); 
    // use your gmail account username here
	    props.put("mail.smtp.user", "username@gmail.com");
	    props.put("mail.smtp.port", "465");
	    props.put("mail.mime.charset", "ISO-8859-1");
	    props.put("mail.smtp.socketFactory.port", "465");
	    props.put("mail.smtp.socketFactory.fallback", "false");
	    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

You’ll also need to specify an Authenticator when creating the session.

You can then use the session to send your mail.

Putting it all together we get this


// Create session
    
Properties sessionProperties = System.getProperties();
props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true"); 
props.put("mail.smtp.host", "smtp.gmail.com"); 
props.put("mail.smtp.auth", "true"); 
// use your gmail account username here
props.put("mail.smtp.user", "username@gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.mime.charset", "ISO-8859-1");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = 
   Session.getDefaultInstance(sessionProperties, new PasswordAuthenticator());
    
// Create message
    
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, 
   InternetAddress.parse(to, false));
message.setSubject(subject);
message.setText(body);

// Send the message

Transport.send(message); 

written by objects \\ tags: , , , , , ,