Today we will look into JavaMail Example to send email in java programs. Sending emails is one of the common tasks in real life applications and that’s why Java provides robust JavaMail API that we can use to send emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.
Table of Contents
- 1 JavaMail Example
- 1.1 JavaMail Example Program
- 1.2 Send Mail in Java using SMTP without authentication
- 1.3 Send Email in Java SMTP with TLS Authentication
- 1.4 Java SMTP Example with SSL Authentication
- 1.5 JavaMail Example – send mail in java with attachment
- 1.6 JavaMail example – send mail in java with image
- 1.7 JavaMail API Troubleshooting Tips
JavaMail Example
Today we will learn how to use JavaMail API to send emails using SMTP server with no authentication, TLS and SSL authentication and how to send attachments and attach and use images in the email body. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them.
JavaMail API is not part of standard JDK, so you will have to download it from it’s official website i.e JavaMail Home Page. Download the latest version of the JavaMail reference implementation and include it in your project build path. The jar file name will be javax.mail.jar.
If you are using Maven based project, just add below dependency in your project.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
Java Program to send email contains following steps:
- Creating
javax.mail.Session
object - Creating
javax.mail.internet.MimeMessage
object, we have to set different properties in this object such as recipient email address, Email Subject, Reply-To email, email body, attachments etc. - Using
javax.mail.Transport
to send the email message.
The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn’t require any authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL authentication, then logic to create will differ.
So I will create a utility class with some utility methods to send emails and then I will use this utility method with different SMTP servers.
JavaMail Example Program
Our EmailUtil class that has a single method to send email looks like below, it requires javax.mail.Session and some other required fields as arguments. To keep it simple, some of the arguments are hard coded but you can extend this method to pass them or read it from some config files.
package com.journaldev.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailUtil {
/**
* Utility method to send simple HTML email
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply@example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Notice that I am setting some header properties in the MimeMessage, they are used by the email clients to properly render and display the email message. Rest of the program is simple and self understood.
Now let’s create our program to send email without authentication.
Send Mail in Java using SMTP without authentication
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Session;
public class SimpleEmail {
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.example.com";
String emailID = "email_me@example.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
Session session = Session.getInstance(props, null);
EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
}
}
Notice that I am using Session.getInstance() to get the Session object by passing the Properties object. We need to set the mail.smtp.host property with the SMTP server host. If the SMTP server is not running on default port (25), then you will also need to set mail.smtp.port property. Just run this program with your no-authentication SMTP server and by setting recipient email id as your own email id and you will get the email in no time.
The program is simple to understand and works well, but in real life most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So we will now see how to create Session object for these authentication protocols.
Send Email in Java SMTP with TLS Authentication
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
public class TLSEmail {
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
*/
public static void main(String[] args) {
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
}
}
Since I am using GMail SMTP server that is accessible to all, you can set the correct variables in above program and run for yourself. Believe me it works!! 🙂
Java SMTP Example with SSL Authentication
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
public class SSLEmail {
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");
EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");
}
}
The program is almost same as TLS authentication, just some properties are different. As you can see that I am calling some other methods from EmailUtil class to send attachment and image in email but I haven’t defined them yet. Actually I kept them to show later and keep it simple at start of the tutorial.
JavaMail Example – send mail in java with attachment
To send a file as attachment, we need to create an object of javax.mail.internet.MimeBodyPart
and javax.mail.internet.MimeMultipart
. First add the body part for the text message in the email and then use FileDataSource to attach the file in second part of the multipart body. The method looks like below.
/**
* Utility method to send email with attachment
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendAttachmentEmail(Session session, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply@example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Second part is attachment
messageBodyPart = new MimeBodyPart();
String filename = "abc.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
The program might look complex at first look but it’s simple, just create a body part for text message and another body part for attachment and then add them to the multipart. You can extend this method to attach multiple files too.
JavaMail example – send mail in java with image
Since we can create HTML body message, if the image file is located at some server location we can use img element to show them in the message. But sometimes we want to attach the image in the email and then use it in the email body itself. You must have seen so many emails that have image attachments and are also used in the email message.
The trick is to attach the image file like any other attachment and then set the Content-ID header for image file and then use the same content id in the email message body with <img src='cid:image_id'>
.
/**
* Utility method to send image in email body
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendImageEmail(Session session, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply@example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Second part is image attachment
messageBodyPart = new MimeBodyPart();
String filename = "image.png";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
//Trick is to add the content-id header here
messageBodyPart.setHeader("Content-ID", "image_id");
multipart.addBodyPart(messageBodyPart);
//third part for displaying image in the email body
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<h1>Attached Image</h1>" +
"<img src='cid:image_id'>", "text/html");
multipart.addBodyPart(messageBodyPart);
//Set the multipart message to the email message
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with image!!");
}catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
JavaMail API Troubleshooting Tips
java.net.UnknownHostException
comes when your system is not able to resolve the IP address for the SMTP server, it might be wrong or not accessible from your network. For example, GMail SMTP server is smtp.gmail.com and if I use smtp.google.com, I will get this exception. If the hostname is correct, try to ping the server through command line to make sure it’s accessible from your system.pankaj@Pankaj:~/CODE$ ping smtp.gmail.com PING gmail-smtp-msa.l.google.com (74.125.129.108): 56 data bytes 64 bytes from 74.125.129.108: icmp_seq=0 ttl=46 time=38.308 ms 64 bytes from 74.125.129.108: icmp_seq=1 ttl=46 time=42.247 ms 64 bytes from 74.125.129.108: icmp_seq=2 ttl=46 time=38.164 ms 64 bytes from 74.125.129.108: icmp_seq=3 ttl=46 time=53.153 ms
- If your program is stuck in Transport send() method call, check that SMTP port is correct. If it’s correct then use telnet to verify that it’s accessible from you machine, you will get output like below.
pankaj@Pankaj:~/CODE$ telnet smtp.gmail.com 587 Trying 2607:f8b0:400e:c02::6d... Connected to gmail-smtp-msa.l.google.com. Escape character is '^]'. 220 mx.google.com ESMTP sx8sm78485186pab.5 - gsmtp HELO 250 mx.google.com at your service
That’s all for JavaMail example to send mail in java using SMTP server with different authentication protocols, attachment and images. I hope it will solve all your needs for sending emails in java programs.
hi pankaj,
when i use this i’m getting – unable to find valid certification path to requested target,
can you help me with this
Hello Mstr @Pankaj , I would thank you first for this useful tutoriel , and ask you a queqtion if you don’t mind:
I used the SMTP via TLS configurtion, in the bigenning it doesn’t work but when I enabled Less Secure App
and in Local it works very well .But the problem appears again when I build my work is remoted in the Server of the Company. Here is the error :
“timestamp”: 1586528739449,
“status”: 500,
“error”: “Internal Server Error”,
“exception”: “javax.mail.AuthenticationFailedException”,
“message”: “534-5.7.14 \n534-5.7.14 Please log in via your web browser and then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/answer/78754 f2sm3094546wro.59 – gsmtp\n”,
“path”: “/api/mailing/sendMail”
}
Thank uou so much for your help 🙂 .
Try enabling “Less secure apps” in your Gmail dashboard
Hello every one I have run the code then I get this error says that:
run:
SimpleEmail Start
Exception in thread “main” java.lang.ExceptionInInitializerError
at com.journaldev.mail.SimpleEmail.main(SimpleEmail.java:23)
Caused by: java.lang.RuntimeException: Uncompilable source code – class EmailUtil is public, should be declared in a file named EmailUtil.java
at com.journaldev.mail.EmailUtil.(EmailUtil_1.java:21)
… 1 more
C:\Users\HP\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I need help to solve that error and I need to make a forgot password with email in jsp so you may help me ?
my code is working fine with local machine but when i host the website and my functionality it is not working. there is parsing issue at server side. I didn’t get the issue. please help!
This is a great start for developers new to emailing in Java, but dealing with javax JavaMail (nowadays migrated to Jakarta Mail) is very low level. Depending on your combination of needs (embedded images, attachments, iCalendar integration, forwarded email, replied-to email, alternative content) you need different Mime structures to have proper email behavior across email clients. You can explore all those structures here: https://www.simplejavamail.org/rfc-compliant.html#section-explore-multipart
Simple Java Mail (https://www.simplejavamail.org) is an open source library that manages these structures for you. It has a much simpler API and simplifies configuration for SSL/TLS connections. In addition, it adds tons of capabilities such as authenticated proxy, encryption, batch processing and much more.
People really shouldn’t be dealing with Mime objects anymore in this day and age. It’s an archaic system that is poorly described in terms of which structure to apply for which combination of needs. This includes most libraries such as Apache, Spring and JavaMail itself. Simple Java Mail solves this problem entirely free of cost.
hello using this code i am being able to send emails to only yaahoo acc. How will i be able to send mails to all acc?
Hello, do you know the algorithm how to send email with Imge in spesific size ,, I mean while Image size > 2MB then the response is “Sorry, your image are to large / more than 2 MB” thank you. 🙂
Great Post with simple explanations. Thank you!!
Hi Pankaj,
How to add Test Results Status in the email body part or testng report.
Hi Pankaj,
In my piece of code I am using this line.
javax.mail.Transport.send(message);
The line is getting executed without any errors and emails are not sent, whereas in another class same piece of code exists but emails are sent appropriately.
Both the class are using the same method with same line of code [I have duplicated the method in these separate classes], yet it fails to send without errors.
Any insight is really appreciated.
Are you running both the classes on the same system, same user?
I have to send mass mail at once with addressing each mail recipient(“Hi username”) at other end except this rest all content is same . how i can do this. if i put in loop then it will create overehead on server.
is there any way to send an attachment more than 25 mb using the google smtp ?
Using the ssis package integration SCRIPT TASK
I can’t understand what is EmailUtil… ’cause without it my code doesn’t work
thank a lot
Pankaj, thank you so much!
I’ve been working on sending email for two days with no success, then found your post – now working perfectly.
Very well written post.
Need some thing which can send mail with an attachment.. any samples pls share
Nice tutorial, is there a way to send the email to multiple recipients?
Nice article
Hi Sir ,
Getting this error please help me
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via
534-5.7.14 your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 w81-v6sm29567346pfk.92 – gsmtp
I want to pull data from db to mail body. It should be like table (like we used to store data in excel). How can I convert my db data to table format in mail body?
I am receiving Exception in thread “main” java.lang.NoClassDefFoundError: javax/mail/Transport.
I am using maven, tried deleting the jar from repository, reinstalling them. Updated project many time. Refreshed the project.
I have no idea why JVM can’t find the Transport.class, even the jar containing this class in under the classpath.
Any suggestions please.
Transport.send(message) not working and also catch shown Message Exception while sending mail using jsp program
My question is : How can I enable any user in my application spring boot to send email to others using a form and the receiver will receive only the name and email of the user and not my Gmail email .
hello sir
i tring to make a leave application online for this i m using jsp and mysql front end is ready but my back end is not responding.and one more thing i wnt to addd in this program it sends notification or a mail to the corresponding email id plz help me to do so.
and thanks in advance plz send me the code to do so on my email.id deepikaporia@gmail.com
How to check attachment’s size for not allowing more than 25 mb.
Thanks for the tutorial, i want to ask but i have a bad english , sorry. When i sent an attachment file, why it goes multiples files , but i only sent a single files, thank you
Hello, thanks for the tutorial. Sorry if i have a bad english. When i sent an attachment file, why it goes multiples file ? But i only sent a single files, thanks a lot
hi ,i need a help i am fresher just started working and i have used ur javamil program its working nice, tq
my question is here we giving email static but i want to send to mail to mailid which is stored in database!!
Thankuu so much!!!
Message is ready
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:724)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at com.focuslogic.util.EmailUtil.sendEmail(EmailUtil.java:52)
at com.focuslogic.mail.TLSEmail.main(TLSEmail.java:40)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:598)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:525)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2059)
… 8 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
… 18 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
… 24 more
Am getting this error while running
remove/ disable starttsl.enable
Diasable the fire Wall in your system and also disable any antivirus software.
hello sir , i need to send the arrays of data to the email , how to do this? please help me….its an urgent…..please mail me a sample in poudelas.123@gmail.com
Hi Pankaj,
I am really stuck with this email implementation, this program perfectly works with gmail server if I reduce the security level. But same propgram i am trying to use with my company’s mail server I am getting below exception. I tried writing power shell script to see if my credentials work or not and it successfully sent the email. It would be really great help if you help.
Can you think of anything need to taken care of in case we are using Java Email APIs?
DEBUG SMTP: trying to connect to host “smtp2.healthtronics.net”, port 587, isSSL true
javax.mail.MessagingException: Could not connect to SMTP host: smtp2.healthtronics.net, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
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 com.email.com.java.mail.EmailUtil.sendEmail(EmailUtil.java:46)
at com.email.com.java.mail.SSLEmail.main(SSLEmail.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:652)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:484)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:863)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
… 13 more
Process finished with exit code 0
hello bro
u should add the ssl key in the code becoz you are using ssl site
Hello Pankaj,
I use below code to send a mail via SMTP.
Properties props = new Properties();
//Properties props=System.getProperties();
props.put(“mail.smtp.user”, userName);
props.put(“mail.smtp.host”, host);
if(!””.equals(port))
props.put(“mail.smtp.port”, port);
if(!””.equals(starttls))
props.put(“mail.smtp.starttls.enable”,starttls);
props.put(“mail.smtp.auth”, auth);
// props.put(“mail.smtps.auth”, “true”);
if(debug){
props.put(“mail.smtp.debug”, “true”);
}else{
props.put(“mail.smtp.debug”, “false”);
}
if(!””.equals(port))
props.put(“mail.smtp.socketFactory.port”, port);
if(!””.equals(socketFactoryClass))
props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
if(!””.equals(fallback))
props.put(“mail.smtp.socketFactory.fallback”, fallback);
Authenticator authe = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“micros.testautomation@gmail.com”,”@lt12345″);
}
};
Session session = Session.getDefaultInstance(props, authe);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setSubject(subject);
//attachment start
// create the message part
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
//Create the body
BodyPart messageBodyTextPart = new MimeBodyPart();
String indexfile=ReportUtil.indexHtmlPath;
messageBodyTextPart.setFileName(indexfile);
DataSource indexsource = new FileDataSource(indexfile);
messageBodyTextPart.setDataHandler(new DataHandler(indexsource));
messageBodyTextPart.setDisposition(MimeBodyPart.INLINE);
messageBodyTextPart.setHeader(“Content-Type”, “text/html”);
// messageBodyTextPart.setText(text);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyTextPart);
// attachment ends
// Put parts in message
msg.setContent(multipart);
msg.setFrom(new InternetAddress(“micros.testautomation@gmail.com”));
for(int i=0;i<mailTo.length;i++){
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
}
// msg.setText(text);
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
I t is working fine without connecting any VPN. If I connect a CISCO VPN, I am not able to send a mail. See the error below.
Exception in thread "main" 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:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.micros.util.SendMail.sendMail(SendMail.java:148)
at com.micros.util.SendMail.execute(SendMail.java:29)
at com.micros.util.ReportUtil.main(ReportUtil.java:282)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:205)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
… 6 more
Please help me in this.Thanks in advance.
It looks like your VPN firewall is not allowing you to connect to GMail servers.
hi pankaj this woks absoutely fine but it is very slow it takes almost 20 seconds to receive the mail
Hi can you please suggest any idea? i am getting same issue… Email sending working fine in local network.. but not in VPN… and i turned off firewall in VPN.. still same problem
Hi,
I have developed email functionality in my application and I am getting “Connection Reset” error.
15:50:31,750 ERROR [stderr] (http-/127.0.0.1:8080-1) javax.mail.MessagingException: Exception reading response;
15:50:31,750 ERROR [stderr] (http-/127.0.0.1:8080-1) nested exception is:
15:50:31,750 ERROR [stderr] (http-/127.0.0.1:8080-1) java.net.SocketException: Connection reset
Can anyone help on this issue?
Thanks Ajay
Can you optimize this mail sending code with the help of multithreading??
Hi . Could you help my in some thing
I need a for smtp
(Implement a SMTP that retrieve mailbox using pop3 )
Hent ; multiple clients connect to on smtp server
Thanks
Very Nice Thanks
Hi
In my program java mail have seen from mail id. i did not need that from mail id ..how to set no reply mail id without our original mail id.
I am able to send an email but the attachment is not being sent as it should be, instead it is being printed in the subject, like this:
——=_Part_0_2060982148.1419892624070
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
This is message body…PFA
——=_Part_0_2060982148.1419892624070
Content-Type: text/plain; name=”\\manifest.txt”
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename=”\\manifest.txt”
Manifest-Version: 1.0….followed by the contents of manifest.txt file…
——=_Part_0_2060982148.1419892624070–
Any clue how to resolve this ?
Hi, I am trying to send an email from an java program to the ODC members. For that I need my company authentication. I have given the details they have asked but I don’t know the detail of service name. Kindly requesting you to give the detail of service name. So that I can proceed further.
hello sir ,
Sir i want send image in as a mail body using android ….
send “To” address may be gmail ,yahoo,outlook….
Why are we putting the properties above in the code:
Properties props = new Properties();
props.put(“mail.smtp.host”, “smtp.gmail.com”); //SMTP Host
props.put(“mail.smtp.socketFactory.port”, “465”); //SSL Port
props.put(“mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”); //SSL Factory Class
props.put(“mail.smtp.auth”, “true”); //Enabling SMTP Authentication
props.put(“mail.smtp.port”, “465”); //SMTP Port
where are we using it..?
Session session = Session.getInstance(props, auth);
Hi,
I am new to java, I am sending email using above code and facing error, can anybody tell me how to create javax.mail.Session object?
Thanks for such a useful and valuable article.
I wanted to know how to send an email with multiple attachments,should we use datasource multiple times or any other approach is there?
In above example to send image, we are attaching two files.
Hi Pankaj,
I went through your tutorial materials, even I am able to send the email successfully. But I have to incorporate the email delivery status whether the email has been sent successfully or not in the java code only, in other words we can say email is delivered or not so that I can pass that status to the other application.
Could you please let me know how I can apply such functionality? Although I have tried to implement such functionality using below approaches but nothing works for me.
1) smtpMsg.setNotifyOptions()
2) props.put(“mail.smtp.dsn.notify”, “SUCCESS,FAILURE,DELAY ORCPT=rfc822;XYZ@gmail.com”);
Thanks in advance
Bhavishya
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 nj3sm8477842pdb.70 – gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at com.tcs.email.EmailUtil.sendEmail(EmailUtil.java:53)
at com.tcs.email.SSLEmail.main(SSLEmail.java:40)
I am getting this error.Please advice
Why don’t you try reading the error message and doing what it says?
— Please log in via your web browser and then try again.
Gmail has some security features that have to be enabled/disabled 1 – Inside your gmail account go to Settings > Forwarding and POP/IMAP and enable the protocols(s) that you wish to use
2 – Enable access of less secure apps https://www.google.com/settings/security/lesssecureapps
i tried this but got exception
INFO: Server startup in 3286 ms
TLSEmail Start
Message is ready
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 z15sm4277784pdi.6 – gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at userdata.EmailUtil.sendEmail(EmailUtil.java:44)
at userdata.SendEmail.mailSending(SendEmail.java:53)
at org.apache.jsp.JSP.EmailVerifyJSP_jsp._jspService(EmailVerifyJSP_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
TLSEmail Start
Message is ready
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 m2sm6651605pdl.14 – gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at userdata.EmailUtil.sendEmail(EmailUtil.java:44)
at userdata.SendEmail.mailSending(SendEmail.java:53)
at org.apache.jsp.JSP.EmailVerifyJSP_jsp._jspService(EmailVerifyJSP_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
how can i resolve?? pls help me….
Sir,
In my project i have to send a mail when ever there is a work status changes.
I exectuted above mentioned program successfully. Even in the real time applications (spring mvc)
do we have to do the same??? Will expose the smtp server details like above? or any other way?
Could you please suggest how to implement this?
Thanks,
Mahesh
You can wrap the sending email logic in a web service and call it from your services, this will create orchestration and separation of concerns.
Hi Pankaj,
I went through your tutorial materials, even I am able to send the email successfully. But I have to incorporate the email delivery status whether the email has been sent successfully or not in the java code only, in other words we can say email is delivered or not so that I can pass that status to the other application.
Could you please let me know how I can apply such functionality? Although I have tried to implement such functionality using below approaches but nothing works for me.
1) smtpMsg.setNotifyOptions()
2) props.put(“mail.smtp.dsn.notify”, “SUCCESS,FAILURE,DELAY ORCPT=rfc822;XYZ@gmail.com”);
hi you had a solution please let me known
I have tried SSL and TLS both examples separately but it always give me this error :
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/bin/answer.py?answer=14257 us3sm3857298lbc.24 – gsmtp
Whereas i can login with same username and password through webpage GUI.
Can you please tell me where is the problem and how to solve it ?
can we send more than one email address?
Thanks in advance.
Hi Pankaj,
When I use these codes in jsp I get the error Duplicate local variable session in line Session session = Session.getInstance(props, auth); here is the complete implementation,
Looking forward to hearing from you soon.
Thanks & Regards,
RJ.
Hi Ratan,
you get the error because in JSP there is already a variable named session. you should change the name of your variable to something else.
Actually you shouldn’t just paste this code in your JSP. Refactor it and write a function that you will just call in your jsp with parameters.
Regars,
Likide
The coding works perfect in java ,however I want to do this in JSP .
When I copy and paste these codes in JSP within
I get one error duplicate local variable session in the line
Session session = Session.getInstance(props, auth);
Hi,
How to take email id and name of the person from HTML form and then send mail to multiple email accounts with Person’s name and other details as message body using JSP.
Regards,
RJ
Thanks Pankaj, It worked for me. Nice Post.
i am a beginner…. i have successfully built the basic mail reading program in netbeans…
i have an error….
run:
Exception in thread “main” java.lang.NullPointerException
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:673)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:633)
at La.main(La.java:49)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
plz give me solution…. its urgent….
Thank you very much!
Hi, I want to export the outlook mail to oracle database. That is want to store all mails along with from/ subject/ content/ attachments and image.
Pls help
You have covered all the necessary details of java mail.
I offer my appreciation for your great work. !!
Hello Pankaj,
Very nice work. Very nice tutorial with all options.
Is it possible to store email attachment on local machine from Microsoft Outlook 2010 using Java?
Please post any example if you have. I would love to see that.
Thanks a lot Pankaj.
Raj
Hi Pankaj,
I’m getting following exception while sending the mail:
java.lang.RuntimeException: javax.mail.MessagingException: Can’t send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I have included the cacerts file too in the jre\lib\security folder. What could I be missing?
Appreciate your time.
Thanks
Ravi
Hello Ravi. . I am facing the same problem. Did you get the solution??
Can you guys try the solution provided here: https://stackoverflow.com/questions/20122099/error-in-javamail-pkix-path-building-failed-unable-to-find-valid-certification
below is the working code :
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class emailNotification {
public static void main(String[] args) throws Exception {
final String username = “valid gmail user name”;
final String password = “valid password”;
Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.starttls.enable”, “true”);
props.put(“mail.smtp.host”, “smtp.gmail.com”);
props.put(“mail.smtp.port”, “587”);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username,
password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(
” from : maild id e.g. abc@gmail.com“));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(“to : maild id e.g. xyz@gmail.com“));
message.setSubject(“subject line”);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart
.setText(“message body : compose your text here”);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
String filename = “E:/FOLDER_1/INNER_FOLDER/INNERNOST_FOLDER/EXISTING_FILE_NAME.filetype”;
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println(“Done”);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
how do i read the content of a message, download any image and or attachments? Thanks in advance
Thanks for the very useful tutorial. I cannot send messages, due to unidentified mail server. However, i can read all access gmail account. Kindly advice on setting the required outgoing mail server. Thanks
hi pankaj sir,
i read u r gmail article very nice. i want to the help regarding get the URL name of dynamically open different browser. how u get all open browser URL with different tabs. in jsp servelets code.
so sir plz provide help me..
Hi Sir,
i read u r article very nice. i want the code for getting multiple browser URL name in java servlets.how u get the name of url with different browser and different tabs..so plz help me..
Hi Pankaj,
Im trying to implement your example, but i’m getting this error from gmail:
Application/device sign-in attempt (prevented)
and after doing a little research, gmail said that they highly recommend that all senders using short keys switch to RSA keys that are at least 1024-bits long.
how can this implementation could be accomplish with your examples?
thanks in adavance
Hi Nidhin
Thanks for your reply.
From a button click in a page it will open my gmail account in a browser tab and successfully signup.
Is it possible to do from my java application. ?
If possible please help me.
I am waiting for your reply
Once again thanks for your reply.
Hi Nidhin
Thanks for your reply. Now i can access my account.
From a button click in a page it will open my gmail account in browser tab and sign up successfully..
Is it possible to Do.
If possible please help. I am waiting for your reply.
Once again thanks for your reply.
Hi this is working fine in my project. I have another requirement, i want to open my own gmail account from my java application. is it possible to open a gmail account in java from application. If possible please give me an example with code.
Please give me a solution. I am waiting for your answer.
Properties props = new Properties();
props.setProperty(“mail.store.protocol”, “imaps”);
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(“emailid”,”password”);
}
});
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect(“imap.gmail.com”, “emailid”, “password”);
Folder inbox = store.getFolder(“INBOX”);
inbox.open(Folder.READ_WRITE);
//Message msg = inbox.getMessage(inbox.getMessageCount());
/* Get the messages which is unread in the Inbox*/
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
System.out.println(“Unread e-mail count : “+ messages.length);
Nice one!! It works.
Just have a question though. How can I hide my from email address and use a different one instead of saying the email was sent from gmail?
I am not sure if it’s possible, I have not tried it.
Thanks. A very helpful article!
Thanks pankaj
Its really working ….nice Article…
Hi,
i am facing one problem to send email with attachment. one application will send to,cc,body and also attached file i need to handle what ever type of file they will send to me i need to attach and send the mail.
the incoming file will be .pdf,.txt,.png,.jpg
Thanks Pankaj for your all such helpfull articles.
is it possible to send email through gmail without authentication
i dont think so…
Tanks you, Pankay! Very good post.
Hi pankaj,
I have a requirement to attach multiple files in outlook as items that is like i need to add multiple emails into single Email.Please tell me the way to do that.
Thankyou.
Hi,
I How to send mail to multiple user ??
Use toEmail to have comma separated email ids.
Hi Pankaj,
I need a favor from you.. Say for example i have multiple images in html content.
How do i add images in that instance.
Please help me.
Thanks in advance
Naresh T
You will use the same logic for each of the image. Note that
messageBodyPart.setHeader("Content-ID", "image_id");
is only for the image. When you will add another image, just make this call again and use the cid value in the HTML code.Hi Pankaj,
Thanks for the reply.
I dont want to attach the images and refer from the CID.
I want to use a basic html content to send a mail so that i can refer the images from my webserver.
Do you have any idea. How to do that.
Coz i have done a POC. Thats absolutely working in OUTLOOK and YAHOO but not in GMAIL 🙁
Please help me.
Thanks in advance.
If its working in Outlook and Yahoo but not in GMail, it means that your code is fine but GMail is blocking the images. Do you see any option such as display external images etc.
how it will work in outlook i got the error:
5th=======> send Email
com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at EmailUtil.sendEmail(EmailUtil.java:60)
at TLSEmail.main(TLSEmail.java:52)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
… 8 more
how did you solved this.please help me.
Thank you pankaj, very Important post I really like your posts.
I am new in software developer. This post is very much helpful to me. Thanks for this nice post.
If i send free sms to mobile phone (like Way2sms) through java programming without using third party sms gateway. Because they provided some amount money.
Hello Pankaj.
This is very nice article ..it is very help full for me.Thanks for posting..!!!