当前位置: 首页 > 知识库问答 >
问题:

使用jsp发送电子邮件

宫子晋
2023-03-14
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link href="bootstrap.css" rel="stylesheet" type="text/css"/>
        <script src="bootstrap.js" type="text/javascript"></script>
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <script src="jquery-3.1.1.js" type="text/javascript"></script>

    </head>
    <body style="background-color:lightgreen">
         <form class="form-group" style=" margin-right:200px; padding: 30px 0px 0 25px;  background-color:white">                     
             <p style="margin: -30px 0 10px  70px; font-size: 20px">Sending Email </p>
                <input type="email" class="form-control" placeholder="To" required name="to" style="width:300px" /><br />
                <input type="email" class="form-control" placeholder="From" required name="from" style="width:300px" /><br />
                <input type="text" class="form-control" placeholder="subject:" required name="subject" style="width:300px" /><br />
                <textarea placeholder="body" required name="body" cols="32" rows="7" style="border:1px gray solid;border-radius:5px;"></textarea><br />
                <input type="submit" value="send" name="btn"   style="width: 300px; height: 35px; border: 1px solid gainsboro; border-radius: 4px; background-color:limegreen; color: white"/><br /><br />
    <%
     String from = request.getParameter("from");
          String to = request.getParameter("to");
          String subject = request.getParameter("subject");
           String bod = request.getParameter("body");
      final String username = "muneeb";
      final String password = "******";
// Get system properties object
      String host = "smtp.gmail.com";

      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", "587");

      // Get the Session object.
        Session session1 = 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(session1);

         // 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(subject);

         // Now set the actual message
         message.setText(bod);
         // Send message
         Transport.send(message);

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

      } catch (MessagingException e) {
             System.out.println(" faild message....");

      }
%>
    </div>
        </div>
</body>
</html>

它显示以下错误:

JasperException:处理JSP页面/assignment3/send_email.JSP第132 129行时发生异常:Message Message=new MimeMessage(session1);130:131://Set FROM:header标头字段。132:message.setFrom(新InternetAddress(from));133:134://设置为:标头的标头字段。135:Message.SetRecipients(Message.RecipientType.To,StackTrace:org.apache.jasper.servlet.jspServletrapper.handlejspException(jspServletrapper.java:584)org.apache.jasper.servlet.jspServletrapper.service(jspServletrapper.java:481)org.apache.jasper.server.jspServlet.servicejjspfile(jspServlet.java:385)org.apache.jasper.server.jspServlet.service(

共有1个答案

仲孙小云
2023-03-14

我认为如果在Servlet中这样做会更好。

看看这里,我将给出一个基本示例,它将从html表单中获取参数,并在servlet中进行操作,如:

`@WebServlet("/Servlet")
    public class Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        RequestDispatcher requestDispatcher;

        String from = request.getParameter("sender");
        String password = request.getParameter("pass");
        String to = request.getParameter("receiver");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");

        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.port", "587");

        if (from.contains("hotmail")) {
            properties.put("mail.smtp.host", "smtp.live.com");

        } else if (from.contains("gmail")) {
            properties.put("mail.smtp.host", "smtp.gmail.com");

        } else if (from.contains("yahoo")) {
            properties.put("mail.smtp.host", "smtp.mail.yahoo.com");

        } else {
            out.println("<h2 style='color:red;'>Unknown domain name!!</h2><br>"
                    + "<p>Please use 'Yahoo or Gmail or Hotmail'</p>");
        }

        Session messageSession = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(from, password);
            }
        });

        try {
            MimeMessage mimeMessage = new MimeMessage(messageSession);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(message);

            Transport.send(mimeMessage);
            requestDispatcher = request.getRequestDispatcher("index.html");
            requestDispatcher.forward(request, response);
            out.println("<h2 style='color:green;'>Message sended successfully.</h2><br>" + "<p>Welldone.</p>");

        } catch (MessagingException e) {
            requestDispatcher = request.getRequestDispatcher("index.html");
            out.println("<h2 style='color:red;'>Fatal Error!!</h2><br>" + "<p>" + e.getMessage() + "</p>");
        }

    }

}
`

和基本HTML表单:

<body>
<h1 align="center">Send Email Form</h1>
<form class="cf" action="Servlet" method="post">
    <div align="center">
        <table>
            <tr>
                <td>From : </td><td><input type="email" name="sender" size="30px" class="input-email"
                    placeholder="Email address"></td>
            </tr>
            <tr>
                <td>Password : </td><td><input type="password" name="pass" size="30px" class="input-email"
                    placeholder="Sender Password"></td>
            </tr>
            <tr>
                <td>To : </td><td><input type="email" name="receiver" size="30px" class="input-email"
                    placeholder="Email address"></td>
            </tr>
            <tr>
                <td>Subject : </td><td><input type="text" name="subject" size="30px" class="input-email"
                    placeholder="Subject"></td>
            </tr>
            <tr>
                <td>Message : </td><td><textarea name="message" id="input-message"
                        class="text" placeholder="Message"></textarea></td>
            </tr>
            <tr>
                <td><input type="submit" value="SEND" class="button">
                </td>
                <td><input type="reset" value="CLEAR" class="button">
                </td>
            </tr>
        </table>
    </div>

</form>
 类似资料:
  • 问题内容: 如何使用curl命令行程序从gmail帐户发送电子邮件? 我尝试了以下方法: 使用file.txt作为电子邮件的内容,但是,当我运行此命令时,出现以下错误: 是否可以从仍由curl托管的个人服务器托管帐户发送电子邮件?这样会使身份验证过程更容易吗? 问题答案: curl –url 'smtps://smtp.gmail.com:465’ –ssl-reqd \ –mail-from '

  • 问题内容: 我正在尝试使用Java发送电子邮件: 我收到错误消息: 此代码可以发送电子邮件吗? 问题答案: 户名+密码不再是推荐的解决方案。这是因为 我尝试了此操作,Gmail向该代码中用作用户名的电子邮件发送了一封电子邮件,其中说我们最近阻止了你的Google帐户的登录尝试,并将我定向到此支持页面:support.google.com/accounts/answer/6010255因此它看起来很

  • 问题内容: 这有点令人困惑,所以请在这里忍受… 我想建立一个系统,使用户可以通过我的网站发送模板化的电子邮件,但实际上并没有使用我的服务器发送它- 它只是打开自己的本地邮件客户端,并准备发送电子邮件。该应用程序将使用预定义的变量填充电子邮件的正文,以节省用户必须自己键入的电子邮件。然后,如果该消息不完全适合其目的,则他们可以根据需要编辑该消息。 我有很多理由希望它通过用户的本地邮件客户端,因此让服

  • 问题内容: 如何使用Python在电子邮件中发送HTML内容?我可以发送简单的文字。 问题答案: 这是一个如何使用替代纯文本版本创建HTML消息的示例:

  • 问题内容: 我已经在ES6中使用React.js构建了一个Web应用程序。我目前要创建一个基本的“联系我们”页面,并希望发送电子邮件。我是React的新手,只是发现我实际上不能使用React本身发送电子邮件。我正在使用,但在将示例代码与我的React文件集成时遇到了一些困难。具体来说,调用是可行的,但是我不知道如何将其链接到我的React前端。 Nodemailer:https://github.

  • 我在EI中的代理服务代码 我希望我可以使用WSO2 EI发送和接收电子邮件。