如何从jsp / servlet发送电子邮件?

如何从JSP / servlet发送电子邮件? 是否有必要下载一些jar子,或者你可以在没有任何jar子的情况下从JSP / servlet发送电子邮件吗?

  • 我的Java代码会是什么样的?

  • 我的HTML代码会是什么样的(如果有的话)?

  • 是否需要多个class级,或者您只使用一个class级?

邮件程序逻辑应该放在它自己的独立类中,您可以在任何地方重用它。 JSP文件应仅包含表示逻辑和标记。 Servlet类应该以适当的方式处理请求并调用邮件程序类。 以下是您需要采取的步骤:

  1. 首先确定您要使用哪个SMTP服务器 ,以便能够发送电子邮件。 你的ISP之一? Gmail之一? 雅虎? 网站托管服务商? 一个自我维护的? 无论如何,请确定此SMTP服务器的主机名,端口,用户名和密码。 您将需要此信息。


  2. 创建一个普通的vanilla Java类,它使用JavaMail API发送邮件消息。 JavaMail API附带了一个很好的教程和FAQ 。 将类命名为Mailer并为其提供send()方法(或任何您想要的)。 使用一些测试器类使用main()方法测试它,如下所示:

     public class TestMail { public static void main(String... args) throws Exception { // Create mailer. String hostname = "smtp.example.com"; int port = 2525; String username = "nobody"; String password = "idonttellyou"; Mailer mailer = new Mailer(hostname, port, username, password); // Send mail. String from = "john.doe@example.com"; String to = "jane.doe@example.com"; String subject = "Interesting news"; String message = "I've got JavaMail to work!"; mailer.send(from, to, subject, message); } } 

    您可以根据需要将其设置为简单或高级。 没关系,只要你有一个类可以发送这样的邮件。


  3. 现在是JSP部分,你提到JSP的原因并不完全清楚,但是由于JSP 应该只代表HTML,我敢打赌你希望在JSP中有类似联系表单的东西。 这是一个启动示例:

     

    Your email address:

    Mail subject:

    Mail message:

    ${message}

    是的,简单明了,只需标记/样式就可以了。


  4. 现在,创建一个Servlet类,它侦听/contacturl-pattern (与表单提交的相同)并实现doPost()方法(与表单使用的方法相同),如下所示:

     public class ContactServlet extends HttpServlet { private Mailer mailer; private String to; public void init() { // Create mailer. You could eventually obtain the settings as // web.xml init parameters or from some properties file. String hostname = "smtp.example.com"; int port = 2525; String username = "nobody"; String password = "forgetit"; this.mailer = new Mailer(hostname, port, username, password); this.to = "you@example.com"; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String subject = request.getParameter("subject"); String message = request.getParameter("message"); // Do some validations and then send mail: try { mailer.send(email, to, subject, message); request.setAttribute("message", "Mail succesfully sent!"); request.getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response); } catch (MailException e) { throw new ServletException("Mailer failed", e); } } } 

    而已。 保持简单和干净。 每件事都有自己明确的责任。

当我们使用java mail api从类文件发送时,您可以从jsp或servlet发送邮件。 这是链接,它将帮助您:

http://www.java-samples.com/showtutorial.php?tutorialid=675

我正在使用javamail包,它非常好用。 上面显示的示例很好,但我可以看到他们没有在外部文件中定义参数(例如web.xml),这是推荐的……

想象一下,您想要更改您的电子邮件地址或SMTP主机..编辑web.xml文件要比使用邮件function的10个servlet容易得多。 例如,在web.xml中添加下一行

  smtp_server smtp.blabla.com 

然后,您可以从servlet访问这些参数

 // 1 - init Properties props = new Properties(); //props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtp_server); props.put("mail.smtp.port", smtp_port); 

JSP页面:

 
To Email-id :

这是Servlet代码:

 String uri=req.getRequestURI(); if(uri.equals("/mail.do")) { SendEmail sa=new SendEmail(); String to_mail=request.getParameter("email"); String body="
Hi this is Test mail
"; sa.SendingEmail(to_email,body); }

和SendEmail类:

  package Email; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public void SendingEmail(String Email,String Body) throws AddressException, MessagingException { String host ="smtp.gmail.com"; String from ="yourMailId"; //Your mail id String pass ="yourPassword"; // Your Password Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); // added this line props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "25"); props.put("mail.smtp.auth", "true"); String[] to = {Email}; // To Email address Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i=0; i < to.length; i++ ) { // changed from a while loop toAddress[i] = new InternetAddress(to[i]); } System.out.println(Message.RecipientType.TO); for( int j=0; j < toAddress.length; j++) { // changed from a while loop message.addRecipient(Message.RecipientType.TO, toAddress[j]); } message.setSubject("Email from SciArchives"); message.setContent(Body,"text/html"); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } } 

这个基本设置很好:

mail.jaractivation.jar导入到项目内的WEB_INF / lib文件夹中。

JavaMail获取mail.jar (官方网站的最新版本)

从http://www.oracle.com/technetwork/java/javase/jaf-136260.html获取activation.jar

1.首先是jsp:emailForm.jsp

这是用于将发件人,接收者详细信息,主题和邮件内容传递给emailUtility的表单

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>     Send email   

Send email using SMTP

Sender address
Recipient address
Subject
Message Text

2.第二个jsp:emailUtility.jsp

这是前面的jsp(emailForm.jsp)中提到的表单操作。

   email utility   <%@ page import="java.util.*" %> <%@ page import="javax.mail.*" %> <%@ page import="javax.mail.internet.*" %> <%@ page import="javax.activation.*" %> <% String host = "smtp.gmail.com"; String to = request.getParameter("to"); String from = request.getParameter("from"); String subject = request.getParameter("subject"); String messageText = request.getParameter("messageText"); boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.debug", "true"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "youremail@gmail.com", "password_here");// Specify the Username and the PassWord } }); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); out.println("Mail was sent to " + to); out.println(" from " + from); out.println(" using host " + host + "."); %>    

3.转到以下URL

HTTP://本地主机:8080 /项目名称/ emailForm.jsp

4.如果服务器出现服务器错误,请重新启动服务器