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");
}
}


compass app flashLight app

18 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
  4. nice article in your blog.thank you for sharing useful info.
    visit
    web programming tutorial
    welookups

    ReplyDelete
  5. I absolutely love your blog and find many of your post's to be what precisely I'm looking for. Would you offer guest writers to write content for you? I wouldn't mind creating a post or elaborating on a few of the subjects you write with regards to here. Again, awesome web site! led light 80w 6k single beam USA

    ReplyDelete
  6. Hey very nice site!! Man .. Excellent .. Amazing .. I'll bookmark your blog and take the feeds also…I'm happy to find a lot of useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . . social media content

    ReplyDelete
  7. Treasurebox is an online store which provide their customers all the latest household items, outdoor furniutre,electronic gadgets nz, Pop up gazebos nz and much more.
    YOu will be easily buy all the items on a single click

    ReplyDelete
  8. Terrific work! This is the type of information that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my site . Thanks =) advertising agency singapore

    ReplyDelete
  9. very nice and Quality of the Leather Jackets are Avalible at very Affordable rates with
    Nice and Comfortable touch and Quality..

    Thanks Alot.

    ReplyDelete
  10. Really informative article.Really looking forward to read more. Really Cool.
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> goldenslot
    สนใจร่วมลงทุนกับเรา สมัครเอเย่น Gclub คลิ๊กได้เลย

    ReplyDelete

  11. Im grateful for the blog post.Really thank you!

    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา Gclub Royal1688
    และยังมีหวยให้คุณได้เล่น สมัครหวยออนไลน์ ได้เลย
    สมัครสล็อตออนไลน์ได้ที่นี่ >>> Golden slot
    ร่วมลงทุนสมัครเอเย่น Gclubกับทีมงานของเราได้เลย

    ReplyDelete
  12. Thanks for every other informative web site. Where else may just I get that kind of info written in such a perfect approach? I've a project that I am simply now working on, and I've been at the look out for such information. successful digital marketing campaign

    ReplyDelete
  13. I found your weblog web site on google and check a number of of your early posts. Continue to keep up the superb operate. I just additional up your RSS feed to my MSN News Reader. Looking for ahead to studying extra from you later on!… make some of the positive changes that improve search engine optimization

    ReplyDelete
  14. I'm still learning from you, while I'm trying to reach my goals. I definitely enjoy reading everything that is posted on your blog.Keep the stories coming. I enjoyed it! affected the SEO industry

    ReplyDelete