如何使用 JSP 页面发送基于 HTML 的电子邮件?
下面提供一个在计算机中发送 HTML 电子邮件的示例。假设你的本地主机已连接到互联网,并且能够发送电子邮件。确保Java 电子邮件 API 包和JAF 包中的所有 jar 文件都可以在 CLASSPATH 中找到。
此示例与上一个示例非常相似,只是这里我们使用 setContent() 方法设置内容,其第二个参数为 "text/html",用于指定要将 HTML 内容包含在消息中。
通过此示例,你可以发送所需长度的 HTML 内容。
示例
<%@ page import = "java.io.*,java.util.*,javax.mail.*"%> <%@ page import = "javax.mail.internet.*,javax.activation.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <% String result; // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties object Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session mailSession = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(mailSession); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like message.setContent("<h1>This is actual message</h1>", "text/html" ); // Send message Transport.send(message); result = "Sent message successfully...."; } catch (MessagingException mex) { mex.printStackTrace(); result = "Error: unable to send message...."; } %> <html> <head> <title>Send HTML Email using JSP</title> </head> <body> <center> <h1>Send Email using JSP</h1> </center> <p align = "center"> <% out.println("Result: " + result + "
"); %> </p> </body> </html>
广告