位置:首页 > Java技术 > JavaMail教程 > JavaMail API 发送HTML格式电子邮件

JavaMail API 发送HTML格式电子邮件

下面是一个例子,从你的机器发送HTML格式电子邮件。这里通过使用JangoSMPT服务器的邮件发送到我们的目标电子邮件地址。

这个例子非常相似,发送简单的电子邮件,除非,这里我们使用的是使用setContent()方法来设置内容的第二个参数为“"text/html"指定的HTML内容被包含在消息中。通过这个例子,你可以发送喜欢HTML内容。

发送包含HTML内容的电子邮件,遵循的步骤是:

  • 获得一个Session

  • 创建一个默认的MimeMessage对象,并设置发件人,收件人,主题(From, To, Subject)在消息中。

  • 设置使用使用setContent(实际的消息),如下方法:

    message.setContent("<h1>This is actual message embedded in 
       HTML tags</h1>", "text/html");
  • 发送使用传输对象的消息。

创建Java类

创建一个Java类文件SendHTMLEmail,是其内容如下:

package com.codeinn;

import java.util.Properties;

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 SendHTMLEmail {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "destinationemail@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "fromemail@gmail.com";
      final String username = "manishaspatil";//change accordingly
      final String password = "******";//change accordingly

      // Assuming you are sending email through relay.jangosmtp.net
      String host = "relay.jangosmtp.net";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "25");

      // Get the Session object.
      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
            }
	});

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

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

	   // Set To: header field of the header.
	   message.setRecipients(Message.RecipientType.TO,
              InternetAddress.parse(to));

	   // Set Subject: header field
	   message.setSubject("Testing Subject");

	   // Send the actual HTML message, as big as you like
	   message.setContent(
              "<h1>This is actual message embedded in HTML tags</h1>",
             "text/html");

	   // Send message
	   Transport.send(message);

	   System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
	   e.printStackTrace();
	   throw new RuntimeException(e);
      }
   }
}

由于我们使用的是由主机提供商JangoSMTP提供 SMTP服务器,我们需要验证用户名和密码。javax.mail.PasswordAuthentication类用于验证的密码。

编译并运行

Now that our class is ready, let us compile the above class. I've saved the class SendHTMLEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar andactivation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt:

javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail.java

Now that the class is compiled, execute the below command to run:

java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail

Verify Output

You should see the following message on the command console:

Sent message successfully....

As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox:

JavaMail API Send HTML Email