Tuesday, October 29, 2013

E-mail in Java

This is a simple E-mail in Java program. You can use it to send message with multiple attachments to multiple recipients at the same time. Before you use the program to send e-mail message, you will need to configure the mail. The configuration form allows you to enter the outgoing server name, port, user name and password to log in the server. For security reason, your password is encrypted. The configuration file (mailconfigs.con) is stored in your current working folder. You can configure the email by going to File menu->Setup Configuration...One you configured the mail correctly, you do not need to configure it again later.

configure e-mail


After you configured the mail, you will need to input the From address (your e-mail address), the recipients' e-mail addresses, subject, and message of the mail. Bcc, Cc e-mail addresses, and file attachments are optional.



In Java, it is easy to send e-mail by using the Apache Commons Mail api. You will download the Apache Commons Mail api from its website. This api depends on the Java Mail api. You can download Java Mail api from here. After downloading the two api, extract the zip files and add the jar files (commons-email-1.3.2.jar and javax.mail.jar) to the Java Build Path in the Eclipse.

In the Commons Mail api, there two classes that can be used to send e-mail message. One class is SimpleEmail. The SimpleEmail class is used to send e-mail message without attachment. Another class is called MultiPartEmail. This class is able to send e-mail message with attachments. Like the SimpleEmail class, the MultiPartEmail class has methods that allow you to configure e-mail in your Java code.

MultiPartEmail email=new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,password);
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);

There are other methods that you will use to set the From e-mail address, To e-mail addresses, Bcc e-mail adddress, Cc e-mail addresses, subject, message, and attachment of the mail.

//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipient's (to) e-mail address
email.addTo(Toadd);
//add recipient's (Bcc) e-mail address
email.addBcc(Bccadd);
//add recipient's (Cc) e-mail address
email.addCc(Ccadd);
//add file attachment
email.attach(new File(path));

//send the email
email.send();

Here is the complete code of the E-mail in Java program.

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;


class UI extends JFrame implements ActionListener{
JTextField textfrom;
JTextField textto;
JTextField textbcc;
JTextField textcc;
JTextField textsubject;
JTextArea textmessage;
JLabel lblstatus;
JTextField txtserver;
JTextField txtport;
JTextField txtuser;
JPasswordField txtpwd;
DefaultListModel<String> listmodel;
MultiPartEmail email;
ArrayList<String> configs;
JFrame frame;
UI(String title){

Container cont=getContentPane();
setTitle(title);
setResizable(false);
setSize(new Dimension(650,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic('F');
JMenuItem itemserver=new JMenuItem("Mail configure...");
itemserver.addActionListener(this);
JMenuItem itemexit=new JMenuItem("Exit");
itemexit.addActionListener(this);
mfile.add(itemserver);
mfile.add(itemexit);
mbar.add(mfile);
setJMenuBar(mbar);

JPanel panelmain=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblfrom=new JLabel("From:");
textfrom=new JTextField(30);
JButton btadd=new JButton("Send");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lblfrom);
panelnorth.add(textfrom);
panelnorth.add(btadd);
GridBagLayout gbl=new GridBagLayout();
JPanel panelcenter=new JPanel(gbl);
GridBagConstraints gc = new GridBagConstraints();
JLabel lblto=new JLabel("To:");
textto=new JTextField(30);
JLabel lblbcc=new JLabel("Bcc:");
textbcc=new JTextField(30);
JLabel lblcc=new JLabel("Cc:");
textcc=new JTextField(30);
JLabel lblsubject=new JLabel("Subject:");
textsubject=new JTextField();
JButton btatt=new JButton("Attach");
btatt.addActionListener(this);

listmodel=new DefaultListModel<String>();
JList<String> attlist=new JList<String>(listmodel);
attlist.setVisibleRowCount(5);

gc.fill = GridBagConstraints.BOTH;
       gc.weightx = 1.0;
       gbl.setConstraints(lblto, gc);
       gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textto, gc);
      panelcenter.add(lblto);
panelcenter.add(textto);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblbcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textbcc, gc);
      panelcenter.add(lblbcc);
panelcenter.add(textbcc);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
   gbl.setConstraints(textcc, gc);
      panelcenter.add(lblcc);
panelcenter.add(textcc);


gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblsubject, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textsubject, gc);
      panelcenter.add(lblsubject);
panelcenter.add(textsubject);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(btatt, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gc.gridheight = 2;
       gbl.setConstraints(attlist, gc);
      panelcenter.add(btatt);
panelcenter.add(attlist);

gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weighty = 1.0;
lblstatus=new JLabel("");
lblstatus.setForeground(Color.RED);
gbl.setConstraints(lblstatus, gc);
panelcenter.add(lblstatus);


JPanel panelsouth=new JPanel(new FlowLayout(FlowLayout.LEFT));
panelsouth.add(new JLabel("Message:"));
textmessage=new JTextArea(15,50);
textmessage.setWrapStyleWord(true);
JScrollPane scroll=new JScrollPane(textmessage);
panelsouth.add(scroll);

panelmain.add(panelnorth);
panelmain.add(panelcenter);
panelmain.add(panelsouth);
cont.add(panelmain);
setVisible(true);
configureMail();
}
public void configureMail(){
readConfigs();
if(configs.size()>2){
setEmailConfigs(configs.get(0),Integer.parseInt(configs.get(1)),configs.get(2),configs.get(3));

}
}

