Latest web development tutorials

Java Send Mail

Send Using E-mail Java applications is very simple, but first you should install JavaMail API and the Java Activation Framework (JAF) on your machine.

  • You can download the latest version of Java the JavaMail , open the right side of the page there is a Downloads link, click on it to download.
  • You can download the latest version of Java (Version 1.1.1) JAF .

You can also use the site to provide download link:

Download and unzip the files in the newly created top-level directory, you'll find some jar file two applications. You need to addmail.jar and activation.jarfiles to your CLASSPATH.

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


Simply send an E-mail

Here is a simple example of sending E-mail. Suppose your localhost already 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 the 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 methods to specify multiple recipients ID:

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

The following is the description of the parameters:

  • type: to be set as TO, CC or BCC CC here on behalf of the CC, BCC representatives of secret CC y Example:.. Message.RecipientType.TO

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


Send an HTML E-mail

Here is an example of HTML E-mail sent. Suppose your localhost already connected to the network.

And it is very similar to the previous example, except that we want to use setContent () method to pass the second parameter is "text / html", to set the content to be sent to specify the HTML content.

// 文件名 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 E-mail with attachments

Here is an example of E-mail with an attachment is sent. Suppose your localhost already 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 email with attachments.

$ java SendFileEmail
Sent message successfully....

User authentication section

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

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

e-mail and other delivery mechanisms consistent with the above.

It requires a user name password authentication messages sent Example:

In the present example QQ mail server, for example, you need to log QQ mailbox in the background in the "Settings" = "open account in POP3 / SMTP service, as shown below:

qq-mail to set the password by generating a license key:

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]";

      // 指定发送邮件的主机为 smtp.qq.com
      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.cc");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}