Sending Mail Using JavaMail API

Posted on by By admin, in Java, Javascript, Miscellaneous | 0

Here, we are going to see how to send mail using JAVA MAIL API.

First, you need mail.jar in your project. If you have, copied it otherwise you can download.

Here are few notes, when you are going to create program for mail sending:

1)     It is always better to create SESSION instance in your code.

2)     Make sure you are using correct information about your SMTP host.

3)     Sender and recipient’s mail-id must be valid and active.

Now, we will see examples:

1: The Properties class represents a persistent set of properties. So create an object of Properties and set all required parameters into this object:

Properties props = new Properties();

props.put(“mail.smtp.auth”,isAuthenticated);

props.put(“mail.smtp.starttls.enable”,isSSLEnabled);

props.put(“mail.smtp.host”, hostname);

props.put(“mail.smtp.port”, port);

2: Create Session instance to authenticate user:

Session session = Session.getInstance(props,new javax.mail.Authenticator()                                                                {

protected PasswordAuthentication getPasswordAuthentication() {

    return new PasswordAuthentication(username, password);

   }

 });

3: Now, Create an object of java.mail.Message with created object of Session:

Message message = new MimeMessage(session);

Now, set required parameters which are used in sending mail, to message object:

message.setFrom(new InternetAddress(from@sender.com));

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to@recipient.com));

message.setSentDate(new Date());

message.setContent(body, “text/html; charset=utf-8”);

message.setSubject(“Testing Java Mail”);

message.setText(“Dear Recipient,” +”\n\n Hurray!! Mail is here.”);

Now, Send Message:

Transport.send(message);

NOTE:

If you are trying to send mail using gmail SMTP, first you need to disable security. You can find this option in your gmail setting or when you send mail, you will get one mail from gmail which will help you to disable security.

You can find below the code which sends mail using gmail SMTP:

package com.helical.Mail;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

  public class SendMailGmail {

 

                public static void main(String[] args)

               {

                                final String username = “username@gmail.com”;

                                final String password = “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 PasswordAuthentication getPasswordAuthentication() {

                                                                return new PasswordAuthentication(username, password);                                                

                                                                      } 

                                                                });

 

                            try

                            {

                                    Message message = new MimeMessage(session);

                                    message.setFrom(new InternetAddress(“from-email@gmail.com”));

                              message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(“to-email@gmail.com”));

                                  message.setSubject(“Java Mail Testing”);

                                 message.setText(“Dear Recipient,”+ “\n\n Mail has received”);                  

                                 Transport.send(message);

                                System.out.println(“Mail Sent Successfully”);

                            }

                           catch (MessagingException e)

                          {

                                                throw new RuntimeException(e);

                          }

            }

}

Troubleshooting:

There are few exception, which you get often:

  • UnknownHostException : SMTP HOST

 

Ping to your SMTP host from command line. Make sure you get response (Success) because sometimes your firewall may block your connection.

 

  • javax.mail.AuthenticationFailedException

 

Check your username and password. If this is correct, try to login using your browser and make sure given user information are correct.

 

  • Could not connect to SMTP host

Check your SMTP host name and SMTP port, this is correct or not. Execute telnet command from your command prompt and check you are able to connect or not. Telnet command is:

C:\> telnet <SMTP HOST> <SMTP PORT>

 

Thanks

Sharad Sinha

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments