Send an email

The JavaMail API is not part of core Java SE, but an optional extension. (It's required in Java Enterprise Edition.) The JavaMail packages can be accessed in two ways: The javax.mail API uses a properties file for reading server names and related configuration. These settings will override any system defaults. Alternatively, the configuration can be set directly in code, using the JavaMail API.

Example

An email configuration file (to run the example, substitute valid values for the uncommented items):
 

# Configuration file for javax.mail
# If a value for an item is not provided, then
# system defaults will be used. These items can
# also be set in code.

# Host whose mail services will be used
# (Default value : localhost)
mail.host=mail.blah.com

# Return address to appear on emails
# (Default value : username@host)
mail.from=webmaster@blah.net

# Other possible items include:
# mail.user=
# mail.store.protocol=
# mail.transport.protocol=
# mail.smtp.host=
# mail.smtp.user=
# mail.debug=

A class which uses this file to send an email:


import java.util.*;
import java.io.*;
import java.nio.file.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/
public final class Emailer {

  public static void main( String... aArguments ){
    Emailer emailer = new Emailer();
    //the domains of these email addresses should be valid,
    //or the example will fail:
    emailer.sendEmail(
      "fromblah@blah.com", "toblah@blah.com",
       "Testing 1-2-3", "blah blah blah"
    );
   }

  /**
  * Send a single email.
  */
  public void sendEmail(
    String aFromEmailAddr, String aToEmailAddr,
    String aSubject, String aBody
  ){
    //Here, no Authenticator argument is used (it is null).
    //Authenticators are used to prompt the user for user
    //name and password.
    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {
      //the "from" address may be set in code, or set in the
      //config file under "mail.from" ; here, the latter style is used
      //message.setFrom(new InternetAddress(aFromEmailAddr));
      message.addRecipient(
        Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
      );
      message.setSubject(aSubject);
      message.setText(aBody);
      Transport.send(message);
    }
    catch (MessagingException ex){
      System.err.println("Cannot send email. " + ex);
    }
  }

  /**
  * Allows the config to be refreshed at runtime, instead of
  * requiring a restart.
  */
  public static void refreshConfig() {
    fMailServerConfig.clear();
    fetchConfig();
  }

  // PRIVATE 

  private static Properties fMailServerConfig = new Properties();

  static {
    fetchConfig();
  }

  /**
  * Open a specific text file containing mail server
  * parameters, and populate a corresponding Properties object.
  */
  private static void fetchConfig() {
    //This file contains the javax.mail config properties mentioned above.
    Path path = Paths.get("C:\\Temp\\MyMailServer.txt");
    try (InputStream input = Files.newInputStream(path)) {
      fMailServerConfig.load(input);
    }
    catch (IOException ex){
      System.err.println("Cannot open and load mail server properties file.");
    }
  }
} 



See Also :
Launch other applications
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -