Home > Java, mail > Java code sending Mail with Attachment using Java Mail API

Java code sending Mail with Attachment using Java Mail API


In a day-to-day life the emails are occupied our life.If we can send our mails by using our java code without help of browser how we feel?

This article do this.By using the JavaMail API send our mail with attachment without help of browser.This code need a mail.jar file.You can download this at http://www.java2s.com/Code/Jar/JKL/Downloadmailjar.htm


/ * This code is only for design the frame
 * @author muneeswaran
package com.mail;

import javax.mail.MessagingException;
import javax.swing.*;

public class MailSender extends JFileChooser

    private JTextField attachmentTextField;
    private JLabel jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel6;
    private JScrollPane jScrollPane1;
    private JTextArea messageTextArea;
    private JButton sendButton, cancelButton, browseButton;
    private JTextField ccTextField, subjectTextField, toTextField;
    String toAddress = null, ccAddress = null, message = null,
            receipientsList[] = null, attachments[] = null, receipients, subject;
    String fromAddress = "put your full mail id"; //Place your mail id here.
    String authenticationPassword = "your password";//Place your password here

    public MailSender()

    private void initComponents()

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel("To");
        toTextField = new javax.swing.JTextField(20);
        jLabel3 = new javax.swing.JLabel("CC");
        ccTextField = new javax.swing.JTextField(20);
        jLabel4 = new javax.swing.JLabel("Subject");
        subjectTextField = new javax.swing.JTextField(20);
        jLabel5 = new javax.swing.JLabel("Attachemnet");
        attachmentTextField = new javax.swing.JTextField(20);
        browseButton = new javax.swing.JButton("Browse");
        jLabel6 = new javax.swing.JLabel("Message");
        jScrollPane1 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea(20, 10);
        sendButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();


        jLabel1.setFont(new java.awt.Font("AlMateen-Bold", 3, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(1, 203, 221));
        jLabel1.setText("Mail Sender");
        sendButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        cancelButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        browseButton.addActionListener(new java.awt.event.ActionListener()

            public void actionPerformed(java.awt.event.ActionEvent evt)

        jLabel1.setBounds(100, 50, 200, 50);
        jLabel2.setBounds(50, 100, 100, 50);
        toTextField.setBounds(150, 100, 300, 40);

        jLabel3.setBounds(50, 150, 100, 50);
        ccTextField.setBounds(150, 150, 300, 40);

        jLabel4.setBounds(50, 200, 100, 50);
        subjectTextField.setBounds(150, 200, 300, 40);

        jLabel5.setBounds(50, 250, 100, 50);
        attachmentTextField.setBounds(150, 250, 200, 40);
        browseButton.setBounds(375, 250, 100, 20);

        jLabel6.setBounds(50, 300, 100, 50);
        messageTextArea.setBounds(150, 300, 300, 40);

        sendButton.setBounds(100, 400, 75, 20);
        cancelButton.setBounds(200, 400, 75, 20);
        JFrame mailFrame = new JFrame("Mail Sender");

        mailFrame.setSize(500, 500);

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)
        // TODO add your handling code here:

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)
        JFileChooser selectFile = new JFileChooser();

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)

        toAddress = toTextField.getText().trim();
        ccAddress = ccTextField.getText().trim();
        subject = subjectTextField.getText().trim();
        message = messageTextArea.getText().trim();
        String attachment = attachmentTextField.getText() + " ";

        attachments = attachment.split(" ");

        receipients = toAddress + "," + ccAddress;
        receipientsList = receipients.split(",");

        SendMailUsingAuthentication mailUsingAuthentication =
                new SendMailUsingAuthentication();
        try {
                    subject, message, fromAddress, authenticationPassword, attachments);
        } catch (MessagingException messagingException) {

    void login(String userName, String password)
        fromAddress = userName;
        authenticationPassword = password;
        System.out.println("User name : " + fromAddress);

    public static void main(String[] args)
        new MailSender();

This is the Code for send Mail with attachment

/* This code is used for send the mail to the any users.</div>
 * It is done by Java Mail Api.
 * By using this code we can send mail with out enter into your mail Account.
 * @author muneeswaran
package com.mail;

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMailUsingAuthentication {

    private String HOST_NAME = "gmail-smtp.l.google.com";
    String messageBody;

    public void postMail(String recipients[], String subject, String message,
            String from, String emailPassword, String[] files) throws MessagingException {
        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator authenticator = new SMTPAuthenticator(from, emailPassword);
        Session session = Session.getDefaultInstance(props, authenticator);


        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setContent(message, "text/plain");

        BodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();

        //add the message body to the mime message

        // add any file attachments to the message
        addAtachments(files, multipart);
        //Put all message parts in the message
        System.out.println("Sucessfully Sent mail to All Users");

    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            //use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            //add the attachment

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        String username;
        String password;

        private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
            username = authenticationUser;
            password = authenticationPassword;

        public PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);

  1. Wesslan
    March 11, 2010 at 6:48 am

    Apache Commons Email simplifies this a lot.

  2. tintin
    March 11, 2010 at 5:03 pm

    Great example

  3. Amit.A.Hublikare
    April 29, 2010 at 11:30 am

    hello, may i know how to keep a copy of mails in my local disk(hard disk) sent through dis application.
    and even how to store d inbox mails in my harddisk

    March 10, 2011 at 7:25 am

    Thank you very much!

    I got the error message…

    javax.mail.internet.AddressException: Illegal whitespace in address in string “put your full mail id”
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:926)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:819)
    at javax.mail.internet.InternetAddress.parse(InternetAddress.java:555)
    at javax.mail.internet.InternetAddress.(InternetAddress.java:91)
    at com.mail.SendMailUsingAuthentication.postMail(SendMailUsingAuthentication.java:70)
    at com.mail.MailSender.sendButtonActionPerformed(Mailsender.java:295)
    at com.mail.MailSender.access$000(Mailsender.java:17)
    at com.mail.MailSender$1.actionPerformed(Mailsender.java:116)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6263)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3255)
    at java.awt.Component.processEvent(Component.java:6028)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    • March 13, 2011 at 10:55 am

      Hi Hari,

      Please replace the string “put your full mail id” with your mail id.Then you will get the answer.

    March 17, 2011 at 4:23 am

    Thank you sir….
    I have clear now..
    and at the same time there is no attachmant..
    I will have to attach files to send the message,Can you help me Please…

  6. harihclcdc
    March 17, 2011 at 8:11 am

    Good noon Sir,
    shall we send SMS to Mobile throw our java application such as (swing or servlet(jsp))…,
    How we have the recognized sender authentication (Service Provider BSNL … ) and sample code…please..

    Thank you
    Sincerely yours

  7. nandy
    April 13, 2011 at 9:55 am

    hi i need code in java to transfer a file from client to server in same machine.the entire file should be sent… Do reply

  8. Ratin Kumar Gupta
    July 25, 2011 at 12:38 pm

    I am finding the following error:

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.websitetoolbox.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection refused: connect

    The error is in

    Plz help me in this.

    Thanks and regards.

  9. Nguyễn Lan
    August 9, 2011 at 5:24 pm

    Hi all

    I want receive mail from any client will send mail for me, my account email is GMAIL. I want use host mail by gmail is smtp.gmail.com & use JavaMail API to code. How should I code for the correct? Thanks so much!

  10. Neptune
    August 27, 2011 at 12:46 pm

    It is very useful code for us to work on client email account.
    I need help in creating email notifier client app which check new emails at every 5 mint
    and show me in status bar

    • August 29, 2011 at 4:44 am

      Hi Neptune,

      You will use this code with thread for get the email notifier.

  11. August 30, 2011 at 10:37 am

    when i use MailSender example i get the following error can u help me

    Exception in thread “AWT-EventQueue-0” java.lang.Error: Unresolved compilation problems:
    Access restriction: The constructor Provider() is not accessible due to restriction on required library C:\Program Files\Java\jdk1.6.0_13\jre\lib\jsse.jar
    Access restriction: The type Provider is not accessible due to restriction on required library C:\Program Files\Java\jdk1.6.0_13\jre\lib\jsse.jar

    at com.model.SendMailUsingAuthentication.postMail(SendMailUsingAuthentication.java:30)
    at com.model.MailSender.sendButtonActionPerformed(MailSender.java:153)
    at com.model.MailSender.access$0(MailSender.java:137)
    at com.model.MailSender$1.actionPerformed(MailSender.java:60)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6216)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
    at java.awt.Component.processEvent(Component.java:5981)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4583)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4413)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4556)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4220)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4150)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4413)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    thank u

  12. jaysukh sasukiya
    September 11, 2011 at 6:05 pm

    i am preparing a bank project in java using swing .there is an exception / nothing process while click ok button if i use getText() method of JTextField in actionPerformed() method and if i do not use getText() method then it work properly.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Fdemo extends JFrame implements ActionListener
    JTextField t1;
    JButton b1;
    JLabel l1;
    Fdemo(String s1)
    Container c1=getContentPane();

    c1.setLayout(new FlowLayout(FlowLayout.LEFT));
    JTextField t1=new JTextField(10);

    b1=new JButton(“ok”);

    l1=new JLabel(“hello”);


    public void actionPerformed(ActionEvent se)
    String ab=t1.getText();
    l1.setText(“how are you?”);


    class Fmain1
    public static void main(String as[])
    Fdemo fd=new Fdemo(“demo frame”);


    if i leave comment here String ab=t1.getText(); then it set text on label(work properly) otherwise when click ok button then exception ”

    java.awt.EventDispatchThread.pumpEventsForHierarchy” and may othes exceptionsgenerated in command prompt .so please help me BY email:jaysukhsasukiya3003@yahoo.com

    • September 14, 2011 at 8:09 am

      HI Jaysukh,

      In the above code you write like JTextField t1=new JTextField(10);,it hides the above field.
      Please use t1 = new JTextField(10); instead of JTextField t1=new JTextField(10);
      you will get the output.

  13. Kaushik
    September 15, 2011 at 2:53 pm

    These code is run very perfactly.
    But it doesn’t able to send attachment like image, .doc file, .xls file etc..

    If you have the code with such attachment, please send it on “kaushik.doshi2007@rediff.com”


  14. jai
    September 24, 2011 at 9:59 am

    hello ,sir now i am creating simple web browser using java swing .it works properly but it does not run java script please give the code for it………..my code is here

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class WebBrowser
    public static void main(String [] args)
    JFrame frame = new EditorPaneFrame();
    class EditorPaneFrame extends JFrame
    private JTextField url;
    private JCheckBox editable;
    private JButton loadButton;
    private JButton backButton;
    private JEditorPane editorPane;
    private Stack urlStack = new Stack();
    public EditorPaneFrame()
    setTitle(“Java Web Browser”);
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    } );
    // set up text field and load button for typing in URL
    url = new JTextField(30);
    loadButton = new JButton(“Load”);
    loadButton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event)
    // remember URL for back button
    catch(Exception e)
    editorPane.setText(“Error: ” +e);
    // set up back button and button action
    backButton = new JButton(“Back”);
    backButton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event)
    if(urlStack.size()<=1) return;
    String urlString = (String)urlStack.peek();
    catch(IOException e)
    editorPane.setText("Error : " +e);
    editorPane = new JEditorPane();
    editorPane.addHyperlinkListener(new HyperlinkListener()
    public void hyperlinkUpdate(HyperlinkEvent event)
    if(event.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
    catch(IOException e)
    editorPane.setText("Error: " + e);
    editable = new JCheckBox();
    editable.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event)
    Container contentPane = getContentPane();
    contentPane.add(new JScrollPane(editorPane), "Center");
    JPanel panel = new JPanel();
    panel.add(new JLabel("URL"));
    panel.add(new JLabel("Editable"));

  15. Ansh
    September 28, 2011 at 4:01 pm

    Hi ,

    I am not able to send the attachment & message body together . Please help me with this .
    Please find the code :

    public static void sendMail(String mailServer, String from, String[] to, String subject, String messageBody, String attachmentPath, String attachmentName) throws MessagingException, AddressException
    Properties props = System.getProperties();
    props.put(“mail.smtp.host”, mailServer);
    props.put(“mail.debug”, “true”);
    Session session = Session.getDefaultInstance(props, null);
    Transport bus = session.getTransport(“smtp”);
    Message message = new MimeMessage(session);

    //X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).

    message.addHeader(“X-Priority”, “1”);
    message.setFrom(new InternetAddress(from));
    InternetAddress[] addressTo = new InternetAddress[to.length];
    for (int i = 0; i < to.length; i++)
    addressTo[i] = new InternetAddress(to[i]);
    message.setRecipients(Message.RecipientType .TO, addressTo);
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    DataSource source = new FileDataSource(attachmentPath);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setText(messageBody); //Fill the message
    System.out.println("Message body is : " + messageBody);

    catch (MessagingException mex)

  16. manisha
    January 13, 2012 at 5:56 pm

    Thanx a lot….

  17. Zonic
    January 17, 2012 at 9:21 am


    Can you please let me know how can I check whether the email has been delivered to the recipient. So I can give a notification to the use about the mail delivery. Btw, your code it great, it works like a charm


  18. hari
    February 17, 2012 at 4:17 pm

    Hi sir,
    I want the complete procedure for where to save mail.jar and how to run it
    My mail id hari_vigneshct@yahoo.com

    • February 20, 2012 at 3:22 pm

      Hi Hari,

      If you use any IDE,add the mail jar with the library and proceed further.

  19. May 21, 2012 at 1:30 pm

    hey mail.jar is missing plz reply

  20. May 21, 2012 at 1:31 pm

    mail.jar is missing plz reply

  21. kiran kumar mandadapu
    June 21, 2012 at 6:32 am


    I want to add an image in attached Html report.But we are unable to get any clue How to add the image into report without attaching the image file as an mail attachment.Can any one please help me.

  22. Shweta Patil
    October 26, 2012 at 5:27 am

    sir i tried above code through eclipse but it won’t work at all.Also i added 3 jar files which are required to send mail i.e.smtp.jar, mailapi.jar, activation.jar. I had also replaced the “put u r mail id” string with my email id and password also but i didn’t get any output. can anyone help me regarding this problem

  23. Radha
    March 20, 2013 at 8:36 am

    Thank u very much. this tutorial is helpfull to my project

  24. Ravi Teja
    March 26, 2013 at 11:44 am

    its showing error SendMailUsingAuthentication cannot be resolved to type

  25. April 1, 2013 at 8:18 am

    hello sir can you build gui interface …..i want to send files,messages with chunking using udp with progress bar using java swings

    the recepient address be the ip address declaration( not domain like email)
    please give the code……….

  26. April 15, 2013 at 1:27 am

    I’m impressed, I must say. Seldom do I come across a blog that’s equally educative and entertaining,
    and let me tell you, you’ve hit the nail on the head. The problem is something that too few people are speaking intelligently about. I am very happy I found this in my hunt for something concerning this.

  27. September 21, 2013 at 5:05 pm

    Good day! This is my first comment here so I just wanted to give a quick shout out and tell you I truly
    enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that deal with the same topics?
    Thanks for your time!

  1. March 8, 2010 at 11:08 pm
  2. March 9, 2010 at 1:13 am
  3. March 9, 2010 at 10:06 pm
  4. March 12, 2010 at 4:30 am
  5. March 18, 2010 at 8:54 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: