Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to send email using Java

In this article we will see how to send email using Java via SMTP.

Sending email from any of the java code present in the web pages is a very important part these days. Some additional features are always required so as to send some of the very important details through email. Here for the purpose of this tutorial, we will be making use of SMTP server.

In this tutorial, we will see illustrate here how to send emails from one email-id to another email id. Make note of the few points to note here before we start our tutorial.

  • There is a need of some jar files known by the name of smtp, mailapi, mail and dsn.
  • The jar files mentioned above should be placed in Tomcat server and that too under the lib folder.
  • Also, these jar files can be directly incorporated at the time of implementing the code.

Listing 1: Sending the email using Java code

package Java;

import java.mail.*;
import java.mail.internet.*;
import java.util.*; 

public class JavaMail {
	public static void main(String[] args)gives MessagingException {
		// It is required to mention the email id of the recipient.
			String senderemail = "senderid@abc.com",
			senderpassword = "*****",
			senderhost = "smtp.abc.com",
			senderport = "XXX",
			recieverid = "recipientid@abc.com",
			subjecttobegiven = "MrBool",
			message = "Welcome to MrBool";

			Properties props = new Properties();
			 props.put("mail.smtp.user", senderemail);
			 props.put("mail.smtp.host", senderhost);
			 props.put("mail.smtp.port", senderport);
			 props.put("mail.smtp.enable","true");
			 props.put("mail.smtp.auth", "true");
			 //props.put("mail.smtp.debug", "true");
			 props.put("mail.smtp.socketFactory.port",sender_port);

Use the below code so as to get the alternative way of sending the email making use of the java code.

Listing 2: Alternative way to send the email

SimpleEmail email = new SimpleEmail();
email.setHostName("mail.myserver.com");
email.addTo("you@abc.com", "Friend");
email.setFrom("me@abc.com", "Me");
email.setSubject("This is a test message");
email.setMsg("This is a simple email using java code");
email.send();

Making use of the java application, we can always send emails from one domain to another . This could include domains like gmail, yahoomail etc. However the only thing which is required is SMTP.

The validation of the sender needs to be set in the application. This needs to be done at the time of the initialization of the session. This is for the reason that it is always disabled by default. We are not requiring giving any sender id in case the person to whom you are sending the email is within the local network only. However in case the email is required to be sent across the network, the sender id needs to be incorporated in the message header.

The below code illustrates what we discussed above.

Listing 3: Validation of the sender of the email

package com.sample.mail;

 /**
  *API provided by Java
  *
  */
import java.mail.*;
import java.mail.internet.*;

 /**
   *Displays the SendMail method in order to send email
   *
   */
public class  SendMail 
{    
    public void sendMail( String recipients, subject, message , from) gives MessagingException
    {
        /**
          * Displays Mail Header Properties
          *
          */
      Properties props = new Properties();

 
        props.put("mail.smtp.port", "XXX");
      props.put("mail.smtp.host", "192.AAA.BB.C");
        
        props.put("mail.auth", "true");
        props.put("mail.smtp.port", "YY");
        props.put("mail.smtp.socket.port", "CC");

        props.put("mail.smtp.socket.class",
 "javax.net.sslSocketFactory");

 props.put("mail.smtp.socketFactory.fallback", "false");
 props.setProperty("mail.smtp.quitwait", "false");

        /**
          * Displays by default the Message Session and Authentication
          * Here Authentication is disabled
          */
 
 Session session = Session.DefaultInstance(properties,
     new java.mail.Authentication() 
 {
 protected Password getPasswordAuthenticator()
{
                      return new PasswordAuthenticator("username","password");
                 }
});

     Message msg = new Message;
        
        addressFrom = new InternetAddress(from);
     msg.setFrom(addressFrom);
        
     InternetAddress addressTo = new InternetAddress(recipients);
        msg.setRecipient(Message.Recipient.TO, addressTo);

        /**
          *The body of the email can have many parts, it can have attachments as well
          *
          */
        
     msg.setSubject(mailsubject);
     msg.setbody(message, "text");
        
     Transmit.send(msg);
    }
    
    public static void main(String s[])
    {
        SendMail mail=new SendMail();
        try
        {        
            mail.sendMail("recipientsemail-id","subject of the email","Testmail","Sender_id");            
        }
        catch (Exception e)
        {
              e.printTrace();
        }
    }
}

Let us now see how to send the email with an attachment. In order to make this, we have a Javamail API that is capable of providing classes known by the name of BodyPart, MimeBodyPart and many more.

Let us go through step by step in order to send the email where the attachment will be included as a part of the email. The very first step is to get the session object. The next would be to compose the message, set all the parts of the email and make the email ready to be sent. The third step would be to create MimeBodyPart object, where in you need to set the text for the message which you are going to send out. The fourth step would be to come up with a new MimeBodyPart object and then setting up the Datahandler object to this specific object.

The next or the fifth step would be the creation of a multipart object. Then add MimeBodyPart object where in we will set the multipart object to the message object. And then finally we have a message ready to be sent out.

Listing 4 : Sending email with the attachment

import java.util.*;
import java.mail.*;
import java.mail.internet.*;
import java.activation.*;

class postattachment{
 public static void main(String [] args){

  String to="recipient_id@abc.com";// you can change the id accordingly
  final String user="sender_id@abc.com";// you can change the id accordingly
  final String password="xxxxx";// you can change the password accordingly
 
  //1) Retrieve the session object   
  Properties props = System.getProps();
  props.setProp("mail.smtp.host", "mail.abc.com");// you can change the site name accordingly
  props.put("mail.smtp.auth", "true");

  Session session = Session.getInstance(props,
   new java.mail.Authentication() {
   protected Password getPasswordAuthenticator() {
   return new PasswordAuthenticator(user,password);
   }
  });
   
  //2) Message set up   
  try{
    MimeMsg msg = new Mimemsg(session);
    msg.setFrom(new Address(user));
    msg.addRecipient(Msg.RecipientType.TO,newAddress(to));
    msg.setSubject("Msg Alert");
    
    //3) Creation of MimeBodyPart object, setting up of the message content    
    BodyPart msgBodyPhase1 = new MimeBodyPhase();
    msgBodyPhase1.setText("Msg Body");
    
    //4) Creating new MimeBodyPart object, setting up of the DataHandler object    
    MimeBodyPart msgBodyPhase2 = new MimeBodyPhase();

    String filename = "Attachment";//change  the file name accordingly
    DataSource src = new FileDatasrc(filename);
    msgBodyPhase2.setDataHandler(new DataHandler(src));
    msgBodyPhase3.setFileName(filename);
   
   
    //5) Creation of the Multipart object as well as incorporating the MimeBodyPart objects    
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPhase(messageBodyPhase1);
    multipart.addBodyPhase(messageBodyPhase2);

    //6) Setting up of the multiplart object
    msg.setContent(multipart );
   
    //7) Finally the sending of the message
    Tranmit.send(message);
 
   System.out.println(" message is sent....");
   }catch (MessagingException ex) {ex.printTrace();}
 }
}

Suppose we want to send lots of different emails and that too to different recipients. We would here like to open the connection to the SMTP for the reason that this is very fast, and it opens the reopened connection for each and every email. Here we would be using the Apache Email for that. However we could always go back to the Java Mail API in case this is required.

Here we will be doing exactly the same that will open the connection.

Listing 5: Sending multiple emails to different recipients

Email email = new HtmlEmail();
email.setHost(server.getHost());
email.setPort(server.getPort());
email.setAuthentication(new Authenticator(getUsername(), getPassword()));
email.setFrom("sender_id@abc.com");
email.addTo(to);
email.setSubject( “This is a subject”);
email.setHtmlMsg(“ This is a message body);
email.send();

Conclusion

We learned different aspects of working with emails using Java Application. See you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login