Send Email Using Gmail SMTP in Java (Jakarta Mail, App Password)

Send email using Gmail SMTP in Java with Jakarta Mail. Ports 587 and 465, App Passwords, OAuth 2.0, HTML and attachments, tests and common errors.

Flow of an email from a Java app through a Jakarta Mail Session and Transport to smtp.gmail.com on port 587 with STARTTLS and App Password login, then to the recipient inbox

To send email using Gmail SMTP in Java, we connect Jakarta Mail to smtp.gmail.com on port 587 with STARTTLS (or port 465 with SSL) and log in with the Gmail address and a 16-character App Password, because Gmail no longer accepts the normal account password from apps. With OAuth 2.0, the app sends an access token instead of the App Password.

We use Gmail SMTP for low-volume mail from small apps, scripts and internal tools, such as password reset links, nightly job reports or a weekly digest for a family meal planner. The code in this article targets Jakarta Mail 2.1 with the Angus Mail 2.0.5 implementation on Java 25.

The following example sends one plain text email over port 587. It reads the credentials from environment variables, so no password ends up in the source code.

static void sendGmail(String to, String subject, String text) throws MessagingException {
    String username = System.getenv("GMAIL_USERNAME");          // anna@gmail.com
    String appPassword = System.getenv("GMAIL_APP_PASSWORD");   // 16-character App Password

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");             // upgrade to TLS
    props.put("mail.smtp.starttls.required", "true");           // fail instead of sending in clear text

    Session session = Session.getInstance(props);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(username));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subject, "UTF-8");
    message.setText(text, "UTF-8");

    Transport.send(message, username, appPassword);             // connect, log in, send, close
}

Notice that Transport.send() takes the user name and password itself, so we need no Authenticator class. We start with the Gmail settings and the App Password, and move on to the Maven setup, SSL on port 465, HTML mail with attachments, OAuth 2.0, a local test server and the errors Gmail returns most often.

1. Gmail SMTP Server Settings

Gmail accepts mail from any SMTP client that encrypts the connection and logs in. The encryption is either STARTTLS, where the client connects in plain text on port 587 and upgrades the connection to TLS, or implicit SSL/TLS on port 465, where the connection is encrypted from the first byte. Both are equally secure once the session is running, and port 587 is the common default.

Flow of an email from a Java app through a Jakarta Mail Session and Transport to smtp.gmail.com on port 587 with STARTTLS and App Password login, then to the recipient inbox
Jakarta Mail opens one connection to smtp.gmail.com, upgrades it to TLS, logs in with the App Password and hands the message to Gmail for delivery

The values we put into the Properties object are always the same few.

SettingValue
Hostsmtp.gmail.com
Port with STARTTLS587 (mail.smtp.starttls.enable=true)
Port with implicit SSL/TLS465 (mail.smtp.ssl.enable=true)
User nameThe full Gmail address, e.g. anna@gmail.com
PasswordA 16-character App Password, or an OAuth 2.0 access token with XOAUTH2
Sending limit (personal account)About 500 emails per day; Google Workspace accounts get 2,000

1.1. Creating a Gmail App Password

An App Password is a 16-character code that lets one app log in to a Google account without the normal password. Google offers it only when 2-Step Verification is on, and it revokes all App Passwords when we change the account password.

  1. Turn on 2-Step Verification in the Google account under Security.
  2. Open myaccount.google.com/apppasswords, enter a name such as meal-planner and click Create.
  3. Copy the 16 characters (Google shows them in four groups) and store them in an environment variable or a secret store, never in the code or in Git.

The App Password page is missing for work and school accounts, for accounts with Advanced Protection and for accounts that use only security keys for 2-Step Verification. These accounts need OAuth 2.0, which we cover in section 6. Google turned off the old “Less secure app access” switch in 2022, so tutorials that tell us to enable it no longer work.

2. Adding Jakarta Mail to the Project

Jakarta Mail is the API (package jakarta.mail), and Angus Mail is the Eclipse implementation that contains the SMTP code. The angus-mail artifact pulls in the API and the activation framework, so one dependency is enough.

<dependency>
    <groupId>org.eclipse.angus</groupId>
    <artifactId>angus-mail</artifactId>
    <version>2.0.5</version>
</dependency>

With Gradle, the same coordinates go into build.gradle.

implementation 'org.eclipse.angus:angus-mail:2.0.5'

Older tutorials use javax.mail imports and the com.sun.mail:javax.mail artifact from JavaMail 1.6. That code still works on old projects, but Jakarta Mail 2.x renamed every package to jakarta.mail, and Spring Boot 3 and later expect the new names.

LibraryPackageMaven artifactStatus
JavaMail 1.6javax.mailcom.sun.mail:javax.mailLegacy, no new features
Jakarta Mail 2.1 + Angus Mail 2.0jakarta.mailorg.eclipse.angus:angus-mailCurrent

Mixing a javax.mail jar with jakarta.mail imports does not work, because the two are separate APIs with different class names. If an old library on the classpath still needs javax.mail, it keeps its own jar and our code keeps the Jakarta one.

3. Send Email Using Gmail SMTP Over TLS (Port 587)

A meal-planning app sends every user a shopping list on Friday evening. The code splits that job into three parts. One method builds the Session with the Gmail settings, one builds the message, and the last step sends it, which keeps the first two testable without a network.

3.1. Configuring the Mail Session

A Session holds the SMTP properties and creates messages and transports. Creating it opens no connection. The property mail.smtp.starttls.required makes the send fail when the server does not offer STARTTLS, instead of sending the password over an unencrypted connection.

static Session gmailSession(boolean implicitSsl) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.connectiontimeout", "10000");
    props.put("mail.smtp.timeout", "10000");
    if (implicitSsl) {
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.ssl.enable", "true");
    } else {
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
    }
    return Session.getInstance(props);
}
Session tls = gmailSession(false);
String host = tls.getProperty("mail.smtp.host");                 // "smtp.gmail.com"
String port = tls.getProperty("mail.smtp.port");                 // "587"
String starttls = tls.getProperty("mail.smtp.starttls.required"); // "true"

The two timeouts are in milliseconds. Without them, a blocked port makes Transport.send() wait for the operating system timeout, which can take minutes and hold a request thread the whole time.

3.2. Building the Message

A MimeMessage carries the headers and the body. The method InternetAddress.parse() accepts a comma-separated list and throws AddressException for a malformed address, so bad input fails before any connection is made.

static MimeMessage shoppingListMail(Session session, String from, String to, List<String> items) throws MessagingException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject("Shopping list for Saturday", "UTF-8");
    message.setText("Please buy: " + String.join(", ", items), "UTF-8");
    message.setSentDate(new Date());
    return message;
}
Session session = gmailSession(false);
MimeMessage mail = shoppingListMail(session, "anna@gmail.com", "bob@example.com", List.of("milk", "eggs"));
String subject = mail.getSubject();                              // "Shopping list for Saturday"
String body = (String) mail.getContent();                        // "Please buy: milk, eggs"
Address[] to = mail.getRecipients(Message.RecipientType.TO);     // [bob@example.com]
Address[] bad = InternetAddress.parse("bob@@example");           // AddressException

We pass “UTF-8” to setSubject() and setText(), so names and dishes with accents arrive intact. Without a charset, Jakarta Mail takes the one from the mail.mime.charset property or the JVM default, which differs between machines on older JDKs.

3.3. Sending the Message

The static method Transport.send(message, user, password) connects to the host from the session, logs in, sends the message to all recipients and closes the connection. It throws AuthenticationFailedException when Gmail rejects the login, SendFailedException when an address is refused, and MessagingException for other SMTP errors.

static void sendShoppingList(String to, List<String> items) throws MessagingException {
    String username = System.getenv("GMAIL_USERNAME");
    String appPassword = System.getenv("GMAIL_APP_PASSWORD");
    if (username == null || appPassword == null) {
        throw new IllegalStateException("Set GMAIL_USERNAME and GMAIL_APP_PASSWORD");
    }
    Session session = gmailSession(false);
    MimeMessage message = shoppingListMail(session, username, to, items);
    Transport.send(message, username, appPassword);
}

We set the two variables in the shell (or in the run configuration of the IDE) before starting the app. Read more about the options in Java system properties if the app gets its settings from -D flags instead.

export GMAIL_USERNAME=anna@gmail.com
export GMAIL_APP_PASSWORD=abcdefghijklmnop
java -jar meal-planner.jar

The From address must be the Gmail account we log in with, or an alias added under “Send mail as” in the Gmail settings. Gmail rewrites any other From address to the account address.

4. Using SSL on Port 465

Port 465 uses implicit TLS, where the client starts the TLS handshake right after the TCP connection. We use it when a firewall blocks 587 or when a hosting provider asks for it. In the session from section 3, the implicitSsl flag switches the two properties.

Session ssl = gmailSession(true);
String sslPort = ssl.getProperty("mail.smtp.port");              // "465"
String sslOn = ssl.getProperty("mail.smtp.ssl.enable");          // "true"
String noStarttls = ssl.getProperty("mail.smtp.starttls.enable"); // null

Many old examples set mail.smtp.socketFactory.class to javax.net.ssl.SSLSocketFactory for port 465. The property mail.smtp.ssl.enable replaces that setup in Angus Mail, so the old socket factory properties can go.

Port 587Port 465
Encryption startsAfter the STARTTLS commandAt connect time
Propertymail.smtp.starttls.enable=truemail.smtp.ssl.enable=true
Typical error when mixed upCould not convert socket to TLS or a read timeoutUnrecognized SSL message or a read timeout

5. Sending HTML Email With an Attachment

An email with formatted text and a file is a MimeMultipart, a container of body parts. The first part holds the HTML, and every attachment is another MimeBodyPart. In the meal planner, the shopping list goes out as an HTML table with a CSV file of the same items attached.

static MimeMessage htmlListMail(Session session, String from, String to, Path csvFile) throws MessagingException, IOException {
    MimeBodyPart html = new MimeBodyPart();
    html.setText("<h2>Shopping list</h2><ul><li>milk</li><li>eggs</li></ul>", "UTF-8", "html");

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.attachFile(csvFile.toFile());

    MimeMultipart multipart = new MimeMultipart();
    multipart.addBodyPart(html);
    multipart.addBodyPart(attachment);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject("Shopping list with CSV", "UTF-8");
    message.setContent(multipart);
    message.saveChanges();
    return message;
}
Path csv = Files.createTempDirectory("mail").resolve("shopping-list.csv");
Files.writeString(csv, "item,qty\nmilk,2\neggs,12\n");
MimeMessage htmlMail = htmlListMail(gmailSession(false), "anna@gmail.com", "bob@example.com", csv);
MimeMultipart parts = (MimeMultipart) htmlMail.getContent();
int partCount = parts.getCount();                                // 2
String htmlType = parts.getBodyPart(0).getContentType();         // "text/html; charset=UTF-8"
String fileName = parts.getBodyPart(1).getFileName();            // "shopping-list.csv"

The three-argument setText(text, charset, “html”) sets the content type to text/html. The method attachFile() reads the file when the message is written, so the file must still exist at send time. For a file we hold only in memory, we pass a jakarta.mail.util.ByteArrayDataSource to setDataHandler() instead.

Mail clients that block HTML show nothing useful from an HTML-only message. For newsletters, we wrap a plain text part and an HTML part in a new MimeMultipart(“alternative”), and the client picks the version it can show.

6. Sending Gmail Email With OAuth 2.0 (XOAUTH2)

OAuth 2.0 replaces the App Password with a short-lived access token that Google issues for the scope https://mail.google.com/. We need it for Google Workspace accounts where the admin has turned off App Passwords, and it is the better choice for any app that sends mail on behalf of other users. Angus Mail supports the XOAUTH2 mechanism without extra libraries.

static void sendWithOAuth(MimeMessage message, String username, String accessToken) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.auth.mechanisms", "XOAUTH2");

    Session session = Session.getInstance(props);
    try (Transport transport = session.getTransport("smtp")) {
        transport.connect(username, accessToken);              // token in place of the password
        transport.sendMessage(message, message.getAllRecipients());
    }
}

The token goes into the password parameter as it is, without Base64 encoding. Access tokens expire after about an hour, so the app keeps the long-lived refresh token from the first user consent and asks Google for a new access token before each batch, for example with the Google Auth Library for Java. The client ID and secret come from an OAuth client created in the Google Cloud console.

A Transport opened this way also lets us send many messages over one connection. That is faster than calling the static Transport.send() in a loop, which opens and closes a connection for every message.

7. Testing Email Code Without Gmail

Unit tests must not send real mail. GreenMail 2.1 starts an SMTP server inside the test on port 3025 and keeps every received message in memory, so the test can read the subject and body back. The same shoppingListMail() method from section 3 works unchanged, and only the host and port differ.

GreenMail mailServer = new GreenMail(ServerSetupTest.SMTP);
mailServer.setUser("anna@example.com", "anna", "secret");
mailServer.start();

Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "3025");
props.put("mail.smtp.auth", "true");
Session testSession = Session.getInstance(props);
MimeMessage sent = shoppingListMail(testSession, "anna@example.com", "bob@example.com", List.of("rice"));
Transport.send(sent, "anna", "secret");

MimeMessage[] received = mailServer.getReceivedMessages();
int count = received.length;                                     // 1
String gotSubject = received[0].getSubject();                    // "Shopping list for Saturday"
String gotTo = received[0].getHeader("To", ",");                 // "bob@example.com"
mailServer.stop();

For JUnit 5 tests, the module com.icegreen:greenmail-junit5 adds a GreenMailExtension that starts and stops the server around each test. In Spring Boot, the same idea works with the Spring Boot mail starter by pointing spring.mail.host to localhost in the test profile.

8. Common Gmail SMTP Errors and Fixes

The first thing to turn on when a send fails is the session debug log. With session.setDebug(true), Jakarta Mail prints every SMTP command and reply to System.out, including the Gmail error code. The trimmed log comes from the GreenMail run in section 7.

DEBUG: setDebug: Jakarta Mail version 2.1.5
DEBUG SMTP: trying to connect to host "localhost", port 3025, isSSL false
220 /127.0.0.1 GreenMail SMTP Service v2.1.14 ready
EHLO localhost
250-/127.0.0.1
250-AUTH PLAIN LOGIN XOAUTH2
250 SMTPUTF8
DEBUG SMTP: protocolConnect login, host=localhost, user=anna, password=<non-null>
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN succeeded
MAIL FROM:<anna@example.com>
250 OK
RCPT TO:<bob@example.com>
250 OK
DATA
354 Start mail input; end with <CRLF>.<CRLF>
...
250 OK
DEBUG SMTP: message successfully delivered to mail server
QUIT

The SMTP reply code in the log points to the cause. Six error messages cover the usual Gmail failures, and each one has a known cause and fix.

Error messageCauseFix
534-5.7.9 Application-specific password required2-Step Verification is on, and the code sends the normal account passwordCreate an App Password and use it as the password
535-5.7.8 Username and Password not acceptedWrong user name or App Password, a revoked App Password, or spaces copied with itUse the full Gmail address, create a new App Password and remove the spaces
530-5.7.0 Must issue a STARTTLS command firstPort 587 without mail.smtp.starttls.enable=trueAdd the STARTTLS property, or switch to port 465 with SSL
MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 587A firewall, proxy or cloud provider blocks outgoing SMTPTry port 465, or use the provider’s mail relay
PKIX path building failedA corporate proxy or antivirus replaces the TLS certificateImport the proxy’s root certificate into the JDK trust store
NoClassDefFoundError: javax/mail/…A javax.mail import with only the Jakarta jar, or the reverseUse one namespace, as shown in section 2

Gmail answers a burst of mail from a new account or a script with 550 5.4.5 Daily user sending limit exceeded. The limit resets after 24 hours, and an app that needs more volume belongs on a transactional email service, not on a personal Gmail account.

9. Gmail SMTP in Java FAQs

Passwords, ports, limits and Spring Boot are the recurring topics in Gmail SMTP threads on Stack Overflow.

9.1. Can we use the normal Gmail password in Java code?

No. Gmail rejects the normal account password from SMTP clients. Personal accounts use an App Password, which needs 2-Step Verification, and Google Workspace accounts use OAuth 2.0 or an App Password if the admin allows it.

9.2. Which port should we use for Gmail SMTP, 465 or 587?

Either one works. Port 587 with STARTTLS is the usual default, and port 465 with mail.smtp.ssl.enable=true helps when a network blocks 587. Port 25 is blocked for outgoing mail on many home and cloud networks.

9.3. Is sending email through Gmail SMTP free?

Yes, for a personal account, within the Gmail sending limits of about 500 emails per day. Bulk or marketing mail breaks the Gmail program policies and gets the account blocked, so it needs an email service built for volume.

9.4. How do we send the same email to several people?

We pass a comma-separated string to InternetAddress.parse(), or call setRecipients() once each for TO, CC and BCC. Gmail counts every recipient toward the daily limit.

MimeMessage group = new MimeMessage(Session.getInstance(new Properties()));
group.setRecipients(Message.RecipientType.TO, InternetAddress.parse("bob@example.com, carol@example.com"));
group.setRecipients(Message.RecipientType.BCC, InternetAddress.parse("dan@example.com"));
int recipients = group.getAllRecipients().length;               // 3

9.5. How do we send Gmail email from Spring Boot?

We add spring-boot-starter-mail and set spring.mail.host=smtp.gmail.com, spring.mail.port=587, the user name, the App Password and spring.mail.properties.mail.smtp.starttls.enable=true. Spring Boot builds the same Jakarta Mail session behind a JavaMailSender bean.

10. Conclusion

Sending email through Gmail from Java needs three things. These are the Angus Mail dependency, a session that points to smtp.gmail.com on port 587 with STARTTLS (or 465 with SSL), and a login with an App Password or an OAuth 2.0 token.

Keeping the session, the message and the send step in separate methods lets us test the first two without a network and run the whole flow against GreenMail. When Gmail refuses a message, the debug log and the SMTP code in the error tell us whether the problem is the password, the port or the network. The same split between building a request and sending it works for any network client, and the Java tutorial covers the language basics behind it, from exceptions to records.

11. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. Hello everyone, could you pls help to send an email using the above code. I am unable to send emails through the above code. Getting following error message. Thanks
    Exception in thread “main” javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at


    534 5.7.9 https://support.google.com/accounts/answer/185833?visit_id=638615011882718410-3790294334&p=InvalidSecondFactor&rd=1 z13sm22908980pjq.0 - gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:947)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:858)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:762)
    at javax.mail.Service.connect(Service.java:342)
    at javax.mail.Service.connect(Service.java:222)
    at com.example.demo.DemoApplication.sendEmail(DemoApplication.java:87)
    at com.example.demo.DemoApplication.main(DemoApplication.java:27)

    • If you have enabled 2-factor authentication on your Google account you can’t use your regular password to access Gmail programmatically. You need to generate an app-specific password and use that in place of your actual password.

      Steps:

      Log in to your Google account Go to My Account > Sign-in & Security > App Passwords (Sign in again to confirm it’s you) Scroll down to Select App (in the Password & sign-in method box) and choose Other (custom name) Give this app password a name, e.g. “mailer” Choose to Generate Copy the long generated password and paste it into your code instead of your actual Gmail password.

      Reference: SO Thread

  2. someone help me i cannot resolve this exception as i’m new to this mail service and just copied the code and run it

  3. You need to connect to your network team regarding this they will give u access on your system to access the there host without any network restrictions.

  4. Hi authentication is happening if i run code from my desktop, if i run the same code in server authentication doesn’t happen , even if i send wrong password authentication is success and messages are getting delivered.

    final String username=rb.getString(“username”);
    final String password=rb.getString(“password”);
    final String host =rb.getString(“host”);
    final String port =rb.getString(“port”);
    Properties props = new Properties();
    // props.put(“mail.smtp.starttls.enable”, “false”);
    props.put(“mail.smtp.host”, host);
    props.put(“mail.smtp.user”, username);
    props.put(“mail.smtp.password”, password);
    props.put(“mail.smtp.port”, port);
    props.put(“mail.smtp.auth”, “true”);
    // props.put(“mail.smtp.auth.ntlm.disable”, “false”);
    // props.put(“mail.smtp.auth.mechanisms”, “NTLM”);
    // props.put(“mail.smtp.auth.ntlm.domain”, “testsmtp.com”);
    // props.put(“mail.smtp.ssl.trust”, “false”);
    System.out.println(“properties loaded “);
    Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
    }
    });

    // Session session = Session.getInstance(props);

    try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(rb.getString(“from”)));

    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(rb.getString(“to”)));

    message.setSubject(rb.getString(“subject”));
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(rb.getString(“text”));

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    String filename = rb.getString(“filename”);
    System.out.println(“file is ” + filename);
    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    // System.out.println(session.getTransport(“smtp”));
    // Transport transport = session.getTransport(“smtp”);

    // transport.connect(username, password);

    Transport.send(message);

    System.out.println(“Message sent successfully”);
    // transport.close();

    } catch (MessagingException e) {

    System.out.println(“Unable to send message ” + e.getMessage() );

  5. Thanks a ton Lokesh and friends who shared…You have helped me a lot. i am very Thankful for this code…God Bless you with great life a ahead

  6. I refered above code…but it is giving me following error :
    i changed name of class as SedEmail2.java

    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    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:291)
    at javax.mail.Service.connect(Service.java:172)
    at demo.Emailsend2.sendEmail(Emailsend2.java:74)
    at demo.Emailsend2.main(Emailsend2.java:27)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
    … 5 more
    Java Result: 1

  7. Sir,
    I updated my code.after updation eject error mention below.

    Thanks

    run:
    DEBUG: setDebug: JavaMail version 1.5.1
    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 “host”, port 25, isSSL false
    com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: host, 25; timeout -1;
    nested exception is:
    java.net.UnknownHostException: host
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1984)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at maina.MainA.sendMail(MainA.java:92)
    at maina.MainA.main(MainA.java:32)
    Caused by: java.net.UnknownHostException: host
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:158)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:154)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:380)
    at java.net.Socket.connect(Socket.java:569)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:569)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
    … 5 more
    BUILD SUCCESSFUL (total time: 2 seconds)

    My 32 line and 92 line Coding is:-

    32 line no.) MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
    “hi baba don’t send virus mails..”,
    “This is my style…of reply..If u send virus mails..”);

    92 line no.) msg.saveChanges();
    Transport transport = session.getTransport(“smtp”);
    transport.connect(host, userName, passWord);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    return true;
    }
    catch (Exception mex)
    {
    mex.printStackTrace();
    return false;
    }
    }

    • This error is thrown to indicate that the IP address of a host could not be determined.
      Find out the IP address of mail server i.e. “blr-outlook.ibm.com” and place that IP directly into “props.put(“mail.smtp.host”, host);”

      • Hi,
        Sorry to say sir,but message does not send in email ids.this code used in my personal machine but that is not even running.Please help me.I’ve used editor NetBeans 7.2.and i’m sending my debug after run.

        Thanks

        DEBUG: setDebug: JavaMail version 1.5.1
        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 “host”, port 25, isSSL false
        BUILD SUCCESSFUL (total time: 3 seconds)

        • This code works buddy. Just your machine is not able to resolve hostname. Open windows command prompt. Type “ping blr-outlook.ibm.com”. See if machine is reachable. I believe it will not and will timeout. If you can ping above from command prompt, then ONLY this code will run.

          • Hi,
            Finally my code is mention below.I don’t know why is not message send in email ids.
            Please check my code and find my mistake and correct them.I check “ping blr-outlook.ibm.com” in cmd.

            I saw in cmd after enter this blah blah..
            Thanks

            Pinging blr-outlook.ibm.com [11.201.51.251] with 32 bytes of data:
            Reply from 11.201.51.251: bytes=32 time=93ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=76ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=71ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=70ms TTL=119

            Ping statistics for 11.201.51.251:
            Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            Approximate round trip times in milli-seconds:
            Minimum = 70ms, Maximum = 93ms, Average = 77ms

            /*
            * To change this template, choose Tools | Templates
            * and open the template in the editor.
            */
            package maina;

            import javax.mail.*;
            import javax.mail.internet.*;
            import java.util.*;
            import javax.mail.Message;
            import javax.mail.PasswordAuthentication;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;

            public class MainA
            {
            String d_email = “KA11479G”,
            d_password = “kn@nov2014”,
            d_host = “blr-outlook.ibm.com”,
            d_port = “25”,
            m_to = “kapeesh.gupta@ibm.com”,
            m_subject = “Testing”,
            m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;

            public static void main(String[] args)throws Exception
            {
            String[] to={“kapeesh.gupta@ibm.com”};
            String[] cc={“debarka.sarkar@ibm.com”};
            String[] bcc={“amit.kudale@ibm.com”};
            //This is for google
            MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);
            }

            public synchronized static boolean sendMail(
            String userName, String passWord, String host,
            String port, String starttls, String auth,
            boolean debug, String socketFactoryClass, String fallback,
            String[] to, String[] cc, String[] bcc,
            String subject, String text)
            {
            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(“25″, port);
            }
            if(!””.equals(starttls)) {
            props.put(“mail.smtp.starttls.enable”,starttls);
            }
            props.put(“mail.smtp.auth”, auth);
            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);
            }
            try
            {
            Session smtpSession = Session.getDefaultInstance(props, null);
            smtpSession.setDebug(true);
            MimeMessage msg = new MimeMessage(smtpSession);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(“kapeesh.gupta@ibm.com”));
            for(int i=0;i<to.length;i++) {
            msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to[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.saveChanges();
            Transport transport = smtpSession.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
            }
            catch (Exception mex)
            {
            return false;
            }
            }
            }

          • I edited your code and below is working code. You must have also got an email. As I am not in IBM network, I still have used gmail SMTP. Please change SMTP Host, port, username, password in application and it should work. And from next time, please do not post any password in comments.

            import java.util.Properties;
            
            import javax.mail.Message;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;
            
            public class MainA 
            {
            	public static void main(String[] args) throws Exception {
            		String[] to = { &quot;kapeesh.gupta@ibm.com&quot; };
            		String[] cc = { &quot;debarka.sarkar@ibm.com&quot; };
            		String[] bcc ={ &quot;amit.kudale@ibm.com&quot; };
            		// This is for google
            		MainA.sendMail(&quot;lokeshgupta1981@gmail.com&quot;, &quot;**********&quot;, &quot;smtp.gmail.com&quot;, &quot;25&quot;, &quot;true&quot;, &quot;true&quot;,
            				true, &quot;javax.net.ssl.SSLSocketFactory&quot;, &quot;false&quot;, to, cc, bcc,
            				&quot;hi baba don’t send virus mails..&quot;,
            				&quot;This is my style…of reply..If u send virus mails..&quot;);
            	}
            
            	public synchronized static boolean sendMail(String userName,
            			String passWord, String host, String port, String starttls,
            			String auth, boolean debug, String socketFactoryClass,
            			String fallback, String[] to, String[] cc, String[] bcc,
            			String subject, String text) {
            		Properties props = new Properties();
            		props.put(&quot;mail.smtp.user&quot;, userName);
            		props.put(&quot;mail.smtp.host&quot;, host);
            		props.put(&quot;port&quot;, port);
            		props.put(&quot;mail.smtp.starttls.enable&quot;, starttls);
            		props.put(&quot;mail.smtp.auth&quot;, auth);
            		if (debug) {
            			props.put(&quot;mail.smtp.debug&quot;, &quot;true&quot;);
            		} else {
            			props.put(&quot;mail.smtp.debug&quot;, &quot;false&quot;);
            		}
            		try {
            			Session smtpSession = Session.getDefaultInstance(props, null);
            			smtpSession.setDebug(true);
            			MimeMessage msg = new MimeMessage(smtpSession);
            			msg.setText(text);
            			msg.setSubject(subject);
            			msg.setFrom(new InternetAddress(&quot;lokeshgupta1981@gmail.com&quot;));
            			for (int i = 0; i &lt; to.length; i++) {
            				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
            						to[i]));
            			}
            			for (int i = 0; i &lt; cc.length; i++) {
            				msg.addRecipient(Message.RecipientType.CC, new InternetAddress(
            						cc[i]));
            			}
            			for (int i = 0; i &lt; bcc.length; i++) {
            				msg.addRecipient(Message.RecipientType.BCC,
            						new InternetAddress(bcc[i]));
            			}
            			msg.saveChanges();
            			Transport transport = smtpSession.getTransport(&quot;smtp&quot;);
            			transport.connect(host, userName, passWord);
            			transport.sendMessage(msg, msg.getAllRecipients());
            			transport.close();
            			return true;
            		} catch (Exception mex) {
            			mex.printStackTrace();
            			System.out.println(mex.getLocalizedMessage());
            			return false;
            		}
            	}
            }
            

            Output:

            DEBUG: setDebug: JavaMail version 1.5.2
            DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
            DEBUG SMTP: useEhlo true, useAuth true
            DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false
            220 mx.google.com ESMTP wk2sm5328789pac.12 – gsmtp
            DEBUG SMTP: connected to host “smtp.gmail.com”, port: 25

            EHLO 192.168.2.6
            250-mx.google.com at your service, [14.102.107.130]
            250-SIZE 35882577
            250-8BITMIME
            250-STARTTLS
            250-ENHANCEDSTATUSCODES
            250-PIPELINING
            250-CHUNKING
            250 SMTPUTF8
            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 SMTP: Found extension “PIPELINING”, arg “”
            DEBUG SMTP: Found extension “CHUNKING”, arg “”
            DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
            STARTTLS
            220 2.0.0 Ready to start TLS
            EHLO 192.168.2.6
            250-mx.google.com at your service, [14.102.107.130]
            250-SIZE 35882577
            250-8BITMIME
            250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
            250-ENHANCEDSTATUSCODES
            250-PIPELINING
            250-CHUNKING
            250 SMTPUTF8
            DEBUG SMTP: Found extension “SIZE”, arg “35882577”
            DEBUG SMTP: Found extension “8BITMIME”, arg “”
            DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN”
            DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
            DEBUG SMTP: Found extension “PIPELINING”, arg “”
            DEBUG SMTP: Found extension “CHUNKING”, arg “”
            DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
            DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
            DEBUG SMTP: AUTH LOGIN command trace suppressed
            DEBUG SMTP: AUTH LOGIN succeeded
            DEBUG SMTP: use8bit false
            MAIL FROM:
            250 2.1.0 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            DEBUG SMTP: Verified Addresses
            DEBUG SMTP: kapeesh.gupta@ibm.com
            DEBUG SMTP: debarka.sarkar@ibm.com
            DEBUG SMTP: amit.kudale@ibm.com
            DATA
            354 Go ahead wk2sm5328789pac.12 – gsmtp
            From: lokeshgupta1981@gmail.com
            To: kapeesh.gupta@ibm.com
            Cc: debarka.sarkar@ibm.com
            Message-ID: <12869066.0.1419089528207.JavaMail.user@user-PC>
            Subject: =?Cp1252?Q?hi_baba_don=92t_send_virus_mails..?=
            MIME-Version: 1.0
            Content-Type: text/plain; charset=Cp1252
            Content-Transfer-Encoding: quoted-printable

            This is my style=85of reply..If u send virus mails..
            .
            250 2.0.0 OK 1419089555 wk2sm5328789pac.12 – gsmtp
            QUIT
            221 2.0.0 closing connection wk2sm5328789pac.12 – gsmtp

          • Hello Sir,
            This time eject error in my code.username and password not accepted.Please tell me and sorry for disturbing.
            Why userName and password not accepted while i entered correct gmail id or password.Still my entries are wrong.Why??

            Line no.21 and Line no.64.are mention below.

            21) MainA.sendMail(“kapeesh1@gmail.com”, “*****”, “smtp.gmail.com”, “25”, “true”, “true”,
            true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,

            64) transport.connect(host,userName,passWord);

            Thanks

            DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
            DEBUG SMTP: AUTH LOGIN command trace suppressed
            DEBUG SMTP: AUTH LOGIN failed
            javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
            535 5.7.8 https://support.google.com/mail/answer/7126229?visit_id=637442894384312704-1021204172&rd=1#cantsignin c9sm14915179pdj.52 – gsmtp

            535-5.7.8 Username and Password not accepted. Learn more at
            535 5.7.8 https://support.google.com/mail/answer/7126229?visit_id=637442894384312704-1021204172&rd=1#cantsignin c9sm14915179pdj.52 – 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:364)
            at javax.mail.Service.connect(Service.java:245)
            at maina.MainA.sendMail(MainA.java:64)
            at maina.MainA.main(MainA.java:21)
            BUILD SUCCESSFUL (total time: 13 seconds)

          • Hi,
            No problem sir,But u have a lot more done.Thank u so much.
            But sir mainly prob in these 2 lines only.and why could not convert socket to TLS???

            1) MainA.sendMail(“kapeesh1@gmail.com”, “********”, “smtp.gmail.com”, 25, “true”, “true”,
            true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);

            2) transport.connect(host, userName, passWord);

            3) javax.mail.MessagingException: Could not convert socket to TLS;

            Thanks

  8. Hello sir,
    Please give me right code.

    My error found is:-

    debug:
    java.lang.NoClassDefFoundError: sendmail/SendMail
    Caused by: java.lang.ClassNotFoundException: sendmail.SendMail
    at java.net.URLClassLoader$1.run(URLClassLoader.java:220)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:209)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:208)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:325)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:270)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:338)
    Error: Could not find the main class sendmail.SendMail.
    Error: A JNI error has occurred, please check your installation and try again
    Exception in thread “main” Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

      • Hello Sir,
        Thanks for give me answer.sir my code perfectly run in my system but message does not send in mail ids.

        Please see this output.and find my mistake and tell me.

        Thanks

        DEBUG: JavaMail version 1.5.1
        DEBUG: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.providers
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/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,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
        DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], 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,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], 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: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: setDebug: JavaMail version 1.5.1
        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: need username and password for authentication
        DEBUG SMTP: useEhlo true, useAuth true
        DEBUG SMTP: trying to connect to host “smtp.ibm.com”, port 25, isSSL false
        Oops something has gone pearshaped!
        com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.ibm.com, 25; timeout -1;
        nested exception is:
        java.net.UnknownHostException: smtp.ibm.com
        BUILD SUCCESSFUL (total time: 2 seconds)

          • Hi,
            I discussed with admin.He told me,our Port no is “25”,Host Name is “blr-outlook.ibm.com”,userName-“KA11479G”,but message does not send in mail id.i m sending my code please see my code and find errors.And send me correct code.

            Thanks

            import javax.mail.*;
            import javax.mail.internet.*;
            import java.util.*;
            import javax.mail.Message;
            import javax.mail.PasswordAuthentication;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;

            public class Main1
            {
            String d_email = “KA11479G”,
            d_password = “kn@nov2014”,
            d_host = “blr-outlook.ibm.com”,
            d_port = “25”,
            m_to = “kapeesh.gupta@ibm.com”,
            m_subject = “Testing”,
            m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;
            public static void main(String[] args)
            {
            String[] to={“kapeesh.gupta@ibm.com”};
            String[] cc={“debarka.sarkar@ibm.com”};
            String[] bcc={“amit.kudale@ibm.com”};
            //This is for google
            Main1.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);
            }

            public synchronized static boolean sendMail(
            String userName, String passWord, String host,
            String port, String starttls, String auth,
            boolean debug, String socketFactoryClass, String fallback,
            String[] to, String[] cc, String[] bcc,
            String subject, String text)
            {
            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);
            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);
            }

            try
            {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(“blr-outlook.ibm.com”));
            for(int i=0;i<to.length;i++) {
            msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to[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.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
            }
            catch (Exception mex)
            {
            return false;
            }
            }

            }

          • Hi,
            I changed this,code is perfectly run but message does not send email ids.Debug is below here.

            Thanks

            DEBUG: setDebug: JavaMail version 1.5.1
            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 “host”, port 25, isSSL false
            BUILD SUCCESSFUL (total time: 2 seconds)

          • In your catch block, before returning false, plz print/log the error as well.

            catch (Exception mex)
            {
            mex.printStackTrace(); //OR Log it
            return false;
            }

            It will show you why mail is not sent.

  9. Hi Lokesh,

    I have been facing an issue with javamail sending a mail from gmail. Actually i need to send it from an smtp server starting with 10.x.x.x using port 25. My Environment is jdk 1.7/windows7 32bit/javamail 1.4.1.

    Sample Code

    String to = "foo@bar.com";//change accordingly
    
            // Sender's email ID needs to be mentioned
            String from = "example@gmail.com";//change accordingly
            
    
            // Assuming you are sending email through relay.jangosmtp.net
            String host = "10.x.x.x";
    
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", "25");
            props.put("mail.debug","true");
    
            // Get the Session object.
            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });
    
            try {
                // Create a default MimeMessage object.
                Message message = new MimeMessage(session);
    
                // Set From: header field of the header.
                message.setFrom(new InternetAddress(from));
    
                // Set To: header field of the header.
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to));
    
                // Set Subject: header field
                message.setSubject("Testing Subject");
    
                // Now set the actual message
                message.setText("Hello,");
    
                // Send message
                Transport.send(message);
    
                System.out.println("Sent message successfully....");
    
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    

    java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
    at org.testng.SuiteRunner.run(SuiteRunner.java:254)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
    at javax.mail.Service.connect(Service.java:310)
    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
    … 30 more
    Caused by: java.net.SocketException: Permission denied: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    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)
    … 37 more

    Remedies Taken:
    – I have unchecked ipv6 in Network and connections.
    – i have added preferipv4stack property also not worked.
    Notes:
    when i have used smtp.gmail.com as host and port as 587 it is working fine. but my task is to send a mail through 10.x.x.x smtp server.
    Please help me Lokesh.
    Thanks in advance.

  10. Exception in thread “main” com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 586; timeout -1;
    nested exception is:
    java.net.ConnectException: Connection refused

    How to resolve this problem..plaese help!!!

  11. hello sir,,,

    I am getting this error…how can I get rid of it…
    pls help me on this…

    I used both 468 and 586 ports…but the error is same…
    ————————————————————————————–
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    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:295)
    at javax.mail.Service.connect(Service.java:176)
    at one.Chjhkj.sendEmail(Chjhkj.java:69)
    at one.Chjhkj.main(Chjhkj.java:22)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(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:321)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 5 more
    ————————————————————————————–

  12. hey when i copy paste this code and change the userid and password in netbeans i am getting following exception please help me out….
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    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 JavaEmail.sendEmail(JavaEmail.java:67)
    at JavaEmail.main(JavaEmail.java:20)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    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:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    … 5 more

  13. what port number should i use ??
    emailProperties.put(“mail.smtp.port”, “586”);
    586 port number gives error.

    • Manjeet, Can you please tell me the exact error [stack trace].. FYI: above program runs fine on my home network.
      Also, please ensure two things before running this program.
      1) You are not behind any firewall. [Most corporate networks have them. e.g. in offices]
      2) Put correct credentials here: [i.e. your email and password]

      String fromUser = “user-email@gmail.com”;
      String fromUserEmailPassword = “*******”;

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.