Java Sends Mail

Keywords: Session Java Python

Original address: Send email using Java Program

If you write code on Java, J2EE, or Python platforms, sending email is a requirement that needs little consideration. Sending an email may require sending an error warning and confirmation by the Registrar or logger. Java provides some of these functions.

Java needs three things to send mail:

  • JavaMail API
  • Java Activation Framework (JAF)
  • SMTP Server Details

You can download the latest version of JavaMail API and JAF from the Java official website. Unzip after downloading these two tools. Add mail. jar, smtp. jar and activation.jar files to the classpath to send mail.

After adding these files, send mail according to the following steps and Java code:

  • A new session object is created by calling getDefaultInstance(), which passes attributes to parameters to obtain all important attributes, such as hostname, SMTP server, etc.
  • In the previous step, a MimeMessage object is created by passing the session object.
  • The last step is to send mail with javax.mail.Transport.
// Java program to send email

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;

public class SendEmail {

    public static void main(String[] args) {
        // email ID of Recipient.
        String recipient = "recipient@gmail.com";

        // email ID of  Sender.
        String sender = "sender@gmail.com";

        // using host as localhost
        String host = "127.0.0.1";

        // Getting system properties
        Properties properties = System.getProperties();

        // Setting up mail server
        properties.setProperty("mail.smtp.host", host);

        // creating session object to get properties
        Session session = Session.getDefaultInstance(properties);

        try {
            // MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From Field: adding senders email to from field.
            message.setFrom(new InternetAddress(sender));

            // Set To Field: adding recipient's email to from field.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

            // Set Subject: subject of the email
            message.setSubject("This is Suject");

            // set body of the email.
            message.setText("This is a test mail");

            // Send email.
            Transport.send(message);
            System.out.println("Mail successfully sent");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

Output:

Mail successfully sent


Send mail to multiple people

Sending an email to multiple people is the same as sending an email to one person. The difference is that you have to add more than one recipient to send an email to more than one person. To add more than one recipient, we have to call the following method and pass the recipient's type and mailing address list as parameters:

void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException{
}

You can use Message.RecipientType.To to add the right-click to the "recipient" column. Similarly, you can use Message.RecipientType.CC and Message.RecipientType.BCC to add to the "copy" and "secret delivery".

The addresses parameter in the above method is an array that contains an Email-IDs list. You must specify the mail using the Internet Address () method.

Suppose you want to email four people. You want to create a string of size 4 that is an array that originally saves the recipient's email address. The following code is to use addRecipients to send a simple email, not to one person, but to multiple people.

// create a new String array
String[] recipients = new String[4];

// add email addresses
recipients[0] = first@gmail.com
recipients[1] = second@gmail.com
recipients[2] = third@gmail.com
recipients[3] = fourth@gmail.com

// inside of try block instead of using addRecipient() 
// use addRecipients()

// specify the type of field(TO, CC ,BCC)
// pass the array of email ids of recipients
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
** Sending mail using HTML templates** Sometimes you use HTML templates to send mail. For example, the body of the mail is written in HTML. This makes the mail well formatted and more attractive. The code of sending mail with HTML is basically the same as that of sending mail in general. The difference is that the `setContent()'method is used instead of `setText()', and in `setContent()', we must specify the second parameter as `text/html', and the first parameter is HTML code. Let's look at the code for sending mail using HTML templates:
// Java program to send email
// with HTML templates

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;

public class SendEmail {

    public static void main(String[] args) {
        // email ID of Recipient.
        String recipient = "recipient@gmail.com";

        // email ID of  Sender.
        String sender = "sender@gmail.com";

        // using host as localhost
        String host = "127.0.0.1";

        // Getting system properties
        Properties properties = System.getProperties();

        // Setting up mail server
        properties.setProperty("mail.smtp.host", host);

        // creating session object to get properties
        Session session = Session.getDefaultInstance(properties);

        try {
            // MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From Field: adding senders email to from field.
            message.setFrom(new InternetAddress(sender));

            // Set To Field: adding recipient's email to from field.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

            // Set Subject: subject of the email
            message.setSubject("This is Suject");

            // set body of the email.
            message.setContent("<h1>This is a HTML text</h1>", "text/html");

            // Send email.
            Transport.send(message);
            System.out.println("Mail successfully sent");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

Output:

Mail successfully sent


Send attachments

The JavaMail API allows sending attachments. To send attachments, we have to create a MimeBodyPart object, one assigning text and the other assigning datahandler. The main process of sending mail with attachments is as follows:

  • Create a session object
  • Create a MimeBodyPart object and assign text to it.
  • Create a MimeBodyPart object and assign it to the datahandler.
  • Create a MultiPart object and assign the MultiPart with two MimeBodyPart s.
  • Set the MultiPart object to the message.SetContent() method.
  • Send mail with Transport().

Let's look at the code:

// Java program to send email
// with attachments

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;

public class SendEmail {

    public static void main(String [] args) 
    { 
        // email ID of Recipient.
        String recipient = "recipient@gmail.com";

        // email ID of Sender.
        String sender = "sender@gmail.com";

        // using host as localhost
        String host = "127.0.0.1";

        // Getting system properties
        Properties properties = System.getProperties();

        // Setting up mail server
        properties.setProperty("mail.smtp.host", host);

        // creating session object to get properties
        Session session = Session.getDefaultInstance(properties);

        try
        {
            // MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From Field: adding senders email to from field.
            message.setFrom(new InternetAddress(sender));

            // Set To Field: adding recipient's email to from field.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

            // Set Subject: subject of the email
            message.setSubject("This is Suject");

            // creating first MimeBodyPart object
            BodyPart messageBodyPart1 = new MimeBodyPart(); 
            messageBodyPart1.setText("This is body of the mail");

            // creating second MimeBodyPart object
            BodyPart messageBodyPart2 = new MimeBodyPart(); 
            String filename = "attachment.txt"
            DataSource source = new FileDataSource(filename);  
            messageBodyPart2.setDataHandler(new DataHandler(source));  
            messageBodyPart2.setFileName(filename);  

            // creating MultiPart object
            Multipart multipartObject = new MimeMultipart();  
            multipartObject.addBodyPart(messageBodyPart1);  
            multipartObject.addBodyPart(messageBodyPart2);



            // set body of the email.
            message.setContent(multipartObject);

            // Send email.
            Transport.send(message);
            System.out.println("Mail successfully sent");
        }
        catch (MessagingException mex) 
        {
            mex.printStackTrace();
        }
    }
}

Output:

Mail successfully sent

Note: Here we use localhost SMTP server to send mail. If you want to use clients such as Gmail and Yahoo to send mail, you have to use respective SMTP server host address.

Posted by sharp3d on Wed, 26 Jun 2019 14:41:33 -0700