JavaMail API – Sending email via Gmail SMTP example
Here are two examples to show you how to use JavaMail API method to send an email via Gmail SMTP server, using both TLS and SSL connection.
To run this example, you need two dependency libraries – javaee.jar and mail.jar, both are bundle in JavaEE SDK.
Outgoing Mail (SMTP) Server requires TLS or SSL: smtp.gmail.com (use authentication) Use Authentication: Yes Port for TLS/STARTTLS: 587 Port for SSL: 465
GMail SMTP detail here – http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
1. JavaMail – GMail via TLS
Send an Email via Gmail SMTP server using TLS connection.
package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailTLS { public static void main(String[] args) { String host = "smtp.gmail.com"; int port = 587; String username = "username"; String password = "password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@no-spam.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@no-spam.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport transport = session.getTransport("smtp"); transport.connect(host, port, username, password); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
2. JavaMail – GMail via SSL
Send an Email via Gmail SMTP server using SSL connection.
package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailSSL { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username","password"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@no-spam.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@no-spam.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
Some hit the
UnknownHostException: smtp.gmail.com, try ping smtp.gmail.com and make sure you got a response (able to access). Often times, your connection may block by your firewall or proxy behind.
Mail sending is working superb.
But do you know , how can we check whether the mail sent is successful or failed?
I would appritiate if ur SSL code works for connecting other smtp too.
I am trying to connect 10.5.128.146 at port 25.
but it is not connecting. Connection timed out msg is coming.
plz help
Thanks in Advance
The problem is that TCP/25 the normal , un-crypted port is. So it depends on your SMTP-server-config if it allows encrypted connection or if you have to use plain connection.
This problem does not come from the code but rather from your server-config.
Well … now … I found the problem with TSL Method.
Your code works as follows
-setting up a new Transport-Connection
-connecting the Transport-Object
so far so good
but then your code goes wrong
-using the static method Transport.send(Message)
The Doc says : this method handles its OWN connection
So why this is the reason for failure ?
Because there no information in the Properties wich Username nor wich Password to use. So to fix this there two ways:
1) setting up the properties correct and delete the whole manual connection set-up
2) using SMTPTransport.sendMessage(Message, Address[]) to send the message
and finaly clean up the connection by invoking CLOSE()
to use the 2nd method you need to set-up a SMTPTransport or a SMTPSSLTransport with properties wich contains the TSL information and then invoke Service.connect(String, int, String, String)
a working example with TSL
hope this helps
Thanks sir ,now its work properly.
finaly
got it work with the other SMTP-Server web.de
simply used TLS-version with changes as i said …
addition
please add comment that G-Mail only works on Port 465 for SSL Method !!
Sorry … hit RETURN to fast … my bad
what i want to say :
SSL works fine with G-Mail … but not with some other Servers … tried 465 and 587 as port value …
error :
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Server : web.de *germany*
TLS doesnt work at all
always get this
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
i am Java-Programmer for 6 years now … and i know what these exceptions mean … but i dont know WHY they are thrown …
any ideas ?
found a solution for TLS-Method
simply use the SSL-Class
BUT
-remove the SSL-Factory-Settings
-set Port to 587
-add the StartTLS-line from TLS-Class to it
DONE
the TLS-Method seems to have bugs in the connect()-Method
Hello sir,i went to send mail in my email id with help of java.mail,for this code use by me is following
package mail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Main {
public static void main(String[] args) {
String host = “smtp.gmail.com”;
int port = 587;
String username = “ajitsingh17985″;
String password = “557216557216″;
Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.starttls.enable”, “true”);
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(“gmail.com”));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(“gmail.com”));
message.setSubject(“Testing Subject”);
message.setText(“Dear Mail Crawler,” +
“\n\n No spam to my email, please!”);
Transport transport = session.getTransport(“smtp”);
transport.connect(host, port, “ajitsingh17985″, “557216557216″);
Transport.send(message);
System.out.println(“Done”);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
and it not works for me error is:-
at mail.Main.main(Main.java:43)
Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at mail.Main.main(Main.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Please help me
can any one help me
thank u soo much..it works..
Hi All
Can you help me this problem?
That is: I want send mail from any address mail to a static address mail using stmp. How can I code? Thanks!
Addition…
That’s: Any Address From Email has not
Authentication but it can send mail. Please help me!
You need to code it yourself, and tell me what’s your problem. Not asking others to do it for you.
Hi mkyong
I had code as:
Properties props = new Properties();
props.put(“mail.smtp.host”, “mailserver.com”);
Session s = Session.getInstance(props,null);
InternetAddress from = new InternetAddress(dynamic_email);// get customer input
InternetAddress to = new InternetAddress(myemail@gmail.com”); //this’s my email
MimeMessage message = new MimeMessage(s);
message.setFrom(from);
message.addRecipient(Message.RecipientTy
pe.TO, to);
message.setSubject(“Your subject”);
message.setText(“Your text”);
Transport.send(message);
But it is not send mail, Please help me! thanks so much!
Please post your last caused by error message
Error: authentication require.
Now I want receive mail from any client will send for me, my account email is Gmail. How should I code for the correct?
Hi mkyong
I have been coding as:
Now I call method above: receiveMailFromClient(“mydream003600@yahoo.com”,”Hello Mydream”,”How are you?”);
But I had not been received mail from any client sent for me. Can you help
2nd one worked for me….thanks buddy……………………………..
.. hello guys the second example works for me….
i just get that codes and paste to my struts 2 application
and it did fine thanks for the codes…
I’m a 17 years old programmer ….
Looking forward for being a good programmer surfing only in
the internet..
Nice to meet you, wonder a 17 years old guy will interest at programming. When i was 17, I just know to use computer to play game :p
Thank you so much, the 2nd program works. The first one doesn’t seem to work.
thanks,
mkyong
finally i succeed thanks a lot buddy really u did a nice work i never forgot u……
I used SSL its worked yar
OK, I will try the SSL version.
[...] Als je even googlet zie je dat er nog mensen het probleem hebben. SSL werkt blijkbaar wel JavaMail API – Sending email via Gmail SMTP example [...]
Hi Mkyong,
I am new to Java and tried your TLS version, as I need to add an email function to an existing app. I am getting the following error. I have sent the code I am using as well. Any help or comments are greatly appreciated.
Thanks,
Michael
Java -cp c:/fis/jre/lib/rt.jar;/fis/lib/mail.jar;/fis/jre/lib/jsse.jar;/fis/lib/xerces.jar;/fis/jre/lib/jce.jar;/fis/jre/lib/sunrsasign.jar;/fis/lib/com.checksol.dex.gateway_v1r1m1f1.jar;/fis/lib/importscrubber.jar;/fis/lib/bcel.jar;/fis/lib/junit.jar;/fis/lib/DoxygenTask.jar;/fis/lib/jalopy-ant-bundle-0.5.2.jar;/fis/lib/jdepend.jar;/fis/lib/xalan.jar;/fis/lib/jaxen-full.jar;/fis/lib/saxpath.jar;/fis/lib/Quick4rt.jar;/fis/lib/regexp.jar;/fis/lib/mail.jar;/fis/lib/mailapi.jar;/fis/lib/activation.jar;/fis/lib/smtp.jar;/fis/lib/tools.jar; SendTLS/SendMailTLS
DEBUG: setDebug: JavaMail version 1.3
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG: SMTPTransport trying to connect to host “smtp.gmail.com”, port 5
DEBUG SMTP RCVD: 220 mx.google.com ESMTP g3sm226831vce.18
DEBUG: SMTPTransport connected to host “smtp.gmail.com”, port: 587
DEBUG SMTP SENT: EHLO NISTEST
DEBUG SMTP RCVD: 250-mx.google.com at your service, [4.58.28.162]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP Found extension “SIZE”, arg “35882577″
DEBUG SMTP Found extension “8BITMIME”, arg “”
DEBUG SMTP Found extension “STARTTLS”, arg “”
DEBUG SMTP Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Exception in thread “main” java.lang.RuntimeException: javax.mail.SendF
ption: Sending failed;
nested exception is:
class javax.mail.AuthenticationFailedException
at SendTLS.SendMailTLS.main(SendMailTLS.java:47)
Caused by: javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.AuthenticationFailedException
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at SendTLS.SendMailTLS.main(SendMailTLS.java:42)
Hi Mkyong!
Thanks for the SSL codes, it works for me.
I also added a file attachment option.
I run it in a JSP file on Tomcat 6.0 local host server. My question is “how can I publish it on a distant server? Does it require a simple configuration?”
how sending mail using struts please help me some one…
Just implements the code in your struts action or any business object.
… hello guys i have an error like this…
authentication required, obviously, make sure you are using correct username and password.
Hi, i’ve tried the both TLS and SSL, no one worked….please if you have any idea of what the problem is then please help me!
that what i get when i run the SSL :
Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at javax.mail.Session.loadProvidersFromStream(Session.java:928)
at javax.mail.Session.access$000(Session.java:174)
at javax.mail.Session$1.load(Session.java:870)
at javax.mail.Session.loadResource(Session.java:1084)
at javax.mail.Session.loadProviders(Session.java:889)
at javax.mail.Session.(Session.java:210)
at javax.mail.Session.getDefaultInstance(Session.java:299)
at com.servlet.JavaMail.main(JavaMail.java:22)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.LineInputStream
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at sun.misc.Launcher$ExtClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 8 more
And that’s what i get when i run the TLS:
Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/BASE64EncoderStream
at javax.mail.internet.MimeMessage.setSubject(MimeMessage.java:793)
at javax.mail.internet.MimeMessage.setSubject(MimeMessage.java:757)
at com.servlet.JavaMail.main(JavaMail.java:30)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.BASE64EncoderStream
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at sun.misc.Launcher$ExtClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 3 more
please replay me!
The error messages are obvious…
You need javaee.jar and mail.jar, both are available in JavaEE SDK.
i didn’t tried second method.
but when i tried first method. it shows following exception.
Seems like it need authontication
i gave my mail id and password in the line
in following variables
String username = “my gmail id”;
String password = “my password”;
i m not sure why it is showing the exception.
Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at JavaMailTest.main(JavaMailTest.java:47)
Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at JavaMailTest.main(JavaMailTest.java:42)
Try 2nd way, see if this work?
For the first example, use this instead in send:
transport.sendMessage(message, message.getAllRecipients());
pls help me out
i m new to java
what is this com.mkyong.common package??
tls ??
ssl??
Study what is java package – http://en.wikipedia.org/wiki/Java_package , the “com.mkyong.common package” is just my package name
, in future , you can try post your question at http://javanullpointer.com
hay..when i am trying this logic from my localhost laptop.
it’s working well, but it is not working when i m uploading this logic on my hosting panel….:-(
so any idea about this…
Thanks lot, i done my project through this coding
thanks again,
thusitha
dear sir,
I am always getting the exception connection is timed out so could not connect!!!
please help asap
It is not working when i put the code in my servlet (but no error is shown)
Does this work for servlets or there is some workaround to make them work?
Help appreciated.
[...] JavaMail API to send Email via GMail smtp server, but hit the following error message : Caused by: [...]
hi,
i am using ssl but i got an following error please help me
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at email.main(email.java:42)
Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1389)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
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 email.main(email.java:37)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:520)
at java.net.Socket.connect(Socket.java:470)
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
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)
SSL example test at 26/feb/2011, with my gmail account, working fine.
Try ping smtp.gmail.com and make sure your connection is able to access it.
[...] http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ [...]
i am a beginner in java
you could give reply please..
thanks.
i am a beginner in java.how to send mail from application use with java mail in j-seam framework & server is jboss
Hi Iam getting following error while executing code
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at emailtestapps.JavaMailApp2.main(JavaMailApp2.java:53)
Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:297)
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 emailtestapps.JavaMailApp2.main(JavaMailApp2.java:48)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
… 7 more
Java Result: 1
please suggest way ..
Thanks
Vijay
HI,
i am also got same exception.
could you find out the reason of that exception.
how did u solve that problem?
please give reply to me.
thanks,
Your program cannot find the smtp.gmail.com host. You should configure DNS servers or use some DNS server configuration property in JavaMail.
[...] [...]
I tried both examples. I updated the username with my gmail username and password with my gmail account password. All run got below error “Connection time out”: ( I do not know why somebody tried these examples successfuly! please help)
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at org.rrd.it.gmail.Gmail.main(Gmail.java:42)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
HI,
i am also tried both two examples but it gives same exception which exception u could get in past that one i got.
please send any solution for that.could you please give me fast replay.
thanQ,for future replay
pandu
Hi Pandu, I’ve tried the second example and success.
-agus-
Gmail TLS didn’t work for me. It gave me authentication failed exception as mention by yehia. So I added pass Anonymous instance of javgax.mail.Authenticator class as shown below.
Session session = Session.getInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});
It did resolved the issue but not I am getting SendFailureException as shown below:
Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for user@gmail.com
at com.mkyong.common.JavaMailApp1.main(JavaMailApp1.java:55)
Caused by: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for @gmail.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at com.mkyong.common.JavaMailApp1.main(JavaMailApp1.java:50)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for user@gmail.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
… 4 more
Thanks a lot………really appreciate your work..
Hi Your JavaMailApp2.java works very well and thanks for proving here .
You are great .
[...] http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ [...]
Sir,i would like to send mail via gmail using JAVAMAIL with JSP…
This was the easiest example of all others listed on google and worked in the first shot. Good work.
i got an unknown smtp host error please help me
[...] is just an API – you need a real "mail agent" for it to talk to. Here's a good link: http://www.mkyong.com/java/javamail-…-smtp-example/ SUGGESTION: 1. Set up a GMail account (for testing purposes) 2. Write the JavaMail "hello [...]
thank you mkyong;
kindly help me in the following:
i used the following code in a program, but it is showing error;
props.put(“mail.smtp.host”, “mail.yourisp.com”);
can you tell, what is the smtp host for gmail and how to find isp…. please help me…..
For gmail smtp detail, check here http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
Btw, what’s your error message?
this is the error, it is showing.
“Sending failed; nested exception is: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.SocketException: Network is unreachable: connect”
and this is the coding:
package com.test;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
public final class MailerBean extends Object implements Serializable {
/* Bean Properties */
private String to = null;
private String from = null;
private String subject = null;
private String message = null;
public static Properties props = null;
public static Session session = null;
static {
/* Setting Properties for STMP host */
props = System.getProperties();
props.put(“mail.smtp.host”, “smtp.gmail.com”);
session = Session.getDefaultInstance(props, null);
}
/* Setter Methods */
public void setTo(String to) {
this.to = to;
}
public void setFrom(String from) {
this.from = from;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setMessage(String message) {
this.message = message;
}
/* Sends Email */
public void sendMail() throws Exception {
if(!this.everythingIsSet())
throw new Exception(“Could not send email.”);
try {
MimeMessage message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(this.to));
message.setFrom(new InternetAddress(this.from));
message.setSubject(this.subject);
message.setText(this.message);
Transport.send(message);
} catch (MessagingException e) {
throw new Exception(e.getMessage());
}
}
/* Checks whether all properties have been set or not */
private boolean everythingIsSet() {
if((this.to == null) || (this.from == null) ||
(this.subject == null) || (this.message == null))
return false;
if((this.to.indexOf(“@”) == -1) ||
(this.to.indexOf(“.”) == -1))
return false;
if((this.from.indexOf(“@”) == -1) ||
(this.from.indexOf(“.”) == -1))
return false;
return true;
}
}
moreover, i am in need of a jsp code, that could send mail. can you help me.
Again, check THIS Gmail smtp detail http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
Gmail is required special workaround to send email, please compare your code with this article example.
do you have coding to send mail using jsp…. it may be useful for me…
my mail id is manihece@gmail.com.
i am a beginner in java…. can you please tell, how to compile and run this code.
This is a normal Java program, uses javac to compile and java to run.
i need email coding and chating room coding in j2ee
This was extremely useful! I’ve been troubleshooting my code with the API and with examples. Yours solved my problem. Thanks
You’re welcome, good to know it helped someone
Top notch code that i can’t find even in google!
Thank you!
Thank you sir for the code but can u please publish the code for receiving the email.
thank you sir, but it dose not work witn me and give me this erroe:
Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5
at com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:78)
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
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)
at com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:57)
and I’m sure from username and password
Very good site thank you for all the content.
Using the above email prog how would I go about adding in the ability to attach a file?
Many thanks,
Peter
thank you sir this example helped me a lot and is very useful
it complete as you have shown the settings to be done on gmail for this
purpose via link
plz tell what should be done for rediffmail
Sorry, i dont have rediffmail account, you should check with rediffmail mail server setting and modify the code accordingly
TLS Failed for me? No tuts seem to work for GMail or Windows Live TLS :\
Thank you ! This example is very useful for me.
SSL works fine, and is very easier!!! Thanks man!
Cheers!!
SSL worked but TLS did not worked it says the authentication failed so may i know the reason why it say so and thanks for the code it worked after i tried so many codes and each code failed except urs so thank u so much
Excellent article! I used SSL approach and able to send mail to gmail account. I was stuck in this for some time. Thanks for the help.
you’re welcome
i have to send a mail from seam application.i used above code but it gave one exception i.e below i give.please give solution
thanks,
java.net.UnknownHostException: smtp.gmail.com
04:46:42,407 ERROR [STDERR] javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com ;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
04:46:42,407 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)
04:46:42,407 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:297)
04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:156)
04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:105)
04:46:42,407 ERROR [STDERR] at javax.mail.Transport.send0(Transport.java:168)
04:46:42,407 ERROR [STDERR] at javax.mail.Transport.send(Transport.java:98)
04:46:42,423 ERROR [STDERR] at com.infyz.streamline.manager.session.MailAction.forgotUser(MailAction.java:273)
04:46:42,423 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
04:46:42,423 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
04:46:42,423 ERROR [STDERR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
04:46:42,423 ERROR [STDERR] at java.lang.reflect.Method.invoke(Method.java:597)
04:46:42,423 ERROR [STDERR] at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:112)
04:46:42,423 ERROR [STDERR] at org.jboss.ejb3.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:166)
04:46:42,423 ERROR [STDERR] at org.jboss.seam.intercept.EJBInvocationContext.proceed(EJBInvocationContext.java:44)
Hi,
you said you could success in send mail.
please can u send the which settings i have to do.
i used above ssl code but it gives exception i.e
# javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
# nested exception is:
# java.net.UnknownHostException: smtp.gmail.com
please send the details ,
thanks,
pandu.v