Sending Email from Java application (JavaMail sample program)

By: Narayanan Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You can use the JavaMail API to send emails from your Java application. Though the JavaMail API allows you to do many things including the ability to retrieve and read the emails or sending emails etc, this sample java program demonstrates how to send email from your Java application. Remember to change the email host (String host) to your email server host, otherwise it won't work.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail {
public static void main(String[] args) {
// Collect the necessary information to send a simple message
// Make sure to replace the values for host, to, and from with
// valid information.
// host - must be a valid smtp server that you currently have
// access to.
// to - whoever is going to get your email
// from - whoever you want to be. Just remember that many smtp
// servers will validate the domain of the from address
// before allowing the mail to be sent.
String host = "server.myhost.com";
String to = "YourFriend@someemail.com";
String from = "Me@myhost.com";
String subject = "My First Email";
String messageText = "I am sending a message using the"
+ " JavaMail API.\n"
+ "Here type your message.";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try {
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(17)


1. View Comment

Hi professional,
I tried the above code but it is throwing the following error(i included mail.jar and activation.jar in the classpath also) Please help me out

javax.mail.MessagingException: Could not connect to SMTP host: 172.17.240.7, por
t: 25;
nested exception is:
java.net.SocketException: Software caused connection abort: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:41
2)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
at javax.mail.Transport.send(Transport.java:118)
at SimpleSendEmail.main(SimpleSendEmail.java:45)
Caused by: java.net.SocketException: Software caused connection abort: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:507)
at java.net.Socket.connect(Socket.java:457)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 7 more


View Tutorial          By: Srinivas at 2008-05-05 23:32:13
2. View Comment

Mail me Codings in java of different programs

View Tutorial          By: vikram at 2008-09-12 06:04:42
3. View Comment

Hey Narayanan, maybe you should check out Vesijama as well. It's a small (open source) wrapper library around the JavaMail smtp API (the stuff you use here). I'ts designed to not bother you with rfc's and requires minimal code.

http://code.google.com/p/vesijama/


View Tutorial          By: Benny Bottema at 2009-05-03 14:27:07
4. View Comment

I tried this code,but is showing this error

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticate
d

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1
333)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:906)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:535)
at javax.mail.Transport.send0(Transport.java:151)
at javax.mail.Transport.send(Transport.java:80)
at SimpleSendEmail.main(SimpleSendEmail.java:32)

Please tell me what is the error.


View Tutorial          By: anju at 2009-05-22 07:42:11
5. View Comment

Hello,
I've tried the above code, but I've ended up in the following error.

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 7sm4905442agd.3

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1333)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:906)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:535)
at javax.mail.Transport.send0(Transport.java:151)
at javax.mail.Transport.send(Transport.java:80)
at testing.MailTest.main(MailTest.java:49)

Could anyone help me?
Thanks and best regards.


View Tutorial          By: Phyo Phyo at 2009-09-14 05:32:28
6. View Comment

i need some simple java programs

View Tutorial          By: ramya at 2009-11-24 04:25:07
7. View Comment

When copying this code into my java IDE, should i configure any thing else in my conputer?
The IIS smtp server ?

I'm lost here because the code does't work with me and throwing this exception:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port:25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)


View Tutorial          By: Barabas at 2010-02-11 03:57:09
8. View Comment

worked for me thanks.

View Tutorial          By: dem125 at 2010-08-03 23:30:32
9. View Comment

hai, i tried the abvoe code, m getting the follwing errors... please help me...
javax.mail.SendfailedException: sending failed;
nested exception is:
java.mail.messagingexception; could not connect to SMTP host :localhost,port:25;

nested exception is:
javax.net.connectexception: connection refused:connect
at javax.mail.transport.send0(transport:java:219)
at javax.mail.transport.send(transport:java:81)
at sendemail.main(sendemail.java;49)


View Tutorial          By: anith at 2011-03-13 06:02:31
10. View Comment

hai, i tried the abvoe code, m getting the follwing errors... please help me...
javax.mail.SendfailedException: sending failed;
nested exception is:
java.mail.messagingexception; could not connect to SMTP host :localhost,port:25;

nested exception is:
javax.net.connectexception: connection refused:connect
at javax.mail.transport.send0(transport:java:219)
at javax.mail.transport.send(transport:java:81)
at sendemail.main(sendemail.java;49)


View Tutorial          By: charan at 2011-10-20 12:59:59
11. View Comment

hi to all i m getting this error plz solve it and replied to my mail
kprasad587@gmail.com

javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com ;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at SimpleSendEmail.main(SimpleSendEmail.java:45)


View Tutorial          By: krishna prasad at 2011-10-28 10:16:26
12. View Comment

hello after working with this code i got the follwing Exception message
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. jm5sm18410921pbc.1

at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at in.xyz.SimpleSendEmail.main(SimpleSendEmail.java:47)


View Tutorial          By: Tapaswini Sabat at 2011-11-05 12:43:49
13. View Comment

Hello, I have been using a very similar code on development of a email verification system. All have worked fine in local system (i.e. my computer) but now, when I deploy to production server I'm getting the following exception.

DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtpout.mysmtpserver.ext", port 3535, isSSL false
DEBUG SMTP: EOF: [EOF]
DEBUG SMTP: could not connect to host "smtpout.mysmtpserver.ext", port: 3535, response: -1

javax.mail.MessagingException: Could not connect to SMTP host: smtpout.secureserver.net, port: 25, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1922)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)

This is just beyond my knowledge. I have tried changing the port to 25 but still get the same error. And again, works fine locally but crashes in server.
I would greatly appreciate it if you could at least give me a light here.
Thanks in advance.


View Tutorial          By: Rod at 2011-11-13 15:09:52
14. View Comment

hello how can i get a better java date code

View Tutorial          By: ramutomotest at 2011-12-08 17:44:49
15. View Comment

Including the required mail properties should solve most of the errors listed above.... try it out

mail.smtp.host
mail.username
mail.password
mail.port

and the trick is how these parameters are being used and passed to the framework on which the application is running.


View Tutorial          By: Rajesh Vaddi at 2011-12-13 23:55:15
16. View Comment

Hi,
What is the process if I want to know whether the email has been successfully sent to the email address provided? Here successfully means,
1. Recipient email server is not down.
2. Recipient email address is valid.
Is there any response sent back when I send an email from the recipient server? If yes, how to catch it in java?
I would be highly obliged if you'll kindly answer my issue.


View Tutorial          By: Koushik Roy at 2012-07-13 05:35:35
17. View Comment

I am getting this exeception when trying to send mail..


DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.7.0_09\jre\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.7.0_09\jre\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.live.com", port 25, isSSL false
DEBUG SMTP: exception reading response: java.net.SocketException: Connection reset
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at com.shoppeeant.SendMail.sendemail(SendMail.java:52)
at org.apache.jsp.JSP.ForgotPassword_jsp._jspService(ForgotPassword_jsp.java:94)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440)


View Tutorial          By: praveen at 2012-12-27 11:15:14

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Narayanan
Sending Email from Java application (JavaMail sample program)

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java