Java 如何从 jsp/servlet 发送电子邮件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3757442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send an email from jsp/servlet?
提问by mihir.gandhrokiya
How to send an email from JSP/servlet? Is it necessary to download some jars or can you send an email from JSP/servlets without any jars?
如何从 JSP/servlet 发送电子邮件?是否有必要下载一些 jars 或者您可以从没有任何 jars 的 JSP/servlets 发送电子邮件?
What would my Java code look like?
What would my HTML code look like (if any)?
Are multiple classes necessary, or can you use just one class?
我的 Java 代码会是什么样子?
我的 HTML 代码会是什么样子(如果有的话)?
是否需要多个类,或者您可以只使用一个类?
回答by prakash.panjwani
You can send mail from jsp or servlet as we send from class file using java mail api. Here is link which will help you for that:
您可以从 jsp 或 servlet 发送邮件,因为我们使用 java 邮件 API 从类文件发送邮件。这是可以帮助您的链接:
回答by mangia
I'm using javamail package and it works very nice. The samples shown above are good but as I can see they didn't define parameters in external file (for example web.xml) which is recommended...
我正在使用 javamail 包,它工作得非常好。上面显示的示例很好,但正如我所见,它们没有在推荐的外部文件(例如 web.xml)中定义参数...
Imagine that you want to change your email address or SMTP host .. It is much easier to edit web.xml file than 10 servlets where you used mail function. For example add next lines in web.xml
想象一下,您要更改电子邮件地址或 SMTP 主机。编辑 web.xml 文件比使用邮件功能的 10 个 servlet 容易得多。例如在 web.xml 中添加下一行
<context-param>
<param-name>smtp_server</param-name>
<param-value>smtp.blabla.com</param-value></context-param>
Then you can access those parameters from servlet with
然后你可以从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);
回答by BalusC
The mailer logic should go in its own standalone class which you can reuse everywhere. The JSP file should contain presentation logic and markup only. The Servlet class should just process the request the appropriate way and call the mailer class. Here are the steps which you need to take:
邮件程序逻辑应该放在它自己的独立类中,您可以在任何地方重用。JSP 文件应仅包含表示逻辑和标记。Servlet 类应该只以适当的方式处理请求并调用邮件程序类。以下是您需要采取的步骤:
First decide which SMTP serveryou'd like to use so that you would be able to send emails. The one of your ISP? The one of Gmail? Yahoo? Website hosting provider? A self-maintained one? Regardless, figure the hostname, port, username and password of this SMTP server. You're going to need this information.
Create a plain vanilla Java class which uses JavaMail APIto send a mail message. The JavaMail API comes with an excellent tutorialand FAQ. Name the class
Mailer
and give it asend()
method (or whatever you want). Test it using some tester class with amain()
method like this: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 = "[email protected]"; String to = "[email protected]"; String subject = "Interesting news"; String message = "I've got JavaMail to work!"; mailer.send(from, to, subject, message); } }
You can make it as simple or advanced as you want. It doesn't matter, as long as you have a class with which you can send a mail like that.
Now the JSP part, it's not entirely clear why you mentioned JSP, but since a JSP is supposedto represent only HTML, I bet that you'd like to have something like a contact form in a JSP. Here's a kickoff example:
<form action="contact" method="post"> <p>Your email address: <input name="email"></p> <p>Mail subject: <input name="subject"></p> <p>Mail message: <textarea name="message"></textarea></p> <p><input type="submit"><span class="message">${message}</span></p> </form>
Yes, plain simple, just markup/style it whatever way you want.
Now, create a Servlet class which listens on an
url-pattern
of/contact
(the same as the form is submitting to) and implement thedoPost()
method (the same method as the form is using) as follows: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 = "[email protected]"; } 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); } } }
That's it. Keep it simple and clean. Each thing has its own clear responsibilities.
首先决定您要使用哪个SMTP 服务器,以便您能够发送电子邮件。你的ISP之一?Gmail 之一?雅虎?网站托管服务提供商?一个自己维护的?无论如何,计算此 SMTP 服务器的主机名、端口、用户名和密码。你会需要这些信息。
创建一个使用JavaMail API发送邮件消息的普通 Java 类。JavaMail API 附带了一个优秀的教程和常见问题解答。为类命名
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 = "[email protected]"; String to = "[email protected]"; String subject = "Interesting news"; String message = "I've got JavaMail to work!"; mailer.send(from, to, subject, message); } }
您可以根据需要使其变得简单或高级。没关系,只要你有一个可以发送这样的邮件的班级。
现在是 JSP 部分,您为什么提到 JSP 还不是很清楚,但是由于 JSP应该只表示 HTML,我敢打赌您希望在 JSP 中拥有联系表单之类的东西。这是一个启动示例:
<form action="contact" method="post"> <p>Your email address: <input name="email"></p> <p>Mail subject: <input name="subject"></p> <p>Mail message: <textarea name="message"></textarea></p> <p><input type="submit"><span class="message">${message}</span></p> </form>
是的,简单明了,只需按您想要的方式标记/设置样式即可。
现在,创建一个 Servlet 类,它侦听
url-pattern
of/contact
(与提交的表单相同)并实现该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 = "[email protected]"; } 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); } } }
就是这样。保持简单和干净。每件事都有自己明确的职责。
回答by Hareesh
JSP page:
JSP页面:
<form action="mail.do" method="POST">
<table>
<tr>
<td>To Email-id :<input type="text" name="email" /></td> <!--enter the email whom to send mail -->
<td><input type="submit" value="send"></input></td>
</tr>
</table>
</form>
Here's the Servlet code:
这是 Servlet 代码:
String uri=req.getRequestURI();
if(uri.equals("/mail.do"))
{
SendEmail sa=new SendEmail();
String to_mail=request.getParameter("email");
String body="<html><body><table width=100%><tr><td>Hi this is Test mail</td></tr></table></body></html>";
sa.SendingEmail(to_email,body);
}
And the SendEmail class:
和 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();
}
}
回答by Smug
This basic setup worked fine:
这个基本设置工作正常:
Import mail.jarand activation.jarinto WEB_INF/libfolder inside the project.
将mail.jar和activation.jar导入到项目内的WEB_INF/lib文件夹中。
get mail.jarfrom JavaMail(latest version from official site).
从JavaMail获取mail.jar (来自官方网站的最新版本)。
get activation.jarfrom http://www.oracle.com/technetwork/java/javase/jaf-136260.html
从http://www.oracle.com/technetwork/java/javase/jaf-136260.html获取activation.jar
1. First jsp : emailForm.jsp
1. 第一个jsp:emailForm.jsp
This is a form used to pass the Sender,Receiver Details,Subject and Message content to the emailUtility
这是用于将发件人、收件人详细信息、主题和消息内容传递给 emailUtility 的表单
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send email</title>
</head>
<body>
<form action="emailUtility.jsp" method="post">
<table border="0" width="35%" align="center">
<caption><h2>Send email using SMTP</h2></caption>
<tr>
<td width="50%">Sender address </td>
<td><input type="text" name="from" size="50"/></td>
</tr>
<tr>
<td width="50%">Recipient address </td>
<td><input type="text" name="to" size="50"/></td>
</tr>
<tr>
<td>Subject </td>
<td><input type="text" name="subject" size="50"/></td>
</tr>
<tr>
<td>Message Text </td>
<td><input type="text" name="messageText"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send"/></td>
</tr>
</table>
</form>
</body>
</html>
2. Second jsp : emailUtility.jsp
2. 第二个jsp:emailUtility.jsp
This is the form action mentioned in the previous jsp(emailForm.jsp).
这就是前面jsp(emailForm.jsp)中提到的表单动作。
<html>
<head>
<title>email utility</title>
</head>
<body>
<%@ 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(
"[email protected]", "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 + ".");
%>
</table>
</body>
</html>
3. Go to the following URL
3.转到以下网址
http://localhost:8080/projectname/emailForm.jsp
http://localhost:8080/projectname/emailForm.jsp
4. Restart the server if it gives u server error.
4. 如果出现服务器错误,请重新启动服务器。