public void actionPerformed(ActionEvent e){
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
if(e.getActionCommand().equals("Send")){
String from=textfrom.getText();
if(textto.getText().length()>0)
Tos=textto.getText().split(", ");
if(textbcc.getText().length()>0)
Bccs=textbcc.getText().split(", ");
if(textcc.getText().length()>0)
Ccs=textcc.getText().split(", ");
String subject=textsubject.getText();
String message=textmessage.getText();

if(from.length()>0 && Tos.length>0 && subject.length()>0 && message.length()>0) {
Th th=new Th(from,Tos,Bccs,Ccs,subject,message);
th.start();

}
else{
JOptionPane.showMessageDialog(this,"From, To, Subject, and Message cannot be blank.");
textfrom.requestFocus();
}

}
else if(e.getActionCommand().equals("Attach")){
selectFile();
}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
else if(e.getActionCommand().equals("Mail configure...")){
JPanel p=new JPanel(new GridLayout(5,1));
txtserver=new JTextField("Enter outgoing server");
txtport=new JTextField("Enter server port");
txtuser=new JTextField("Enter user name");
txtpwd=new JPasswordField("Enter password");
JButton bt=new JButton("Save and Close");
bt.addActionListener(this);
p.add(txtserver);
p.add(txtport);
p.add(txtuser);
p.add(txtpwd);
p.add(bt);

frame=new JFrame("Configure mail");
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setVisible(true);

}
else if(e.getActionCommand().equals("Save and Close")){
saveConfigs();
frame.dispose();
}
}
class Th extends Thread{
String from;
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
String subject;
String message;
Th(String fromaddr,String[] toaddr,String[] bccaddr,String[] ccaddr,String subj,String mess){
from=fromaddr;
Tos=toaddr;
Bccs=bccaddr;
Ccs=ccaddr;
subject=subj;
message=mess;
lblstatus.setText("Sending the message");

}
public void run(){
sendEmail(from,Tos, Bccs,Ccs,subject, message);
email=null; //create object
lblstatus.setText("");
}
}
public void readConfigs(){
configs=new ArrayList<String>();
BufferedReader br=null;
try {
File f=new File("mailconfigs.con");
if(f.exists()){
FileReader fr=new FileReader(f);
br=new BufferedReader(fr);
String line="";
while((line=br.readLine())!=null){
configs.add(line);
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public void saveConfigs(){
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw = new FileWriter("mailconfigs.con");
bw=new BufferedWriter(fw);
bw.write(txtserver.getText());
bw.newLine();
bw.write(txtport.getText());
bw.newLine();
bw.write(txtuser.getText());
bw.newLine();
bw.write(encrypt(new String(txtpwd.getPassword())));



} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



public String encrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]+101);

return(new String(sb));
}

public String decrypt(String passw){

byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]-101);

return(new String(sb));
}

public void selectFile(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
listmodel.addElement(file.getPath());
       }
}

public void setEmailConfigs(String smtp,int port, String user, String password){
email = new  MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,decrypt(password));
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
}

public void sendEmail(String from, String[] Tos, String[] Bccs, String[] Ccs, String subject, String message){
configureMail();

if(email.getHostName().length()>0){
try {
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipients' (to) e-mail addresses
if(Tos!=null)
for(String Toadd:Tos)
email.addTo(Toadd);
//add recipients' (Bcc) e-mail addresses
if(Bccs!=null)
for(String Bccadd:Bccs)
email.addBcc(Bccadd);
//add recipients' (Cc) e-mail addresses
if(Ccs!=null)
for(String Ccadd:Ccs)
email.addCc(Ccadd);
//add file attachments
for(int i=0;i<listmodel.getSize();i++)
email.attach(new File(listmodel.get(i)));

//send the email
email.send();
}catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(this,"The email is not configured.");
}

}
}
public class EmailSender {
public static void main(String[] args){
new UI("E-Mail Sender");
}
}


6 comments:

  1. hi,
    nice idea , i m verry interested to implement this codes but
    i have problem in downloadin commons email , the API required :binaires or source
    can you explain more .
    thanks

    ReplyDelete
  2. Excellent post and wonderful blog, I really like this type of interesting articles keep it you.ppc campaigns
    Well, I read this information first time in your blog. That was a great research, it really nice and amazing one dear

    ReplyDelete


  3. In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased. I am looking forward to your article will become better and better.
    hotmail login | red ball | 192.168.1.1

    ReplyDelete