如何从JSP / servlet发送电子邮件?是否有必要下载一些罐子,或者你可以在没有任何罐子的情况下从JSP / servlets发送电子邮件吗?
我的Java代码是什么样的?
我的HTML代码会是什么样子(如果有的话)?
是否需要多个班级,或者您只能使用一个班级?
答案 0 :(得分:23)
邮件程序逻辑应该放在它自己的独立类中,您可以在任何地方重用它。 JSP文件应仅包含表示逻辑和标记。 Servlet类应该以适当的方式处理请求并调用邮件程序类。以下是您需要采取的步骤:
首先确定您要使用哪个SMTP server,以便能够发送电子邮件。你的ISP之一? Gmail之一?雅虎?网站托管服务商?一个自我维护的?无论如何,请确定此SMTP服务器的主机名,端口,用户名和密码。您将需要此信息。
创建一个普通的vanilla Java类,它使用JavaMail API发送邮件消息。 JavaMail API附带了出色的tutorial和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);
}
}
您可以根据需要将其设为简单或高级。没关系,只要你有一个类可以发送这样的邮件。
现在是JSP的一部分,你提到JSP的原因并不完全清楚,但由于JSP supposed只代表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
/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 = "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);
}
}
}
就是这样。保持简单和干净。每件事都有其明确的职责。
答案 1 :(得分:4)
您可以使用java mail api从类文件发送来自jsp或servlet的邮件。 以下链接将帮助您:
答案 2 :(得分:2)
我正在使用javamail包,它非常好用。上面显示的示例很好,但我可以看到它们没有在外部文件中定义参数(例如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>
然后,您可以使用
从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);
答案 3 :(得分:1)
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>
这是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);
}
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();
}
}
答案 4 :(得分:-1)
这个基本设置运行良好:
将 mail.jar 和 activation.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"%>
<!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。第二个jsp:emailUtility.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(
"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 + ".");
%>
</table>
</body>
</html>
第3。转到以下网址
http://localhost:8080/projectname/emailForm.jsp
<强> 4。如果服务器出现服务器错误,请重新启动服务器。