The Java Calendar class provides many helpful methods for modifying Date objects. Here you will find a short code snippet for obtaining the last day of the month. To utilize the code please don’t forget to import the java.util.Calendar class or which ever Calendar you utilize. How the snippet works is it utilizes the getActualMaximum function which returns the max value for a field based on the current settings of the Calendar.
Calendar cal = Calendar.getInstance();
cal.set( Calendar.MONTH, 11 );
cal.set( Calendar.DATE, cal.getActualMaximum(Calendar.DAY_OF_MONTH) );
Calendar, DAY_OF_MONTH, getActualMaximum
For those new to Struts and in particular the Struts HTML library it might come as a surprise that there is no id property on their tags. Don’t get frustrated the tag library document clearly states that the styleId property renders its assigned value as the element id. This means that instead of id use styleId as shown by the following example.
Example
HTML
<input type="text" name="firstName" id="firstName"
maxlength="10" size="12" />
Struts HTML
<html:text property="firstName" styleId="firstName"
maxlenght="10" size="12" />
Resources
HTML library, Struts, Struts HTML
MDBitz - Matthew Denton
Java
In the previous tutorial we walked through how to send email from a Java Application. This tutorial extends off that and explains how to send email from a SMTP server that requires basic User Authentication in the form of a user name and password. This is performed by use of the Authenticator object.
Prerequisites
This tutorial builds off of the previous example and as such you will need to review that tutorial to understand the requirements necessary to utilize the JavaMail API.
How to send an email from SMTP Server requiring User Name/Password Authentication
To get started lets build off of our MailUtil class we have already created by copying the class and refactoring it to BasicAuthMailUtil. For those who don’t know what refactoring is it means to rename the class.
After we have refactored the class our first step is to create our Authenticator object. Now we could do this by creating a separate class or creating an internal class. For our purposes we will create an internal class. To create an internal class you simply declare a class inside the class declaration of another class. We would do this by placing our BasicSMPTAuthenticator class stub before the closing } of our BasicAuthMailUtil class.
public class BasicAuthMailUtil {
/* existing code */
private class BasicSMTPAuthenticator
extends javax.mail.Authenticator
{
}
}
For our Authenticator to function we need to implement the getPasswordAuthentication method which will return to the caller a PasswordAuthentication object with the desired username and password
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( AUTH_USER, AUTH_PSWD );
}
You could replace the AUTH_USER and AUTH_PSWD values directly with the user and password information for the server or define them as variables of the BasicAuthMailUtil Class.
private static String AUTH_USER = "USER NAME";
private static String AUTH_PSWD = "PASSWORD";
Now that our Authenticator is created the last step is to initialize the session with our Authenticator. Therefore we will modify:
Session sess = Session.getInstance(props);
with the following which instantiates our Authenticator then obtains the Mail Session Instance based on the properties and Authenticator.
Authenticator auth = new BasicSMTPAuthenticator();
Session sess = Session.getDefaultInstance( props, auth );
Congratulations you now have a utility class that can send emails from a SMTP Server that requires user name and password authentication.
Resources
Authenticator, eMail, JavaMail API, PasswordAuthentication, SMTP, Tutorial
MDBitz - Matthew Denton
Java
Sending email from your java application is very straightforward when you utilize the JavaMail API. This library contains all the functionality necessary to connect to a SMTP Mail Server and send your email to its desired recipients. The next time you have an application performing some vital functionality instead of just logging an exception send an email to the administrator or development team so that the issue can be resolved right away.
Prerequisites
In order to use the javaMail API you need to obtain both the Java Mail and Activation Framework libraries which can be found at the following locations:
How to Send an Email
To send an email from java we must first start by importing the required classes into our MailUtil java class.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
After we have imported the necessary resources lets go ahead with the creation of our postMail function that will send and email with subject and message, to the specified recipients, cc recipients from the sender. Also it is important to note that we will be throwing any MessagingExceptions that occur so that the caller will be responsible for handling them as they see fit.
public static void postMail( String recipients[],
String subject, String message, String from,
String ccRecipients[] ) throws MessagingException {
}
Now that we have our method stub in place lets begin by initializing a Mail Session configured to our SMTP Mail Server. Please note that if you utilize logging in your application you can also set the debug mode to true to get useful information.
//Create Properties
Properties props = new Properties();
props.put( "mail.smtp.host", HOST );
props.put("mail.debug", "true" );
//Get Session
Session sess = Session.getInstance(props);
After our session is initialize we can go ahead with creating our email message.
Message msg = new MimeMessage( sess );
Populate the From email address by use of the InternetAddress class
msg.setFrom(new InternetAddress(from) );
We can populate the recipents of the message utilizing the setRecipients function. This function takes two parameters the Type of recipient and the array of recipients. So we would use Message.RecipientType.TO and Message.RecipientType.CC for To and CC recipients.
// recipients
InternetAddress[] addressTo =
new InternetAddress[recipients.length];
for( int i=0; i < recipients.length; i ++ ) {
addressTo[i] = new InternetAddress( recipients[i] );
}
msg.setRecipients( Message.RecipientType.TO, addressTo );
// ccRecipients
if( ccRecipients != null && ccRecipients.length > 0 ) {
InternetAddress[] addressCC =
new InternetAddress[ccRecipients.length];
for( int i=0; i < ccRecipients.length; i ++ ) {
addressCC[i] = new InternetAddress( ccRecipients[i] );
}
msg.setRecipients( Message.RecipientType.CC, addressCC );
}
After populating the recipients of the email we can set the subject and Date of the email
msg.setSubject(subject);
msg.setSentDate(new Date() );
Finally we set the content of the email. Please note that in most cases the text format will be text/plain for simple text emails or text/html for html formatted messages.
msg.setContent( message, "text/html" );
Now that our message is prepared we send utilizing the Transport class.
And that is how to send an email from your Java Application, The full source for the created Utility class can be found below. If your server requires Password authentication then you may be interested in the Advanced Tutorial.
Resources
eMail, How To, javax.activation, javax.mail, Tutorial
If a beginner coder you may get confused by the fact that Date.parse function has been deprecated. Not to worry though, it was deprecated for good reason as the DateFormat classes gives you a better way to convert strings into JAVA Date objects.
The DateFormat class contains a parse method that will convert a String into a Date Object based on the format you have specified. This gives you the flexibility to convert date Strings that are in various formats.
How to convert a String to a Date
Import the required classes
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
imoprt java.util.Date;
Create your DateFormat initialized with the format of the string you are to convert into a Date object.
DateFormat dateFormat = new SimpleDateFormat( "MM/dd/yyyy");
Convert your date String, but remember to catch the ParseException that can be thrown if the String can not be converted into a Date.
try {
Date theDate = dateFormat.parse( "09/09/2009" );
} catch (ParseException e ) {
e.printStackTrace();
}
Resources:
DateFormat, Parse Date, SimpleDateFormat