Getting started with Java - advanced tutorial - 06. Email

Original address: http://www.work100.net/training/java-email.html
More tutorials: Beam cloud - free course

Mail sending and receiving

Serial number Chapter in text video
1 Summary -
2 Send a simple email -
3 Send an HTML message -
4 Send mail with attachments -
5 User authentication -

Please refer to the navigation above for reading

1. overview

Sending E-mail using a Java application is easy, but first you should install the JavaMail API and the Java Activation Framework (JAF) on your machine.

  • You can download the latest version of JavaMail from the Java website, open a Downloads link on the right side of the page, and click it to download

  • You can download the latest version of JAF (Version 1.1.1) from the Java website

You can also use the download link provided by our website:

  • JavaMail mail.jar 1.4.5

  • JAF (Version 1.1.1) activation.jar

Download and extract these files, and in the newly created top-level directory, you will find some jar files of these two applications. You need to add the mail.jar and activation.jar files to your CLASSPATH.

If you use a third-party mail server such as QQ's SMTP server, you can see the full instance of user authentication at the bottom of the article.

2. Send a simple email

Here is an example of sending a simple E-mail. Suppose your local host is connected to the network.

// File name SendEmail.java

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

public class SendEmail
{
   public static void main(String [] args)
   {   
      // Recipient email
      String to = "abcd@gmail.com";

      // Sender email
      String from = "web@gmail.com";

      // Specify localhost as the host to send mail
      String host = "localhost";

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

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

      // Get the default session object
      Session session = Session.getDefaultInstance(properties);

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

         // Set From: header field
         message.setFrom(new InternetAddress(from));

         // Set To: header field
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Set message body
         message.setText("This is actual message");

         // send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run this program to send a simple E-mail:

$ java SendEmail
Sent message successfully....

If you want to send an E-mail to multiple recipients, use the following method to specify multiple recipient ID S:

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

The following is a description of the parameters:

  • type: TO, CC or BCC, where CC stands for CC and BCC stands for secret CC. Example: Message.RecipientType.TO

  • addresses: This is an array of email IDs. When specifying an email ID, you will need to use the InternetAddress() method.

3. Send an HTML email

Here is an example of sending HTML E-mail. Suppose your local host is connected to the network.

Similar to the previous example, except that we use the setContent() method to set the content to specify the HTML content to be sent with the second parameter "text/html".

// File name SendHTMLEmail.java

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

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

      // Recipient email
      String to = "abcd@gmail.com";

      // Sender email
      String from = "web@gmail.com";

      // Specify localhost as the host to send mail
      String host = "localhost";

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

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

      // Gets the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

         // Set From: header field
         message.setFrom(new InternetAddress(from));

         // Set To: header field
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Send html message, you can insert html tag
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );

         // send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run this program to send HTML e-mail:

$ java SendHTMLEmail
Sent message successfully....

Send mail with attachments

4. Send email with attachments

Here is an example of sending an E-mail with attachments. Suppose your local host is connected to the network.

// File name SendFileEmail.java

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

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

      // Recipient email
      String to = "abcd@gmail.com";

      // Sender email
      String from = "web@gmail.com";

      // Specify localhost as the host to send mail
      String host = "localhost";

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

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

      // Gets the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

         // Set From: header field
         message.setFrom(new InternetAddress(from));

         // Set To: header field
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Create message section
         BodyPart messageBodyPart = new MimeBodyPart();

         // news
         messageBodyPart.setText("This is message body");

         // Create multiple messages
         Multipart multipart = new MimeMultipart();

         // Set text message section
         multipart.addBodyPart(messageBodyPart);

         // Appendix
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send full message
         message.setContent(multipart );

         //   send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run your program to send an email with attachments.

$ java SendFileEmail
Sent message successfully....

5. User authentication

If you need to provide the user name and password to the e-mail server to achieve the purpose of user authentication, you can do so through the following settings:

props.put("mail.smtp.auth", "true");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

Other sending mechanisms of e-mail are consistent with the above.

Need user name and password to verify email sending instance:

This example takes QQ mail server as an example. You need to start POP3/SMTP service in setting = account = in the background of logging in QQ mailbox, as shown in the following figure:

QQ mailbox sets password by generating authorization code:

The Java code is as follows:

// Need user name password email send instance
//File name SendEmail2.java
//This example takes QQ mailbox as an example. You need to set it in QQ background

import java.util.Properties;

import javax.mail.Authenticator;
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 SendEmail2
{
   public static void main(String [] args)
   {
      // Recipient email
      String to = "xxx@qq.com";

      // Sender email
      String from = "xxx@qq.com";

      // Specify the host to send mail as smtp.qq.com
      String host = "smtp.qq.com";  //QQ mail server

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

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

      properties.put("mail.smtp.auth", "true");
      // Get the default session object
      Session session = Session.getDefaultInstance(properties,new Authenticator(){
        public PasswordAuthentication getPasswordAuthentication()
        {
         return new PasswordAuthentication("xxx@qq.com", "qq Email authorization code"); //Sender's email user name and authorization code
        }
       });

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

         // Set From: header field
         message.setFrom(new InternetAddress(from));

         // Set To: header field
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Set message body
         message.setText("This is actual message");

         // send message
         Transport.send(message);
         System.out.println("Sent message successfully....from runoob.com");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Set SSL encryption

For QQ mailbox, SSL encryption should be set, and the following code should be added

The code is as follows:

MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);

Full reference code:

import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.mail.Authenticator;
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;
import com.sun.mail.util.MailSSLSocketFactory;

public class SendEmail 
{
    public static void main(String [] args) throws GeneralSecurityException 
    {
        // Recipient email
        String to = "XXXXX@qq.com";

        // Sender email
        String from = "XXXXXX@qq.com";

        // Specify the host to send mail as smtp.qq.com
        String host = "smtp.qq.com";  //QQ mail server

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

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

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // Get the default session object
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("429240967@qq.com", "Authorized QQ Mailbox password"); //Sender's email user name and password
            }
        });

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

            // Set From: header field
            message.setFrom(new InternetAddress(from));

            // Set To: header field
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("This is the Subject Line!");

            // Set message body
            message.setText("This is actual message");

            // send message
            Transport.send(message);
            System.out.println("Sent message successfully....from runoob.com");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

Last article: Network programming
Next article: Multithreading

If you are interested in the content of the course, you can scan the code to pay attention to our official account or QQ group, and pay attention to our curriculum updates in time.


Tags: Java Session SSL network

Posted on Sat, 07 Mar 2020 19:43:11 -0500 by papacostas