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

, , , , ,

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.

Transport.send( msg);

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

, , , ,

Overview

Search Engine Optimization (SEO) is straightforwardly the modification of your website to make it friendlier to Search Engines with the goal of increasing your page ranking from Organic Search. Unfortunately implementing SEO on a site is not as straightforward as Google and other Search Engines  utilize proprietary algorithms that utilize hundreds of variables to rank your site.  Although SEO is an important step needed be forewarned there is no silver bullet that will get you the #1 ranking and know also that fluffing your site with false content or doorways specifically for Search Engines can and will hurt your ranking and might even get you black listed.

Basic Guidelines

Rule #1 : Create your site for your users and not for search engines.

No matter what anyone tells you your site needs to speak to your visitors with search engines an after thought.  The premises are these if your content is not useful for your visitors as all it does is spit out generic keywords then a user is not going to stay on your site as their is no point.  Create rich, unique, and useful content that users will want, by doing so you may not be seeding organic search on the short term but sites linking to your site will enhance your ranking over the long term.  Seriously you built your site for a purpose make sure you meet your goals.

With that important fact out of the way lets move on to some of the basic SEO techniques.

  • Page Title
    The title of your page should be precise and informative. This tells the user where they are and what they can find on this page.  It is good practice to keep your name in the title with the title of the page. For example if you are a website developer and your company is XYZ corp and your tag line is “The Website Experts” then a reasonable title for the main page could be “XYZ Corp : Thew Website Experts”. However once inside the site the title should be more specific to the content on the page, for example a contact page could be “Contact Us at XYZ Corp” or “XYZ Corp : Contact Us”.

    <title>XYZ Corp: Portfolio of Short Films</title>
  • Keywords
    Keywords is debated as not being used by Search Engines due to their abuse by web sites. However it is a good practice to add keywords to your page as long as they are relevant to your content. The keywords meta tag gets placed in the head tag of your html.

    <meta name="keywords" content="Search engine optimization"/>
  • Description
    The description meta tag is used to place  a short description of the page. It is good practice to utilize keywords as part of your sentences inside this tag.

    <meta name="description" content="Search Engine Optimization (SEO) Tips and Tricks">
  • URL Structure
    The url or the page is displayed in search results and possibly when users link to your site. Making the link user friendly also can notify Search Engines what content to expect on the page.  For example if you are an online store and are selling antique lamps then a posible url for your products could be www.antiquecompany.com/products/lamps/Red_Floral_Shade_Lamp/ This provides the user with information on what they can find on the page instead of a url like www.antiquecompany.com/?cateogry=1&product=237 which tells the user nothing about what to expect on that page.
  • Site Map
    Having a site map for your website can provide users and search engines the ability to readily find pages in your site that is of interest to them.  I highly, highly recommend that you utilize a separate page for this with a link of every page in a utility navigation (not the main nav), please do not add it to the bottom of every page as it just adds clutter to your site.  A site map is a last resort for users to find content, your navigation should readily provide them access to content that they want, if users are repeatedly accessing the site map then you may want to reconsider the structure of your site.
  • Content
    Content is the most important element of your site. Regardless of the above if your site does not provide new, unique, compelling, and above all else useful content a visitor will not stay. A visitor to your website is there for a purpose and your site should provide the information they are looking for. If you simply regurgitate information without providing anything new or different then users will not revisit your site.  When writing content keep in mind the keywords that users could be looking for and add those in to the content if appropriate. Do not force them in though having good content regardless of keywords will lead to visitors which could lead to links to your site and content increasing your ranking.

    • Anchor Text
      Anchor tags or a tags provide links to other sites. Utilize descriptive text instead of click here or similar general text so that users and search engines to understand what the page you are linking to is about.
    • Heading Tags
      Heading Tags or h1, h2 tags are meant to be used to specify the importance of content use them as such.  Place titles in header tags so that users and search engines realize their importance.
    • Images
      Search Engines can not view images instead the utilize the image name and alt property to gather information on what the image is.  Utilize short but descriptive names and place a description of the image in the alt tag as this will be displayed to users if the image can not be loaded.

Conclusion

Search Engine Optimization is a fickle topic, with each Search Engine utilizing their own algorithms and variables. The simplest and most often forgotten rule is simple build your site and write content for your users.  As for the rest be wary of SEO professionals who guarantee results as there are numerous “black hat” methods used that can get your black listed and removed from results.  Simply provide valuable and clear content following the basic guidelines is more than enough for most websites.

, ,