Java code sending Mail with Attachment using Java Mail API
Introduction
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
Code:
/ * 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()
{
initComponents();
}
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();
//setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("AlMateen-Bold", 3, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(1, 203, 221));
jLabel1.setText("Mail Sender");
jScrollPane1.setViewportView(messageTextArea);
sendButton.setText("Send");
sendButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
sendButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cancelButtonActionPerformed(evt);
}
});
browseButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
browseButtonActionPerformed(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.add(jLabel1);
mailFrame.add(jLabel2);
mailFrame.add(toTextField);
mailFrame.add(jLabel3);
mailFrame.add(ccTextField);
mailFrame.add(jLabel4);
mailFrame.add(subjectTextField);
mailFrame.add(jLabel5);
mailFrame.add(attachmentTextField);
mailFrame.add(browseButton);
mailFrame.add(jLabel6);
mailFrame.add(messageTextArea);
mailFrame.add(sendButton);
mailFrame.add(cancelButton);
mailFrame.setLayout(null);
mailFrame.setVisible(true);
mailFrame.setSize(500, 500);
mailFrame.setResizable(false);
mailFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
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();
selectFile.showOpenDialog(this);
attachmentTextField.setText(selectFile.getSelectedFile().toString());
}
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 {
mailUsingAuthentication.postMail(receipientsList,
subject, message, fromAddress, authenticationPassword, attachments);
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
}
}
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);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
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.setSubject(subject);
msg.setContent(message, "text/plain");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
//add the message body to the mime message
multipart.addBodyPart(messageBodyPart);
// add any file attachments to the message
addAtachments(files, multipart);
//Put all message parts in the message
msg.setContent(multipart);
Transport.send(msg);
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));
attachmentBodyPart.setFileName(filename);
//add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
String username;
String password;
private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
username = authenticationUser;
password = authenticationPassword;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
}
Categories: Java, mail
gmail, how to send email using java, Java, Java Mail API, java mail api attachment, java mail attach file, java mail client, java mail properties, java mail server, java mail tutorial, javamail example, mail, mail api, mail sender, mail with attachment, send mail, sending mail

Apache Commons Email simplifies this a lot.
http://commons.apache.org/email/
Thanks for your sharing
Great example
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
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)
Hi Hari,
Please replace the string “put your full mail id” with your mail id.Then you will get the answer.
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…
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
Hariharan.G
Hi Hari,
Go thru the below link,I think its helpful to you.
http://www.java-samples.com/showtutorial.php?tutorialid=22
Happy Coding…
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
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
Transport.send(msg);
Plz help me in this.
Thanks and regards.
Ratin
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!
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
Hi Neptune,
You will use this code with thread for get the email notifier.
hi
sir
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
Hi Guptha,
The below links help to resolve your issue
http://www.coderanch.com/t/455878/Security/jsse-jar
hi,sir.
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)
{
super(s1);
Container c1=getContentPane();
c1.setLayout(new FlowLayout(FlowLayout.LEFT));
JTextField t1=new JTextField(10);
c1.add(t1);
b1=new JButton(“ok”);
b1.addActionListener(this);
c1.add(b1);
l1=new JLabel(“hello”);
c1.add(l1);
}
public void actionPerformed(ActionEvent se)
{
if(se.getActionCommand()==”ok”)
{
String ab=t1.getText();
l1.setText(“how are you?”);
}
}
}
class Fmain1
{
public static void main(String as[])
{
Fdemo fd=new Fdemo(“demo frame”);
fd.setVisible(true);
fd.setSize(400,400);
}
}
if i leave comment here String ab=t1.getText(); then it set text on label(work properly) otherwise when click ok button then exception ”
AbsractButton.fireActionPerformed(AbstractButton.java:19)
java.awt.EventDispatchThread.pumpEventsForHierarchy” and may othes exceptionsgenerated in command prompt .so please help me BY email:jaysukhsasukiya3003@yahoo.com
by
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.
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”
Thanks…
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();
frame.show();
}
}
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”);
setSize(600,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
} );
// 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)
{
try
{
// remember URL for back button
urlStack.push(url.getText());
editorPane.setPage(url.getText());
}
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;
try
{
urlStack.pop();
String urlString = (String)urlStack.peek();
url.setText(urlString);
editorPane.setPage(urlString);
}
catch(IOException e)
{
editorPane.setText("Error : " +e);
}
}
});
editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent event)
{
if(event.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
try
{
urlStack.push(event.getURL().toString());
url.setText(event.getURL().toString());
editorPane.setPage(event.getURL());
}
catch(IOException e)
{
editorPane.setText("Error: " + e);
}
}
}
});
editable = new JCheckBox();
editable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
editorPane.setEditable(editable.isSelected());
}
});
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(editorPane), "Center");
JPanel panel = new JPanel();
panel.add(new JLabel("URL"));
panel.add(url);
panel.add(loadButton);
panel.add(backButton);
panel.add(new JLabel("Editable"));
panel.add(editable);
contentPane.add(panel,"South");
}
}
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);
try
{
Transport bus = session.getTransport(“smtp”);
bus.connect();
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);
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
messageBodyPart.setText(messageBody); //Fill the message
System.out.println("Message body is : " + messageBody);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
Thanx a lot….
Hi,
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
Thanks
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
Hi Hari,
If you use any IDE,add the mail jar with the library and proceed further.
hey mail.jar is missing plz reply
Hey
mail.jar is missing plz reply