Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java sends a message


May 10, 2021 Java


Table of contents


Java sends a message

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

You can download the latest version on JavaMail (Version 1.2).

You can download the latest version again at JAF (Version 1.1.1).

Download and unzip these files, the top folder you will find a lot of jar files. You'll need .jar email and .jar to add to your CLASSPATH.

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


Send a simple E-mail

Here's an example of sending a simple E-mail. Let's say your localhost is connected to the network.

// 文件名 SendEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail
{
   public static void main(String [] args)
   {   
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");
 
         // 设置消息体
         message.setText("This is actual 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 IDs:

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

Here's a description of the parameters:

  • Type: To be set to TO, CC or BCC. H ere CC stands for CC, BCC stands for secret CC y. Example: Message.RecipientType.TO

  • Addresss: This is an array of email IDs. When you specify an e-mail ID, you will need to use the InternetAddress() method.


Send an HTML E-mail

Here is an example of sending HTML E-mail. Let's say your localhost is connected to the network.

Similar to the previous example, except that we're going to use the setContent() method to set the content to specify the HTML content to send through the second parameter, "text/html."

// 文件名 SendHTMLEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendHTMLEmail
{
   public static void main(String [] args)
   {
     
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 发送 HTML 消息, 可以插入html标签
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
 
         // 发送消息
         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 an E-mail with attachments

Here is an example of sending an E-mail with attachments. L et's say your localhost is connected to the network.

// 文件名 SendFileEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendFileEmail
{
   public static void main(String [] args)
   {
     
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 创建消息部分
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 消息
         messageBodyPart.setText("This is message body");
        
         // 创建多重消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 附件部分
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整消息
         message.setContent(multipart );
 
         //   发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run your program to send a message with attachments.

$ java SendFileEmail
Sent message successfully....

The user authentication section

If you need to provide a username and password to the e-mail server for user authentication purposes, you can do so by setting up the following:

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

The other sending mechanisms for e-mail are consistent with the above.

An instance of sending a message that requires a username password verification:

This example to QQ mail server as an example, you need to log in to QQ mailbox background in the "settings" account to open POP3 / SMTP service, as shown in the following image:

Java sends a message

The Java code is as follows:

// 需要用户名密码邮件发送实例
//文件名 SendEmail2.java
//本实例以QQ邮箱为例,你需要在qq后台设置

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)
   {
      // 收件人电子邮箱
      String to = "[email protected]";

      // 发件人电子邮箱
      String from = "[email protected]";

      // 指定发送邮件的主机为 localhost
      String host = "smtp.qq.com";  //QQ 邮件服务器

      // 获取系统属性
      Properties properties = System.getProperties();

      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);

      properties.put("mail.smtp.auth", "true");
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties,new Authenticator(){
	    public PasswordAuthentication getPasswordAuthentication()
	    {
	     return new PasswordAuthentication("[email protected]", "qq邮箱密码"); //发件人邮件用户名、密码
	    }
	   });

      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);

         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));

         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");

         // 设置消息体
         message.setText("This is actual message");

         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....from w3cschool.cn");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}