写一个servlet,使用Java的Socket类来与SMTP服务器通信,实现发送电子邮件
时间: 2024-01-21 16:16:08 浏览: 106
以下是一个使用Java Socket类与SMTP服务器通信并发送电子邮件的Servlet示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendEmailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取邮件相关信息
String toAddress = request.getParameter("toAddress");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
// SMTP服务器信息
String host = "smtp.example.com";
int port = 25;
// 发件人和收件人信息
String fromAddress = "sender@example.com";
String username = "sender@example.com";
String password = "password";
// 建立Socket连接
Socket socket = new Socket(host, port);
// 创建输入输出流
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// 接收服务器欢迎信息
String welcomeMsg = in.readLine();
System.out.println(welcomeMsg);
// 发送EHLO命令
out.println("EHLO " + host);
// 接收服务器回应
String ehloMsg = "";
while ((ehloMsg = in.readLine()) != null) {
System.out.println(ehloMsg);
if (ehloMsg.indexOf("250 ") == 0) {
break;
}
}
// 发送AUTH LOGIN命令
out.println("AUTH LOGIN");
// 接收服务器回应
String authMsg = in.readLine();
System.out.println(authMsg);
// 发送用户名和密码
out.println(new String(Base64.getEncoder().encode(username.getBytes())));
out.println(new String(Base64.getEncoder().encode(password.getBytes())));
// 发送MAIL FROM命令
out.println("MAIL FROM: <" + fromAddress + ">");
// 接收服务器回应
String mailFromMsg = in.readLine();
System.out.println(mailFromMsg);
// 发送RCPT TO命令
out.println("RCPT TO: <" + toAddress + ">");
// 接收服务器回应
String rcptToMsg = in.readLine();
System.out.println(rcptToMsg);
// 发送DATA命令
out.println("DATA");
// 接收服务器回应
String dataMsg = in.readLine();
System.out.println(dataMsg);
// 发送邮件内容
out.println("From: " + fromAddress);
out.println("To: " + toAddress);
out.println("Subject: " + subject);
out.println("");
out.println(message);
out.println(".");
// 接收服务器回应
String sendMsg = in.readLine();
System.out.println(sendMsg);
// 发送QUIT命令
out.println("QUIT");
// 关闭Socket连接
socket.close();
// 返回结果
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Email sent successfully.</h2>");
out.println("</body></html>");
}
}
```
上述代码中,我们建立了一个Socket连接到SMTP服务器,并通过输入输出流发送SMTP命令来完成邮件发送的过程。在实际应用中,我们需要将邮件相关信息从前端表单中获取并传递给Servlet来完成邮件发送的过程。
阅读全文