Send Mail using James Server

This application illustrates how to send mail on the mail server and also saved the message in database table.

Send Mail using James Server

Send Mail using James Server

     

This application illustrates how to send mail on the mail server and also saved the message in database table.

In this example we create a send mail class which is used to send the mail in the mail box of James mail server and insert the message in database table. The below figure shows the Test Mail - Message which is in the text area.

The Complete Application is as follows:

 

Output on Console:

 

Source Code of SendMail.java 

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;

public class SendMail {
  public static void main(String args[]) throws Exception {
  String host = "localhost";
  String from = "sandeep@localhost";
  String to = "sandeep@localhost";
  String user = "sandeep";
  String password = "sandeep";
  String content = "This is Test Message.";
  Properties properties = System.getProperties();
  properties.setProperty("mail.smtp.host", host);
  Session session = Session.getDefaultInstance(properties);
  MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  message.setSubject("Test Mail");
  message.setText(content);
  Transport.send(message);
  System.out.println("Message Send SuccessFully..." + content);

  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "test";
  String driver = "com.mysql.jdbc.Driver";
  String username = "root"; 
  String userPassword = "root";
  String strQuery = null;

  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,username,userPassword);
  Statement st = conn.createStatement();
  strQuery = "insert into message set message='"+content+"'"; 
  int rs = st.executeUpdate(strQuery);
  System.out.println("Query Executed Successfully...");  
  } catch (Exception e) {
  System.out.println(e.getMessage());
  } finally {
  conn.close();
  }  
  }
} 

Download Source Code