The Javamail API

Other topics

Remarks:

The JavaMail page on the Oracle website describes it as follows

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with the Java SE platform and is also included in the Java EE platform.

The primary site for the JavaMail project is now on java.net. From there you can find the javadocs for many versions of the APIs, links to the source code repositories, links for downloads, examples and hints for using JavaMail with some popular Email service providers.

Sending an email to a POP3 email server

This example shows how to establish a connection to an SSL-enabled POP3 email server and send a simple (text only) email.

    // Configure mail provider
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.mymailprovider.com");
    props.put("mail.pop3.host", "pop3.mymailprovider.com");
    // Enable SSL
    props.put("mail.pop3.ssl.enable", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // Enable SMTP Authentication
    props.put("mail.smtp.auth","true");

    Authenticator auth = new PasswordAuthentication("user", "password");
    Session session = Session.getDefaultInstance(props, auth);

    // Get the store for authentication
    final Store store;
    try {
        store = session.getStore("pop3");
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException(e);
    }

    try {
        store.connect();
    } catch (AuthenticationFailedException | MessagingException e) {
        throw new IllegalStateException(e);
    }
    
    try {
      // Setting up the mail
      InternetAddress from = new InternetAddress("[email protected]");
      InternetAddress to = new InternetAddress("[email protected]");

      MimeMessage message = new MimeMessage(session);
      message.setFrom(from);
      message.addRecipient(Message.RecipientType.TO, to);

      message.setSubject("Test Subject");
      message.setText("Hi, I'm a Mail sent with Java Mail API.");

      // Send the mail
      Transport.send(message);
    } catch (AddressException | MessagingException e)
        throw new IllegalStateException(e);
    } 

Caveats:

  • Various details have been hardwired into the code above for illustration purposes.
  • The exception handling is NOT examplary. The IllegalStateException is a bad choice, for a start.
  • No attempt has been made to handle resources correctly.

Send Simple Email

public class GoogleMailTest {

    GoogleMailTest() {

    }

    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMailTest.Send(username, password, recipientEmail, "", title, message);
    }

    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.put("mail.debug", "true");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");
        props.put("mail.smtps.quitwait", "false");
        Session session = Session.getInstance(props, null);
        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        JOptionPane.showMessageDialog(null, msg.getSize());
        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }
        msg.setSubject(title);
        msg.setText(message);
        msg.setSentDate(new Date());
        SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }
    //    And use this code in any class, I'm using it in the same class in main method
    public static void main(String[] args) {
        String senderMail = "[email protected]"; //sender mail id
        String password = "769inzimam-9771"; // sender mail password here
        String toMail = "[email protected]"; // recepient  mail id here
        String cc = ""; // cc mail id here
        String title = "Java mail test"; // Subject of the mail
        String msg = "Message here"; // message to be sent

        GoogleMailTest gmt = new GoogleMailTest();

        try {
            if (cc.isEmpty()) {
                GoogleMailTest.Send(senderMail, password, toMail, title, msg);
            } else {
                GoogleMailTest.Send(senderMail, password, toMail, cc, title, msg);
            }
        } catch (MessagingException ex) {
            Logger.getLogger(GoogleMailTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Send HTML Formatted Mail

You can use the same Example above Send Simple Mail with a little modification. Use msg.setContent() instead of msg.setText() and use content type html as text/html.

check this

msg.setContent(message, "text/html; charset=utf-8");

instead of

msg.setText(message);

Contributors

Topic Id: 8089

Example Ids: 15368,26158,26159

This site is not affiliated with any of the contributors.